Fix PR15296
[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 "Utils/X86ShuffleDecode.h"
18 #include "X86.h"
19 #include "X86InstrBuilder.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/VariadicFunction.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/Function.h"
37 #include "llvm/IR/GlobalAlias.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/LLVMContext.h"
42 #include "llvm/MC/MCAsmInfo.h"
43 #include "llvm/MC/MCContext.h"
44 #include "llvm/MC/MCExpr.h"
45 #include "llvm/MC/MCSymbol.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   // If the input is a buildvector just emit a smaller one.
89   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
90     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
91                        Vec->op_begin()+NormalizedIdxVal, ElemsPerChunk);
92
93   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
94   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
95                                VecIdx);
96
97   return Result;
98 }
99
100 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
101 /// sets things up to match to an AVX VINSERTF128 instruction or a
102 /// simple superregister reference.  Idx is an index in the 128 bits
103 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering INSERT_VECTOR_ELT operations easier.
105 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
106                                   unsigned IdxVal, SelectionDAG &DAG,
107                                   DebugLoc dl) {
108   // Inserting UNDEF is Result
109   if (Vec.getOpcode() == ISD::UNDEF)
110     return Result;
111
112   EVT VT = Vec.getValueType();
113   assert(VT.is128BitVector() && "Unexpected vector size!");
114
115   EVT ElVT = VT.getVectorElementType();
116   EVT ResultVT = Result.getValueType();
117
118   // Insert the relevant 128 bits.
119   unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
120
121   // This is the index of the first element of the 128-bit chunk
122   // we want.
123   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
124                                * ElemsPerChunk);
125
126   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
127   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
128                      VecIdx);
129 }
130
131 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
132 /// instructions. This is used because creating CONCAT_VECTOR nodes of
133 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
134 /// large BUILD_VECTORS.
135 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
136                                    unsigned NumElems, SelectionDAG &DAG,
137                                    DebugLoc dl) {
138   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
139   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
140 }
141
142 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
143   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
144   bool is64Bit = Subtarget->is64Bit();
145
146   if (Subtarget->isTargetEnvMacho()) {
147     if (is64Bit)
148       return new X86_64MachoTargetObjectFile();
149     return new TargetLoweringObjectFileMachO();
150   }
151
152   if (Subtarget->isTargetLinux())
153     return new X86LinuxTargetObjectFile();
154   if (Subtarget->isTargetELF())
155     return new TargetLoweringObjectFileELF();
156   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
157     return new TargetLoweringObjectFileCOFF();
158   llvm_unreachable("unknown subtarget type");
159 }
160
161 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
162   : TargetLowering(TM, createTLOF(TM)) {
163   Subtarget = &TM.getSubtarget<X86Subtarget>();
164   X86ScalarSSEf64 = Subtarget->hasSSE2();
165   X86ScalarSSEf32 = Subtarget->hasSSE1();
166
167   RegInfo = TM.getRegisterInfo();
168   TD = getDataLayout();
169
170   // Set up the TargetLowering object.
171   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
172
173   // X86 is weird, it always uses i8 for shift amounts and setcc results.
174   setBooleanContents(ZeroOrOneBooleanContent);
175   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
176   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
177
178   // For 64-bit since we have so many registers use the ILP scheduler, for
179   // 32-bit code use the register pressure specific scheduling.
180   // For Atom, always use ILP scheduling.
181   if (Subtarget->isAtom())
182     setSchedulingPreference(Sched::ILP);
183   else if (Subtarget->is64Bit())
184     setSchedulingPreference(Sched::ILP);
185   else
186     setSchedulingPreference(Sched::RegPressure);
187   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
188
189   // Bypass expensive divides on Atom when compiling with O2
190   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
191     addBypassSlowDiv(32, 8);
192     if (Subtarget->is64Bit())
193       addBypassSlowDiv(64, 16);
194   }
195
196   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
197     // Setup Windows compiler runtime calls.
198     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
199     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
200     setLibcallName(RTLIB::SREM_I64, "_allrem");
201     setLibcallName(RTLIB::UREM_I64, "_aullrem");
202     setLibcallName(RTLIB::MUL_I64, "_allmul");
203     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208
209     // The _ftol2 runtime function has an unusual calling conv, which
210     // is modeled by a special pseudo-instruction.
211     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
212     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
213     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
214     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
215   }
216
217   if (Subtarget->isTargetDarwin()) {
218     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
219     setUseUnderscoreSetJmp(false);
220     setUseUnderscoreLongJmp(false);
221   } else if (Subtarget->isTargetMingw()) {
222     // MS runtime is weird: it exports _setjmp, but longjmp!
223     setUseUnderscoreSetJmp(true);
224     setUseUnderscoreLongJmp(false);
225   } else {
226     setUseUnderscoreSetJmp(true);
227     setUseUnderscoreLongJmp(true);
228   }
229
230   // Set up the register classes.
231   addRegisterClass(MVT::i8, &X86::GR8RegClass);
232   addRegisterClass(MVT::i16, &X86::GR16RegClass);
233   addRegisterClass(MVT::i32, &X86::GR32RegClass);
234   if (Subtarget->is64Bit())
235     addRegisterClass(MVT::i64, &X86::GR64RegClass);
236
237   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
238
239   // We don't accept any truncstore of integer registers.
240   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
241   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
242   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
243   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
244   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
245   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
246
247   // SETOEQ and SETUNE require checking two conditions.
248   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
249   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
250   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
251   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
252   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
253   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
254
255   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
256   // operation.
257   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
258   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
259   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
260
261   if (Subtarget->is64Bit()) {
262     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
263     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
264   } else if (!TM.Options.UseSoftFloat) {
265     // We have an algorithm for SSE2->double, and we turn this into a
266     // 64-bit FILD followed by conditional FADD for other targets.
267     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
268     // We have an algorithm for SSE2, and we turn this into a 64-bit
269     // FILD for other targets.
270     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
271   }
272
273   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
274   // this operation.
275   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
276   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
277
278   if (!TM.Options.UseSoftFloat) {
279     // SSE has no i16 to fp conversion, only i32
280     if (X86ScalarSSEf32) {
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
282       // f32 and f64 cases are Legal, f80 case is not
283       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
284     } else {
285       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
286       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
287     }
288   } else {
289     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
290     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
291   }
292
293   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
294   // are Legal, f80 is custom lowered.
295   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
296   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
297
298   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
299   // this operation.
300   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
301   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
302
303   if (X86ScalarSSEf32) {
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
305     // f32 and f64 cases are Legal, f80 case is not
306     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
307   } else {
308     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
309     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
310   }
311
312   // Handle FP_TO_UINT by promoting the destination to a larger signed
313   // conversion.
314   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
315   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
316   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
317
318   if (Subtarget->is64Bit()) {
319     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
320     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
321   } else if (!TM.Options.UseSoftFloat) {
322     // Since AVX is a superset of SSE3, only check for SSE here.
323     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
324       // Expand FP_TO_UINT into a select.
325       // FIXME: We would like to use a Custom expander here eventually to do
326       // the optimal thing for SSE vs. the default expansion in the legalizer.
327       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
328     else
329       // With SSE3 we can use fisttpll to convert to a signed i64; without
330       // SSE, we're stuck with a fistpll.
331       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
332   }
333
334   if (isTargetFTOL()) {
335     // Use the _ftol2 runtime function, which has a pseudo-instruction
336     // to handle its weird calling convention.
337     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
338   }
339
340   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
341   if (!X86ScalarSSEf64) {
342     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
343     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
344     if (Subtarget->is64Bit()) {
345       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
346       // Without SSE, i64->f64 goes through memory.
347       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
348     }
349   }
350
351   // Scalar integer divide and remainder are lowered to use operations that
352   // produce two results, to match the available instructions. This exposes
353   // the two-result form to trivial CSE, which is able to combine x/y and x%y
354   // into a single instruction.
355   //
356   // Scalar integer multiply-high is also lowered to use two-result
357   // operations, to match the available instructions. However, plain multiply
358   // (low) operations are left as Legal, as there are single-result
359   // instructions for this in x86. Using the two-result multiply instructions
360   // when both high and low results are needed must be arranged by dagcombine.
361   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
362     MVT VT = IntVTs[i];
363     setOperationAction(ISD::MULHS, VT, Expand);
364     setOperationAction(ISD::MULHU, VT, Expand);
365     setOperationAction(ISD::SDIV, VT, Expand);
366     setOperationAction(ISD::UDIV, VT, Expand);
367     setOperationAction(ISD::SREM, VT, Expand);
368     setOperationAction(ISD::UREM, VT, Expand);
369
370     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
371     setOperationAction(ISD::ADDC, VT, Custom);
372     setOperationAction(ISD::ADDE, VT, Custom);
373     setOperationAction(ISD::SUBC, VT, Custom);
374     setOperationAction(ISD::SUBE, VT, Custom);
375   }
376
377   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
378   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
379   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
380   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
381   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
382   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
383   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
384   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
385   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
386   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
387   if (Subtarget->is64Bit())
388     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
389   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
390   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
391   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
392   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
393   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
394   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
395   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
396   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
397
398   // Promote the i8 variants and force them on up to i32 which has a shorter
399   // encoding.
400   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
401   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
402   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
403   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
404   if (Subtarget->hasBMI()) {
405     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
406     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
407     if (Subtarget->is64Bit())
408       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
409   } else {
410     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
411     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
412     if (Subtarget->is64Bit())
413       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
414   }
415
416   if (Subtarget->hasLZCNT()) {
417     // When promoting the i8 variants, force them to i32 for a shorter
418     // encoding.
419     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
420     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
421     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
422     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
423     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
424     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
425     if (Subtarget->is64Bit())
426       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
427   } else {
428     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
429     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
430     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
431     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
432     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
433     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
434     if (Subtarget->is64Bit()) {
435       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
436       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
437     }
438   }
439
440   if (Subtarget->hasPOPCNT()) {
441     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
442   } else {
443     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
444     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
445     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
446     if (Subtarget->is64Bit())
447       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
448   }
449
450   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
451   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
452
453   // These should be promoted to a larger select which is supported.
454   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
455   // X86 wants to expand cmov itself.
456   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
457   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
458   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
459   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
460   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
461   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
462   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
463   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
464   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
465   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
466   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
467   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
468   if (Subtarget->is64Bit()) {
469     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
470     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
471   }
472   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
473   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
474   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
475   // support continuation, user-level threading, and etc.. As a result, no
476   // other SjLj exception interfaces are implemented and please don't build
477   // your own exception handling based on them.
478   // LLVM/Clang supports zero-cost DWARF exception handling.
479   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
480   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
481
482   // Darwin ABI issue.
483   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
484   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
485   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
486   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
487   if (Subtarget->is64Bit())
488     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
489   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
490   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
491   if (Subtarget->is64Bit()) {
492     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
493     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
494     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
495     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
496     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
497   }
498   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
499   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
500   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
501   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
502   if (Subtarget->is64Bit()) {
503     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
504     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
505     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
506   }
507
508   if (Subtarget->hasSSE1())
509     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
510
511   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
512   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
513
514   // On X86 and X86-64, atomic operations are lowered to locked instructions.
515   // Locked instructions, in turn, have implicit fence semantics (all memory
516   // operations are flushed before issuing the locked instruction, and they
517   // are not buffered), so we can fold away the common pattern of
518   // fence-atomic-fence.
519   setShouldFoldAtomicFences(true);
520
521   // Expand certain atomics
522   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
523     MVT VT = IntVTs[i];
524     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
526     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
527   }
528
529   if (!Subtarget->is64Bit()) {
530     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
531     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
532     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
533     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
534     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
535     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
536     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
537     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
538     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
539     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
540     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
541     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
542   }
543
544   if (Subtarget->hasCmpxchg16b()) {
545     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
546   }
547
548   // FIXME - use subtarget debug flags
549   if (!Subtarget->isTargetDarwin() &&
550       !Subtarget->isTargetELF() &&
551       !Subtarget->isTargetCygMing()) {
552     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
553   }
554
555   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
556   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
557   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
558   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
559   if (Subtarget->is64Bit()) {
560     setExceptionPointerRegister(X86::RAX);
561     setExceptionSelectorRegister(X86::RDX);
562   } else {
563     setExceptionPointerRegister(X86::EAX);
564     setExceptionSelectorRegister(X86::EDX);
565   }
566   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
567   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
568
569   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
570   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
571
572   setOperationAction(ISD::TRAP, MVT::Other, Legal);
573   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
574
575   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
576   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
577   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
578   if (Subtarget->is64Bit()) {
579     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
580     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
581   } else {
582     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
583     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
584   }
585
586   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
587   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
588
589   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
590     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
591                        MVT::i64 : MVT::i32, Custom);
592   else if (TM.Options.EnableSegmentedStacks)
593     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
594                        MVT::i64 : MVT::i32, Custom);
595   else
596     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
597                        MVT::i64 : MVT::i32, Expand);
598
599   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
600     // f32 and f64 use SSE.
601     // Set up the FP register classes.
602     addRegisterClass(MVT::f32, &X86::FR32RegClass);
603     addRegisterClass(MVT::f64, &X86::FR64RegClass);
604
605     // Use ANDPD to simulate FABS.
606     setOperationAction(ISD::FABS , MVT::f64, Custom);
607     setOperationAction(ISD::FABS , MVT::f32, Custom);
608
609     // Use XORP to simulate FNEG.
610     setOperationAction(ISD::FNEG , MVT::f64, Custom);
611     setOperationAction(ISD::FNEG , MVT::f32, Custom);
612
613     // Use ANDPD and ORPD to simulate FCOPYSIGN.
614     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
615     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
616
617     // Lower this to FGETSIGNx86 plus an AND.
618     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
619     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
620
621     // We don't support sin/cos/fmod
622     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
623     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
624     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
625     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
626     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
627     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
628
629     // Expand FP immediates into loads from the stack, except for the special
630     // cases we handle.
631     addLegalFPImmediate(APFloat(+0.0)); // xorpd
632     addLegalFPImmediate(APFloat(+0.0f)); // xorps
633   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
634     // Use SSE for f32, x87 for f64.
635     // Set up the FP register classes.
636     addRegisterClass(MVT::f32, &X86::FR32RegClass);
637     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
638
639     // Use ANDPS to simulate FABS.
640     setOperationAction(ISD::FABS , MVT::f32, Custom);
641
642     // Use XORP to simulate FNEG.
643     setOperationAction(ISD::FNEG , MVT::f32, Custom);
644
645     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
646
647     // Use ANDPS and ORPS to simulate FCOPYSIGN.
648     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
649     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
650
651     // We don't support sin/cos/fmod
652     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
653     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
654     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
655
656     // Special cases we handle for FP constants.
657     addLegalFPImmediate(APFloat(+0.0f)); // xorps
658     addLegalFPImmediate(APFloat(+0.0)); // FLD0
659     addLegalFPImmediate(APFloat(+1.0)); // FLD1
660     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
661     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
662
663     if (!TM.Options.UnsafeFPMath) {
664       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
665       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
666       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
667     }
668   } else if (!TM.Options.UseSoftFloat) {
669     // f32 and f64 in x87.
670     // Set up the FP register classes.
671     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
672     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
673
674     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
675     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
676     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
677     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
678
679     if (!TM.Options.UnsafeFPMath) {
680       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
681       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
682       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
683       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
684       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
685       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
686     }
687     addLegalFPImmediate(APFloat(+0.0)); // FLD0
688     addLegalFPImmediate(APFloat(+1.0)); // FLD1
689     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
690     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
691     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
692     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
693     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
694     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
695   }
696
697   // We don't support FMA.
698   setOperationAction(ISD::FMA, MVT::f64, Expand);
699   setOperationAction(ISD::FMA, MVT::f32, Expand);
700
701   // Long double always uses X87.
702   if (!TM.Options.UseSoftFloat) {
703     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
704     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
705     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
706     {
707       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
708       addLegalFPImmediate(TmpFlt);  // FLD0
709       TmpFlt.changeSign();
710       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
711
712       bool ignored;
713       APFloat TmpFlt2(+1.0);
714       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
715                       &ignored);
716       addLegalFPImmediate(TmpFlt2);  // FLD1
717       TmpFlt2.changeSign();
718       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
719     }
720
721     if (!TM.Options.UnsafeFPMath) {
722       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
723       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
724       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
725     }
726
727     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
728     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
729     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
730     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
731     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
732     setOperationAction(ISD::FMA, MVT::f80, Expand);
733   }
734
735   // Always use a library call for pow.
736   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
737   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
738   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
739
740   setOperationAction(ISD::FLOG, MVT::f80, Expand);
741   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
742   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
743   setOperationAction(ISD::FEXP, MVT::f80, Expand);
744   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
745
746   // First set operation action for all vector types to either promote
747   // (for widening) or expand (for scalarization). Then we will selectively
748   // turn on ones that can be effectively codegen'd.
749   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
750            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
751     MVT VT = (MVT::SimpleValueType)i;
752     setOperationAction(ISD::ADD , VT, Expand);
753     setOperationAction(ISD::SUB , VT, Expand);
754     setOperationAction(ISD::FADD, VT, Expand);
755     setOperationAction(ISD::FNEG, VT, Expand);
756     setOperationAction(ISD::FSUB, VT, Expand);
757     setOperationAction(ISD::MUL , VT, Expand);
758     setOperationAction(ISD::FMUL, VT, Expand);
759     setOperationAction(ISD::SDIV, VT, Expand);
760     setOperationAction(ISD::UDIV, VT, Expand);
761     setOperationAction(ISD::FDIV, VT, Expand);
762     setOperationAction(ISD::SREM, VT, Expand);
763     setOperationAction(ISD::UREM, VT, Expand);
764     setOperationAction(ISD::LOAD, VT, Expand);
765     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
766     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
767     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
768     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
769     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
770     setOperationAction(ISD::FABS, VT, Expand);
771     setOperationAction(ISD::FSIN, VT, Expand);
772     setOperationAction(ISD::FSINCOS, VT, Expand);
773     setOperationAction(ISD::FCOS, VT, Expand);
774     setOperationAction(ISD::FSINCOS, VT, Expand);
775     setOperationAction(ISD::FREM, VT, Expand);
776     setOperationAction(ISD::FMA,  VT, Expand);
777     setOperationAction(ISD::FPOWI, VT, Expand);
778     setOperationAction(ISD::FSQRT, VT, Expand);
779     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
780     setOperationAction(ISD::FFLOOR, VT, Expand);
781     setOperationAction(ISD::FCEIL, VT, Expand);
782     setOperationAction(ISD::FTRUNC, VT, Expand);
783     setOperationAction(ISD::FRINT, VT, Expand);
784     setOperationAction(ISD::FNEARBYINT, VT, Expand);
785     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
786     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
787     setOperationAction(ISD::SDIVREM, VT, Expand);
788     setOperationAction(ISD::UDIVREM, VT, Expand);
789     setOperationAction(ISD::FPOW, VT, Expand);
790     setOperationAction(ISD::CTPOP, VT, Expand);
791     setOperationAction(ISD::CTTZ, VT, Expand);
792     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
793     setOperationAction(ISD::CTLZ, VT, Expand);
794     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
795     setOperationAction(ISD::SHL, VT, Expand);
796     setOperationAction(ISD::SRA, VT, Expand);
797     setOperationAction(ISD::SRL, VT, Expand);
798     setOperationAction(ISD::ROTL, VT, Expand);
799     setOperationAction(ISD::ROTR, VT, Expand);
800     setOperationAction(ISD::BSWAP, VT, Expand);
801     setOperationAction(ISD::SETCC, VT, Expand);
802     setOperationAction(ISD::FLOG, VT, Expand);
803     setOperationAction(ISD::FLOG2, VT, Expand);
804     setOperationAction(ISD::FLOG10, VT, Expand);
805     setOperationAction(ISD::FEXP, VT, Expand);
806     setOperationAction(ISD::FEXP2, VT, Expand);
807     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
808     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
809     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
810     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
811     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
812     setOperationAction(ISD::TRUNCATE, VT, Expand);
813     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
814     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
815     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
816     setOperationAction(ISD::VSELECT, VT, Expand);
817     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
818              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
819       setTruncStoreAction(VT,
820                           (MVT::SimpleValueType)InnerVT, Expand);
821     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
822     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
823     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
824   }
825
826   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
827   // with -msoft-float, disable use of MMX as well.
828   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
829     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
830     // No operations on x86mmx supported, everything uses intrinsics.
831   }
832
833   // MMX-sized vectors (other than x86mmx) are expected to be expanded
834   // into smaller operations.
835   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
836   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
837   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
838   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
839   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
840   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
841   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
842   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
843   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
844   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
845   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
846   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
847   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
848   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
849   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
850   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
851   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
852   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
853   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
854   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
855   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
856   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
857   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
858   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
859   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
860   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
861   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
862   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
863   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
864
865   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
866     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
867
868     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
869     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
870     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
871     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
872     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
873     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
874     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
875     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
876     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
877     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
878     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
879     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
880   }
881
882   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
883     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
884
885     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
886     // registers cannot be used even for integer operations.
887     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
888     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
889     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
890     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
891
892     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
893     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
894     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
895     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
896     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
897     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
898     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
899     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
900     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
901     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
902     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
903     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
904     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
905     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
906     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
907     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
908     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
909     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
910
911     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
912     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
913     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
914     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
915
916     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
917     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
918     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
919     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
920     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
921
922     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
923     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
924       MVT VT = (MVT::SimpleValueType)i;
925       // Do not attempt to custom lower non-power-of-2 vectors
926       if (!isPowerOf2_32(VT.getVectorNumElements()))
927         continue;
928       // Do not attempt to custom lower non-128-bit vectors
929       if (!VT.is128BitVector())
930         continue;
931       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
932       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
933       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
934     }
935
936     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
937     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
938     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
939     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
940     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
942
943     if (Subtarget->is64Bit()) {
944       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
945       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
946     }
947
948     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
949     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
950       MVT VT = (MVT::SimpleValueType)i;
951
952       // Do not attempt to promote non-128-bit vectors
953       if (!VT.is128BitVector())
954         continue;
955
956       setOperationAction(ISD::AND,    VT, Promote);
957       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
958       setOperationAction(ISD::OR,     VT, Promote);
959       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
960       setOperationAction(ISD::XOR,    VT, Promote);
961       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
962       setOperationAction(ISD::LOAD,   VT, Promote);
963       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
964       setOperationAction(ISD::SELECT, VT, Promote);
965       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
966     }
967
968     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
969
970     // Custom lower v2i64 and v2f64 selects.
971     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
972     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
973     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
974     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
975
976     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
977     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
978
979     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
980     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
981     // As there is no 64-bit GPR available, we need build a special custom
982     // sequence to convert from v2i32 to v2f32.
983     if (!Subtarget->is64Bit())
984       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
985
986     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
987     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
988
989     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
990   }
991
992   if (Subtarget->hasSSE41()) {
993     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
994     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
995     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
996     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
997     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
998     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
999     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1000     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1001     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1002     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1003
1004     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1005     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1006     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1007     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1008     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1009     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1010     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1011     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1012     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1013     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1014
1015     // FIXME: Do we need to handle scalar-to-vector here?
1016     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1017
1018     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1019     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1020     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1021     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1022     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1023
1024     // i8 and i16 vectors are custom , because the source register and source
1025     // source memory operand types are not the same width.  f32 vectors are
1026     // custom since the immediate controlling the insert encodes additional
1027     // information.
1028     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1029     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1030     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1031     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1032
1033     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1034     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1036     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1037
1038     // FIXME: these should be Legal but thats only for the case where
1039     // the index is constant.  For now custom expand to deal with that.
1040     if (Subtarget->is64Bit()) {
1041       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1042       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1043     }
1044   }
1045
1046   if (Subtarget->hasSSE2()) {
1047     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1048     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1049
1050     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1051     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1052
1053     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1054     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1055
1056     // In the customized shift lowering, the legal cases in AVX2 will be
1057     // recognized.
1058     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1059     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1060
1061     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1062     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1063
1064     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1065
1066     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1067     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1068   }
1069
1070   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1071     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1072     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1073     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1074     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1075     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1076     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1077
1078     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1079     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1080     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1081
1082     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1083     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1084     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1085     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1086     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1087     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1088     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1089     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1090     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1091     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1092     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1093     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1094
1095     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1096     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1097     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1098     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1099     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1100     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1101     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1102     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1103     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1104     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1105     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1106     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1107
1108     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1109     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1110
1111     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1112
1113     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1114     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1115     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1116
1117     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1118     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1119     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1120
1121     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1122
1123     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1124     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1125
1126     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1127     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1128
1129     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1130     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1131
1132     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1133
1134     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1135     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1136     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1137     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1138
1139     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1140     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1141     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1142
1143     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1144     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1145     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1146     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1147
1148     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1149     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1150     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1151     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1152     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1153     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1154
1155     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1156       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1157       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1158       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1159       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1160       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1161       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1162     }
1163
1164     if (Subtarget->hasInt256()) {
1165       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1166       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1167       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1168       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1169
1170       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1171       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1172       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1173       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1174
1175       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1176       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1177       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1178       // Don't lower v32i8 because there is no 128-bit byte mul
1179
1180       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1181
1182       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1183     } else {
1184       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1185       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1186       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1187       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1188
1189       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1190       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1191       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1192       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1193
1194       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1195       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1196       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1197       // Don't lower v32i8 because there is no 128-bit byte mul
1198     }
1199
1200     // In the customized shift lowering, the legal cases in AVX2 will be
1201     // recognized.
1202     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1203     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1204
1205     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1206     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1207
1208     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1209
1210     // Custom lower several nodes for 256-bit types.
1211     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1212              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1213       MVT VT = (MVT::SimpleValueType)i;
1214
1215       // Extract subvector is special because the value type
1216       // (result) is 128-bit but the source is 256-bit wide.
1217       if (VT.is128BitVector())
1218         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1219
1220       // Do not attempt to custom lower other non-256-bit vectors
1221       if (!VT.is256BitVector())
1222         continue;
1223
1224       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1225       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1226       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1227       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1228       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1229       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1230       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1231     }
1232
1233     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1234     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1235       MVT VT = (MVT::SimpleValueType)i;
1236
1237       // Do not attempt to promote non-256-bit vectors
1238       if (!VT.is256BitVector())
1239         continue;
1240
1241       setOperationAction(ISD::AND,    VT, Promote);
1242       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1243       setOperationAction(ISD::OR,     VT, Promote);
1244       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1245       setOperationAction(ISD::XOR,    VT, Promote);
1246       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1247       setOperationAction(ISD::LOAD,   VT, Promote);
1248       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1249       setOperationAction(ISD::SELECT, VT, Promote);
1250       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1251     }
1252   }
1253
1254   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1255   // of this type with custom code.
1256   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1257            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1258     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1259                        Custom);
1260   }
1261
1262   // We want to custom lower some of our intrinsics.
1263   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1264   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1265
1266   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1267   // handle type legalization for these operations here.
1268   //
1269   // FIXME: We really should do custom legalization for addition and
1270   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1271   // than generic legalization for 64-bit multiplication-with-overflow, though.
1272   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1273     // Add/Sub/Mul with overflow operations are custom lowered.
1274     MVT VT = IntVTs[i];
1275     setOperationAction(ISD::SADDO, VT, Custom);
1276     setOperationAction(ISD::UADDO, VT, Custom);
1277     setOperationAction(ISD::SSUBO, VT, Custom);
1278     setOperationAction(ISD::USUBO, VT, Custom);
1279     setOperationAction(ISD::SMULO, VT, Custom);
1280     setOperationAction(ISD::UMULO, VT, Custom);
1281   }
1282
1283   // There are no 8-bit 3-address imul/mul instructions
1284   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1285   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1286
1287   if (!Subtarget->is64Bit()) {
1288     // These libcalls are not available in 32-bit.
1289     setLibcallName(RTLIB::SHL_I128, 0);
1290     setLibcallName(RTLIB::SRL_I128, 0);
1291     setLibcallName(RTLIB::SRA_I128, 0);
1292   }
1293
1294   // Combine sin / cos into one node or libcall if possible.
1295   if (Subtarget->hasSinCos()) {
1296     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1297     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1298     if (Subtarget->isTargetDarwin()) {
1299       // For MacOSX, we don't want to the normal expansion of a libcall to
1300       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1301       // traffic.
1302       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1303       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1304     }
1305   }
1306
1307   // We have target-specific dag combine patterns for the following nodes:
1308   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1309   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1310   setTargetDAGCombine(ISD::VSELECT);
1311   setTargetDAGCombine(ISD::SELECT);
1312   setTargetDAGCombine(ISD::SHL);
1313   setTargetDAGCombine(ISD::SRA);
1314   setTargetDAGCombine(ISD::SRL);
1315   setTargetDAGCombine(ISD::OR);
1316   setTargetDAGCombine(ISD::AND);
1317   setTargetDAGCombine(ISD::ADD);
1318   setTargetDAGCombine(ISD::FADD);
1319   setTargetDAGCombine(ISD::FSUB);
1320   setTargetDAGCombine(ISD::FMA);
1321   setTargetDAGCombine(ISD::SUB);
1322   setTargetDAGCombine(ISD::LOAD);
1323   setTargetDAGCombine(ISD::STORE);
1324   setTargetDAGCombine(ISD::ZERO_EXTEND);
1325   setTargetDAGCombine(ISD::ANY_EXTEND);
1326   setTargetDAGCombine(ISD::SIGN_EXTEND);
1327   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1328   setTargetDAGCombine(ISD::TRUNCATE);
1329   setTargetDAGCombine(ISD::SINT_TO_FP);
1330   setTargetDAGCombine(ISD::SETCC);
1331   if (Subtarget->is64Bit())
1332     setTargetDAGCombine(ISD::MUL);
1333   setTargetDAGCombine(ISD::XOR);
1334
1335   computeRegisterProperties();
1336
1337   // On Darwin, -Os means optimize for size without hurting performance,
1338   // do not reduce the limit.
1339   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1340   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1341   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1342   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1343   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1344   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1345   setPrefLoopAlignment(4); // 2^4 bytes.
1346   BenefitFromCodePlacementOpt = true;
1347
1348   // Predictable cmov don't hurt on atom because it's in-order.
1349   PredictableSelectIsExpensive = !Subtarget->isAtom();
1350
1351   setPrefFunctionAlignment(4); // 2^4 bytes.
1352 }
1353
1354 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1355   if (!VT.isVector()) return MVT::i8;
1356   return VT.changeVectorElementTypeToInteger();
1357 }
1358
1359 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1360 /// the desired ByVal argument alignment.
1361 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1362   if (MaxAlign == 16)
1363     return;
1364   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1365     if (VTy->getBitWidth() == 128)
1366       MaxAlign = 16;
1367   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1368     unsigned EltAlign = 0;
1369     getMaxByValAlign(ATy->getElementType(), EltAlign);
1370     if (EltAlign > MaxAlign)
1371       MaxAlign = EltAlign;
1372   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1373     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1374       unsigned EltAlign = 0;
1375       getMaxByValAlign(STy->getElementType(i), EltAlign);
1376       if (EltAlign > MaxAlign)
1377         MaxAlign = EltAlign;
1378       if (MaxAlign == 16)
1379         break;
1380     }
1381   }
1382 }
1383
1384 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1385 /// function arguments in the caller parameter area. For X86, aggregates
1386 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1387 /// are at 4-byte boundaries.
1388 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1389   if (Subtarget->is64Bit()) {
1390     // Max of 8 and alignment of type.
1391     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1392     if (TyAlign > 8)
1393       return TyAlign;
1394     return 8;
1395   }
1396
1397   unsigned Align = 4;
1398   if (Subtarget->hasSSE1())
1399     getMaxByValAlign(Ty, Align);
1400   return Align;
1401 }
1402
1403 /// getOptimalMemOpType - Returns the target specific optimal type for load
1404 /// and store operations as a result of memset, memcpy, and memmove
1405 /// lowering. If DstAlign is zero that means it's safe to destination
1406 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1407 /// means there isn't a need to check it against alignment requirement,
1408 /// probably because the source does not need to be loaded. If 'IsMemset' is
1409 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1410 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1411 /// source is constant so it does not need to be loaded.
1412 /// It returns EVT::Other if the type should be determined using generic
1413 /// target-independent logic.
1414 EVT
1415 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1416                                        unsigned DstAlign, unsigned SrcAlign,
1417                                        bool IsMemset, bool ZeroMemset,
1418                                        bool MemcpyStrSrc,
1419                                        MachineFunction &MF) const {
1420   const Function *F = MF.getFunction();
1421   if ((!IsMemset || ZeroMemset) &&
1422       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1423                                        Attribute::NoImplicitFloat)) {
1424     if (Size >= 16 &&
1425         (Subtarget->isUnalignedMemAccessFast() ||
1426          ((DstAlign == 0 || DstAlign >= 16) &&
1427           (SrcAlign == 0 || SrcAlign >= 16)))) {
1428       if (Size >= 32) {
1429         if (Subtarget->hasInt256())
1430           return MVT::v8i32;
1431         if (Subtarget->hasFp256())
1432           return MVT::v8f32;
1433       }
1434       if (Subtarget->hasSSE2())
1435         return MVT::v4i32;
1436       if (Subtarget->hasSSE1())
1437         return MVT::v4f32;
1438     } else if (!MemcpyStrSrc && Size >= 8 &&
1439                !Subtarget->is64Bit() &&
1440                Subtarget->hasSSE2()) {
1441       // Do not use f64 to lower memcpy if source is string constant. It's
1442       // better to use i32 to avoid the loads.
1443       return MVT::f64;
1444     }
1445   }
1446   if (Subtarget->is64Bit() && Size >= 8)
1447     return MVT::i64;
1448   return MVT::i32;
1449 }
1450
1451 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1452   if (VT == MVT::f32)
1453     return X86ScalarSSEf32;
1454   else if (VT == MVT::f64)
1455     return X86ScalarSSEf64;
1456   return true;
1457 }
1458
1459 bool
1460 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1461   if (Fast)
1462     *Fast = Subtarget->isUnalignedMemAccessFast();
1463   return true;
1464 }
1465
1466 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1467 /// current function.  The returned value is a member of the
1468 /// MachineJumpTableInfo::JTEntryKind enum.
1469 unsigned X86TargetLowering::getJumpTableEncoding() const {
1470   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1471   // symbol.
1472   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1473       Subtarget->isPICStyleGOT())
1474     return MachineJumpTableInfo::EK_Custom32;
1475
1476   // Otherwise, use the normal jump table encoding heuristics.
1477   return TargetLowering::getJumpTableEncoding();
1478 }
1479
1480 const MCExpr *
1481 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1482                                              const MachineBasicBlock *MBB,
1483                                              unsigned uid,MCContext &Ctx) const{
1484   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1485          Subtarget->isPICStyleGOT());
1486   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1487   // entries.
1488   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1489                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1490 }
1491
1492 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1493 /// jumptable.
1494 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1495                                                     SelectionDAG &DAG) const {
1496   if (!Subtarget->is64Bit())
1497     // This doesn't have DebugLoc associated with it, but is not really the
1498     // same as a Register.
1499     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1500   return Table;
1501 }
1502
1503 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1504 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1505 /// MCExpr.
1506 const MCExpr *X86TargetLowering::
1507 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1508                              MCContext &Ctx) const {
1509   // X86-64 uses RIP relative addressing based on the jump table label.
1510   if (Subtarget->isPICStyleRIPRel())
1511     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1512
1513   // Otherwise, the reference is relative to the PIC base.
1514   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1515 }
1516
1517 // FIXME: Why this routine is here? Move to RegInfo!
1518 std::pair<const TargetRegisterClass*, uint8_t>
1519 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1520   const TargetRegisterClass *RRC = 0;
1521   uint8_t Cost = 1;
1522   switch (VT.SimpleTy) {
1523   default:
1524     return TargetLowering::findRepresentativeClass(VT);
1525   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1526     RRC = Subtarget->is64Bit() ?
1527       (const TargetRegisterClass*)&X86::GR64RegClass :
1528       (const TargetRegisterClass*)&X86::GR32RegClass;
1529     break;
1530   case MVT::x86mmx:
1531     RRC = &X86::VR64RegClass;
1532     break;
1533   case MVT::f32: case MVT::f64:
1534   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1535   case MVT::v4f32: case MVT::v2f64:
1536   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1537   case MVT::v4f64:
1538     RRC = &X86::VR128RegClass;
1539     break;
1540   }
1541   return std::make_pair(RRC, Cost);
1542 }
1543
1544 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1545                                                unsigned &Offset) const {
1546   if (!Subtarget->isTargetLinux())
1547     return false;
1548
1549   if (Subtarget->is64Bit()) {
1550     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1551     Offset = 0x28;
1552     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1553       AddressSpace = 256;
1554     else
1555       AddressSpace = 257;
1556   } else {
1557     // %gs:0x14 on i386
1558     Offset = 0x14;
1559     AddressSpace = 256;
1560   }
1561   return true;
1562 }
1563
1564 //===----------------------------------------------------------------------===//
1565 //               Return Value Calling Convention Implementation
1566 //===----------------------------------------------------------------------===//
1567
1568 #include "X86GenCallingConv.inc"
1569
1570 bool
1571 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1572                                   MachineFunction &MF, bool isVarArg,
1573                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1574                         LLVMContext &Context) const {
1575   SmallVector<CCValAssign, 16> RVLocs;
1576   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1577                  RVLocs, Context);
1578   return CCInfo.CheckReturn(Outs, RetCC_X86);
1579 }
1580
1581 SDValue
1582 X86TargetLowering::LowerReturn(SDValue Chain,
1583                                CallingConv::ID CallConv, bool isVarArg,
1584                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1585                                const SmallVectorImpl<SDValue> &OutVals,
1586                                DebugLoc dl, SelectionDAG &DAG) const {
1587   MachineFunction &MF = DAG.getMachineFunction();
1588   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1589
1590   SmallVector<CCValAssign, 16> RVLocs;
1591   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1592                  RVLocs, *DAG.getContext());
1593   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1594
1595   SDValue Flag;
1596   SmallVector<SDValue, 6> RetOps;
1597   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1598   // Operand #1 = Bytes To Pop
1599   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1600                    MVT::i16));
1601
1602   // Copy the result values into the output registers.
1603   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604     CCValAssign &VA = RVLocs[i];
1605     assert(VA.isRegLoc() && "Can only return in registers!");
1606     SDValue ValToCopy = OutVals[i];
1607     EVT ValVT = ValToCopy.getValueType();
1608
1609     // Promote values to the appropriate types
1610     if (VA.getLocInfo() == CCValAssign::SExt)
1611       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1612     else if (VA.getLocInfo() == CCValAssign::ZExt)
1613       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1614     else if (VA.getLocInfo() == CCValAssign::AExt)
1615       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1616     else if (VA.getLocInfo() == CCValAssign::BCvt)
1617       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1618
1619     // If this is x86-64, and we disabled SSE, we can't return FP values,
1620     // or SSE or MMX vectors.
1621     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1622          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1623           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1624       report_fatal_error("SSE register return with SSE disabled");
1625     }
1626     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1627     // llvm-gcc has never done it right and no one has noticed, so this
1628     // should be OK for now.
1629     if (ValVT == MVT::f64 &&
1630         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1631       report_fatal_error("SSE2 register return with SSE2 disabled");
1632
1633     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1634     // the RET instruction and handled by the FP Stackifier.
1635     if (VA.getLocReg() == X86::ST0 ||
1636         VA.getLocReg() == X86::ST1) {
1637       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1638       // change the value to the FP stack register class.
1639       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1640         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1641       RetOps.push_back(ValToCopy);
1642       // Don't emit a copytoreg.
1643       continue;
1644     }
1645
1646     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1647     // which is returned in RAX / RDX.
1648     if (Subtarget->is64Bit()) {
1649       if (ValVT == MVT::x86mmx) {
1650         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1651           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1652           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1653                                   ValToCopy);
1654           // If we don't have SSE2 available, convert to v4f32 so the generated
1655           // register is legal.
1656           if (!Subtarget->hasSSE2())
1657             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1658         }
1659       }
1660     }
1661
1662     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1663     Flag = Chain.getValue(1);
1664     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1665   }
1666
1667   // The x86-64 ABIs require that for returning structs by value we copy
1668   // the sret argument into %rax/%eax (depending on ABI) for the return.
1669   // We saved the argument into a virtual register in the entry block,
1670   // so now we copy the value out and into %rax/%eax.
1671   if (Subtarget->is64Bit() &&
1672       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1673     MachineFunction &MF = DAG.getMachineFunction();
1674     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1675     unsigned Reg = FuncInfo->getSRetReturnReg();
1676     assert(Reg &&
1677            "SRetReturnReg should have been set in LowerFormalArguments().");
1678     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1679
1680     unsigned RetValReg = Subtarget->isTarget64BitILP32() ? X86::EAX : X86::RAX;
1681     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1682     Flag = Chain.getValue(1);
1683
1684     // RAX/EAX now acts like a return value.
1685     RetOps.push_back(DAG.getRegister(RetValReg, MVT::i64));
1686   }
1687
1688   RetOps[0] = Chain;  // Update chain.
1689
1690   // Add the flag if we have it.
1691   if (Flag.getNode())
1692     RetOps.push_back(Flag);
1693
1694   return DAG.getNode(X86ISD::RET_FLAG, dl,
1695                      MVT::Other, &RetOps[0], RetOps.size());
1696 }
1697
1698 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1699   if (N->getNumValues() != 1)
1700     return false;
1701   if (!N->hasNUsesOfValue(1, 0))
1702     return false;
1703
1704   SDValue TCChain = Chain;
1705   SDNode *Copy = *N->use_begin();
1706   if (Copy->getOpcode() == ISD::CopyToReg) {
1707     // If the copy has a glue operand, we conservatively assume it isn't safe to
1708     // perform a tail call.
1709     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1710       return false;
1711     TCChain = Copy->getOperand(0);
1712   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1713     return false;
1714
1715   bool HasRet = false;
1716   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1717        UI != UE; ++UI) {
1718     if (UI->getOpcode() != X86ISD::RET_FLAG)
1719       return false;
1720     HasRet = true;
1721   }
1722
1723   if (!HasRet)
1724     return false;
1725
1726   Chain = TCChain;
1727   return true;
1728 }
1729
1730 MVT
1731 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1732                                             ISD::NodeType ExtendKind) const {
1733   MVT ReturnMVT;
1734   // TODO: Is this also valid on 32-bit?
1735   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1736     ReturnMVT = MVT::i8;
1737   else
1738     ReturnMVT = MVT::i32;
1739
1740   MVT MinVT = getRegisterType(ReturnMVT);
1741   return VT.bitsLT(MinVT) ? MinVT : VT;
1742 }
1743
1744 /// LowerCallResult - Lower the result values of a call into the
1745 /// appropriate copies out of appropriate physical registers.
1746 ///
1747 SDValue
1748 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1749                                    CallingConv::ID CallConv, bool isVarArg,
1750                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1751                                    DebugLoc dl, SelectionDAG &DAG,
1752                                    SmallVectorImpl<SDValue> &InVals) const {
1753
1754   // Assign locations to each value returned by this call.
1755   SmallVector<CCValAssign, 16> RVLocs;
1756   bool Is64Bit = Subtarget->is64Bit();
1757   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1758                  getTargetMachine(), RVLocs, *DAG.getContext());
1759   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1760
1761   // Copy all of the result registers out of their specified physreg.
1762   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1763     CCValAssign &VA = RVLocs[i];
1764     EVT CopyVT = VA.getValVT();
1765
1766     // If this is x86-64, and we disabled SSE, we can't return FP values
1767     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1768         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1769       report_fatal_error("SSE register return with SSE disabled");
1770     }
1771
1772     SDValue Val;
1773
1774     // If this is a call to a function that returns an fp value on the floating
1775     // point stack, we must guarantee the value is popped from the stack, so
1776     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1777     // if the return value is not used. We use the FpPOP_RETVAL instruction
1778     // instead.
1779     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1780       // If we prefer to use the value in xmm registers, copy it out as f80 and
1781       // use a truncate to move it from fp stack reg to xmm reg.
1782       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1783       SDValue Ops[] = { Chain, InFlag };
1784       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1785                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1786       Val = Chain.getValue(0);
1787
1788       // Round the f80 to the right size, which also moves it to the appropriate
1789       // xmm register.
1790       if (CopyVT != VA.getValVT())
1791         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1792                           // This truncation won't change the value.
1793                           DAG.getIntPtrConstant(1));
1794     } else {
1795       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1796                                  CopyVT, InFlag).getValue(1);
1797       Val = Chain.getValue(0);
1798     }
1799     InFlag = Chain.getValue(2);
1800     InVals.push_back(Val);
1801   }
1802
1803   return Chain;
1804 }
1805
1806 //===----------------------------------------------------------------------===//
1807 //                C & StdCall & Fast Calling Convention implementation
1808 //===----------------------------------------------------------------------===//
1809 //  StdCall calling convention seems to be standard for many Windows' API
1810 //  routines and around. It differs from C calling convention just a little:
1811 //  callee should clean up the stack, not caller. Symbols should be also
1812 //  decorated in some fancy way :) It doesn't support any vector arguments.
1813 //  For info on fast calling convention see Fast Calling Convention (tail call)
1814 //  implementation LowerX86_32FastCCCallTo.
1815
1816 /// CallIsStructReturn - Determines whether a call uses struct return
1817 /// semantics.
1818 enum StructReturnType {
1819   NotStructReturn,
1820   RegStructReturn,
1821   StackStructReturn
1822 };
1823 static StructReturnType
1824 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1825   if (Outs.empty())
1826     return NotStructReturn;
1827
1828   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1829   if (!Flags.isSRet())
1830     return NotStructReturn;
1831   if (Flags.isInReg())
1832     return RegStructReturn;
1833   return StackStructReturn;
1834 }
1835
1836 /// ArgsAreStructReturn - Determines whether a function uses struct
1837 /// return semantics.
1838 static StructReturnType
1839 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1840   if (Ins.empty())
1841     return NotStructReturn;
1842
1843   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1844   if (!Flags.isSRet())
1845     return NotStructReturn;
1846   if (Flags.isInReg())
1847     return RegStructReturn;
1848   return StackStructReturn;
1849 }
1850
1851 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1852 /// by "Src" to address "Dst" with size and alignment information specified by
1853 /// the specific parameter attribute. The copy will be passed as a byval
1854 /// function parameter.
1855 static SDValue
1856 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1857                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1858                           DebugLoc dl) {
1859   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1860
1861   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1862                        /*isVolatile*/false, /*AlwaysInline=*/true,
1863                        MachinePointerInfo(), MachinePointerInfo());
1864 }
1865
1866 /// IsTailCallConvention - Return true if the calling convention is one that
1867 /// supports tail call optimization.
1868 static bool IsTailCallConvention(CallingConv::ID CC) {
1869   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1870           CC == CallingConv::HiPE);
1871 }
1872
1873 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1874   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1875     return false;
1876
1877   CallSite CS(CI);
1878   CallingConv::ID CalleeCC = CS.getCallingConv();
1879   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1880     return false;
1881
1882   return true;
1883 }
1884
1885 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1886 /// a tailcall target by changing its ABI.
1887 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1888                                    bool GuaranteedTailCallOpt) {
1889   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1890 }
1891
1892 SDValue
1893 X86TargetLowering::LowerMemArgument(SDValue Chain,
1894                                     CallingConv::ID CallConv,
1895                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1896                                     DebugLoc dl, SelectionDAG &DAG,
1897                                     const CCValAssign &VA,
1898                                     MachineFrameInfo *MFI,
1899                                     unsigned i) const {
1900   // Create the nodes corresponding to a load from this parameter slot.
1901   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1902   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1903                               getTargetMachine().Options.GuaranteedTailCallOpt);
1904   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1905   EVT ValVT;
1906
1907   // If value is passed by pointer we have address passed instead of the value
1908   // itself.
1909   if (VA.getLocInfo() == CCValAssign::Indirect)
1910     ValVT = VA.getLocVT();
1911   else
1912     ValVT = VA.getValVT();
1913
1914   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1915   // changed with more analysis.
1916   // In case of tail call optimization mark all arguments mutable. Since they
1917   // could be overwritten by lowering of arguments in case of a tail call.
1918   if (Flags.isByVal()) {
1919     unsigned Bytes = Flags.getByValSize();
1920     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1921     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1922     return DAG.getFrameIndex(FI, getPointerTy());
1923   } else {
1924     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1925                                     VA.getLocMemOffset(), isImmutable);
1926     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1927     return DAG.getLoad(ValVT, dl, Chain, FIN,
1928                        MachinePointerInfo::getFixedStack(FI),
1929                        false, false, false, 0);
1930   }
1931 }
1932
1933 SDValue
1934 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1935                                         CallingConv::ID CallConv,
1936                                         bool isVarArg,
1937                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1938                                         DebugLoc dl,
1939                                         SelectionDAG &DAG,
1940                                         SmallVectorImpl<SDValue> &InVals)
1941                                           const {
1942   MachineFunction &MF = DAG.getMachineFunction();
1943   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1944
1945   const Function* Fn = MF.getFunction();
1946   if (Fn->hasExternalLinkage() &&
1947       Subtarget->isTargetCygMing() &&
1948       Fn->getName() == "main")
1949     FuncInfo->setForceFramePointer(true);
1950
1951   MachineFrameInfo *MFI = MF.getFrameInfo();
1952   bool Is64Bit = Subtarget->is64Bit();
1953   bool IsWindows = Subtarget->isTargetWindows();
1954   bool IsWin64 = Subtarget->isTargetWin64();
1955
1956   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1957          "Var args not supported with calling convention fastcc, ghc or hipe");
1958
1959   // Assign locations to all of the incoming arguments.
1960   SmallVector<CCValAssign, 16> ArgLocs;
1961   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1962                  ArgLocs, *DAG.getContext());
1963
1964   // Allocate shadow area for Win64
1965   if (IsWin64) {
1966     CCInfo.AllocateStack(32, 8);
1967   }
1968
1969   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1970
1971   unsigned LastVal = ~0U;
1972   SDValue ArgValue;
1973   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1974     CCValAssign &VA = ArgLocs[i];
1975     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1976     // places.
1977     assert(VA.getValNo() != LastVal &&
1978            "Don't support value assigned to multiple locs yet");
1979     (void)LastVal;
1980     LastVal = VA.getValNo();
1981
1982     if (VA.isRegLoc()) {
1983       EVT RegVT = VA.getLocVT();
1984       const TargetRegisterClass *RC;
1985       if (RegVT == MVT::i32)
1986         RC = &X86::GR32RegClass;
1987       else if (Is64Bit && RegVT == MVT::i64)
1988         RC = &X86::GR64RegClass;
1989       else if (RegVT == MVT::f32)
1990         RC = &X86::FR32RegClass;
1991       else if (RegVT == MVT::f64)
1992         RC = &X86::FR64RegClass;
1993       else if (RegVT.is256BitVector())
1994         RC = &X86::VR256RegClass;
1995       else if (RegVT.is128BitVector())
1996         RC = &X86::VR128RegClass;
1997       else if (RegVT == MVT::x86mmx)
1998         RC = &X86::VR64RegClass;
1999       else
2000         llvm_unreachable("Unknown argument type!");
2001
2002       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2003       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2004
2005       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2006       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2007       // right size.
2008       if (VA.getLocInfo() == CCValAssign::SExt)
2009         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2010                                DAG.getValueType(VA.getValVT()));
2011       else if (VA.getLocInfo() == CCValAssign::ZExt)
2012         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2013                                DAG.getValueType(VA.getValVT()));
2014       else if (VA.getLocInfo() == CCValAssign::BCvt)
2015         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2016
2017       if (VA.isExtInLoc()) {
2018         // Handle MMX values passed in XMM regs.
2019         if (RegVT.isVector())
2020           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2021         else
2022           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2023       }
2024     } else {
2025       assert(VA.isMemLoc());
2026       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2027     }
2028
2029     // If value is passed via pointer - do a load.
2030     if (VA.getLocInfo() == CCValAssign::Indirect)
2031       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2032                              MachinePointerInfo(), false, false, false, 0);
2033
2034     InVals.push_back(ArgValue);
2035   }
2036
2037   // The x86-64 ABIs require that for returning structs by value we copy
2038   // the sret argument into %rax/%eax (depending on ABI) for the return.
2039   // Save the argument into a virtual register so that we can access it
2040   // from the return points.
2041   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2042     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2043     unsigned Reg = FuncInfo->getSRetReturnReg();
2044     if (!Reg) {
2045       MVT PtrTy = getPointerTy();
2046       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2047       FuncInfo->setSRetReturnReg(Reg);
2048     }
2049     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2050     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2051   }
2052
2053   unsigned StackSize = CCInfo.getNextStackOffset();
2054   // Align stack specially for tail calls.
2055   if (FuncIsMadeTailCallSafe(CallConv,
2056                              MF.getTarget().Options.GuaranteedTailCallOpt))
2057     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2058
2059   // If the function takes variable number of arguments, make a frame index for
2060   // the start of the first vararg value... for expansion of llvm.va_start.
2061   if (isVarArg) {
2062     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2063                     CallConv != CallingConv::X86_ThisCall)) {
2064       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2065     }
2066     if (Is64Bit) {
2067       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2068
2069       // FIXME: We should really autogenerate these arrays
2070       static const uint16_t GPR64ArgRegsWin64[] = {
2071         X86::RCX, X86::RDX, X86::R8,  X86::R9
2072       };
2073       static const uint16_t GPR64ArgRegs64Bit[] = {
2074         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2075       };
2076       static const uint16_t XMMArgRegs64Bit[] = {
2077         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2078         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2079       };
2080       const uint16_t *GPR64ArgRegs;
2081       unsigned NumXMMRegs = 0;
2082
2083       if (IsWin64) {
2084         // The XMM registers which might contain var arg parameters are shadowed
2085         // in their paired GPR.  So we only need to save the GPR to their home
2086         // slots.
2087         TotalNumIntRegs = 4;
2088         GPR64ArgRegs = GPR64ArgRegsWin64;
2089       } else {
2090         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2091         GPR64ArgRegs = GPR64ArgRegs64Bit;
2092
2093         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2094                                                 TotalNumXMMRegs);
2095       }
2096       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2097                                                        TotalNumIntRegs);
2098
2099       bool NoImplicitFloatOps = Fn->getAttributes().
2100         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2101       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2102              "SSE register cannot be used when SSE is disabled!");
2103       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2104                NoImplicitFloatOps) &&
2105              "SSE register cannot be used when SSE is disabled!");
2106       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2107           !Subtarget->hasSSE1())
2108         // Kernel mode asks for SSE to be disabled, so don't push them
2109         // on the stack.
2110         TotalNumXMMRegs = 0;
2111
2112       if (IsWin64) {
2113         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2114         // Get to the caller-allocated home save location.  Add 8 to account
2115         // for the return address.
2116         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2117         FuncInfo->setRegSaveFrameIndex(
2118           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2119         // Fixup to set vararg frame on shadow area (4 x i64).
2120         if (NumIntRegs < 4)
2121           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2122       } else {
2123         // For X86-64, if there are vararg parameters that are passed via
2124         // registers, then we must store them to their spots on the stack so
2125         // they may be loaded by deferencing the result of va_next.
2126         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2127         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2128         FuncInfo->setRegSaveFrameIndex(
2129           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2130                                false));
2131       }
2132
2133       // Store the integer parameter registers.
2134       SmallVector<SDValue, 8> MemOps;
2135       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2136                                         getPointerTy());
2137       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2138       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2139         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2140                                   DAG.getIntPtrConstant(Offset));
2141         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2142                                      &X86::GR64RegClass);
2143         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2144         SDValue Store =
2145           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2146                        MachinePointerInfo::getFixedStack(
2147                          FuncInfo->getRegSaveFrameIndex(), Offset),
2148                        false, false, 0);
2149         MemOps.push_back(Store);
2150         Offset += 8;
2151       }
2152
2153       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2154         // Now store the XMM (fp + vector) parameter registers.
2155         SmallVector<SDValue, 11> SaveXMMOps;
2156         SaveXMMOps.push_back(Chain);
2157
2158         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2159         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2160         SaveXMMOps.push_back(ALVal);
2161
2162         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2163                                FuncInfo->getRegSaveFrameIndex()));
2164         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2165                                FuncInfo->getVarArgsFPOffset()));
2166
2167         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2168           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2169                                        &X86::VR128RegClass);
2170           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2171           SaveXMMOps.push_back(Val);
2172         }
2173         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2174                                      MVT::Other,
2175                                      &SaveXMMOps[0], SaveXMMOps.size()));
2176       }
2177
2178       if (!MemOps.empty())
2179         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2180                             &MemOps[0], MemOps.size());
2181     }
2182   }
2183
2184   // Some CCs need callee pop.
2185   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2186                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2187     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2188   } else {
2189     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2190     // If this is an sret function, the return should pop the hidden pointer.
2191     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2192         argsAreStructReturn(Ins) == StackStructReturn)
2193       FuncInfo->setBytesToPopOnReturn(4);
2194   }
2195
2196   if (!Is64Bit) {
2197     // RegSaveFrameIndex is X86-64 only.
2198     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2199     if (CallConv == CallingConv::X86_FastCall ||
2200         CallConv == CallingConv::X86_ThisCall)
2201       // fastcc functions can't have varargs.
2202       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2203   }
2204
2205   FuncInfo->setArgumentStackSize(StackSize);
2206
2207   return Chain;
2208 }
2209
2210 SDValue
2211 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2212                                     SDValue StackPtr, SDValue Arg,
2213                                     DebugLoc dl, SelectionDAG &DAG,
2214                                     const CCValAssign &VA,
2215                                     ISD::ArgFlagsTy Flags) const {
2216   unsigned LocMemOffset = VA.getLocMemOffset();
2217   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2218   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2219   if (Flags.isByVal())
2220     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2221
2222   return DAG.getStore(Chain, dl, Arg, PtrOff,
2223                       MachinePointerInfo::getStack(LocMemOffset),
2224                       false, false, 0);
2225 }
2226
2227 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2228 /// optimization is performed and it is required.
2229 SDValue
2230 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2231                                            SDValue &OutRetAddr, SDValue Chain,
2232                                            bool IsTailCall, bool Is64Bit,
2233                                            int FPDiff, DebugLoc dl) const {
2234   // Adjust the Return address stack slot.
2235   EVT VT = getPointerTy();
2236   OutRetAddr = getReturnAddressFrameIndex(DAG);
2237
2238   // Load the "old" Return address.
2239   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2240                            false, false, false, 0);
2241   return SDValue(OutRetAddr.getNode(), 1);
2242 }
2243
2244 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2245 /// optimization is performed and it is required (FPDiff!=0).
2246 static SDValue
2247 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2248                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2249                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2250   // Store the return address to the appropriate stack slot.
2251   if (!FPDiff) return Chain;
2252   // Calculate the new stack slot for the return address.
2253   int NewReturnAddrFI =
2254     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2255   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2256   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2257                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2258                        false, false, 0);
2259   return Chain;
2260 }
2261
2262 SDValue
2263 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2264                              SmallVectorImpl<SDValue> &InVals) const {
2265   SelectionDAG &DAG                     = CLI.DAG;
2266   DebugLoc &dl                          = CLI.DL;
2267   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2268   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2269   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2270   SDValue Chain                         = CLI.Chain;
2271   SDValue Callee                        = CLI.Callee;
2272   CallingConv::ID CallConv              = CLI.CallConv;
2273   bool &isTailCall                      = CLI.IsTailCall;
2274   bool isVarArg                         = CLI.IsVarArg;
2275
2276   MachineFunction &MF = DAG.getMachineFunction();
2277   bool Is64Bit        = Subtarget->is64Bit();
2278   bool IsWin64        = Subtarget->isTargetWin64();
2279   bool IsWindows      = Subtarget->isTargetWindows();
2280   StructReturnType SR = callIsStructReturn(Outs);
2281   bool IsSibcall      = false;
2282
2283   if (MF.getTarget().Options.DisableTailCalls)
2284     isTailCall = false;
2285
2286   if (isTailCall) {
2287     // Check if it's really possible to do a tail call.
2288     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2289                     isVarArg, SR != NotStructReturn,
2290                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2291                     Outs, OutVals, Ins, DAG);
2292
2293     // Sibcalls are automatically detected tailcalls which do not require
2294     // ABI changes.
2295     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2296       IsSibcall = true;
2297
2298     if (isTailCall)
2299       ++NumTailCalls;
2300   }
2301
2302   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2303          "Var args not supported with calling convention fastcc, ghc or hipe");
2304
2305   // Analyze operands of the call, assigning locations to each operand.
2306   SmallVector<CCValAssign, 16> ArgLocs;
2307   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2308                  ArgLocs, *DAG.getContext());
2309
2310   // Allocate shadow area for Win64
2311   if (IsWin64) {
2312     CCInfo.AllocateStack(32, 8);
2313   }
2314
2315   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2316
2317   // Get a count of how many bytes are to be pushed on the stack.
2318   unsigned NumBytes = CCInfo.getNextStackOffset();
2319   if (IsSibcall)
2320     // This is a sibcall. The memory operands are available in caller's
2321     // own caller's stack.
2322     NumBytes = 0;
2323   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2324            IsTailCallConvention(CallConv))
2325     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2326
2327   int FPDiff = 0;
2328   if (isTailCall && !IsSibcall) {
2329     // Lower arguments at fp - stackoffset + fpdiff.
2330     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2331     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2332
2333     FPDiff = NumBytesCallerPushed - NumBytes;
2334
2335     // Set the delta of movement of the returnaddr stackslot.
2336     // But only set if delta is greater than previous delta.
2337     if (FPDiff < X86Info->getTCReturnAddrDelta())
2338       X86Info->setTCReturnAddrDelta(FPDiff);
2339   }
2340
2341   if (!IsSibcall)
2342     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2343
2344   SDValue RetAddrFrIdx;
2345   // Load return address for tail calls.
2346   if (isTailCall && FPDiff)
2347     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2348                                     Is64Bit, FPDiff, dl);
2349
2350   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2351   SmallVector<SDValue, 8> MemOpChains;
2352   SDValue StackPtr;
2353
2354   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2355   // of tail call optimization arguments are handle later.
2356   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2357     CCValAssign &VA = ArgLocs[i];
2358     EVT RegVT = VA.getLocVT();
2359     SDValue Arg = OutVals[i];
2360     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2361     bool isByVal = Flags.isByVal();
2362
2363     // Promote the value if needed.
2364     switch (VA.getLocInfo()) {
2365     default: llvm_unreachable("Unknown loc info!");
2366     case CCValAssign::Full: break;
2367     case CCValAssign::SExt:
2368       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2369       break;
2370     case CCValAssign::ZExt:
2371       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2372       break;
2373     case CCValAssign::AExt:
2374       if (RegVT.is128BitVector()) {
2375         // Special case: passing MMX values in XMM registers.
2376         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2377         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2378         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2379       } else
2380         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2381       break;
2382     case CCValAssign::BCvt:
2383       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2384       break;
2385     case CCValAssign::Indirect: {
2386       // Store the argument.
2387       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2388       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2389       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2390                            MachinePointerInfo::getFixedStack(FI),
2391                            false, false, 0);
2392       Arg = SpillSlot;
2393       break;
2394     }
2395     }
2396
2397     if (VA.isRegLoc()) {
2398       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2399       if (isVarArg && IsWin64) {
2400         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2401         // shadow reg if callee is a varargs function.
2402         unsigned ShadowReg = 0;
2403         switch (VA.getLocReg()) {
2404         case X86::XMM0: ShadowReg = X86::RCX; break;
2405         case X86::XMM1: ShadowReg = X86::RDX; break;
2406         case X86::XMM2: ShadowReg = X86::R8; break;
2407         case X86::XMM3: ShadowReg = X86::R9; break;
2408         }
2409         if (ShadowReg)
2410           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2411       }
2412     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2413       assert(VA.isMemLoc());
2414       if (StackPtr.getNode() == 0)
2415         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2416                                       getPointerTy());
2417       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2418                                              dl, DAG, VA, Flags));
2419     }
2420   }
2421
2422   if (!MemOpChains.empty())
2423     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2424                         &MemOpChains[0], MemOpChains.size());
2425
2426   if (Subtarget->isPICStyleGOT()) {
2427     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2428     // GOT pointer.
2429     if (!isTailCall) {
2430       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2431                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2432     } else {
2433       // If we are tail calling and generating PIC/GOT style code load the
2434       // address of the callee into ECX. The value in ecx is used as target of
2435       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2436       // for tail calls on PIC/GOT architectures. Normally we would just put the
2437       // address of GOT into ebx and then call target@PLT. But for tail calls
2438       // ebx would be restored (since ebx is callee saved) before jumping to the
2439       // target@PLT.
2440
2441       // Note: The actual moving to ECX is done further down.
2442       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2443       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2444           !G->getGlobal()->hasProtectedVisibility())
2445         Callee = LowerGlobalAddress(Callee, DAG);
2446       else if (isa<ExternalSymbolSDNode>(Callee))
2447         Callee = LowerExternalSymbol(Callee, DAG);
2448     }
2449   }
2450
2451   if (Is64Bit && isVarArg && !IsWin64) {
2452     // From AMD64 ABI document:
2453     // For calls that may call functions that use varargs or stdargs
2454     // (prototype-less calls or calls to functions containing ellipsis (...) in
2455     // the declaration) %al is used as hidden argument to specify the number
2456     // of SSE registers used. The contents of %al do not need to match exactly
2457     // the number of registers, but must be an ubound on the number of SSE
2458     // registers used and is in the range 0 - 8 inclusive.
2459
2460     // Count the number of XMM registers allocated.
2461     static const uint16_t XMMArgRegs[] = {
2462       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2463       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2464     };
2465     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2466     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2467            && "SSE registers cannot be used when SSE is disabled");
2468
2469     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2470                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2471   }
2472
2473   // For tail calls lower the arguments to the 'real' stack slot.
2474   if (isTailCall) {
2475     // Force all the incoming stack arguments to be loaded from the stack
2476     // before any new outgoing arguments are stored to the stack, because the
2477     // outgoing stack slots may alias the incoming argument stack slots, and
2478     // the alias isn't otherwise explicit. This is slightly more conservative
2479     // than necessary, because it means that each store effectively depends
2480     // on every argument instead of just those arguments it would clobber.
2481     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2482
2483     SmallVector<SDValue, 8> MemOpChains2;
2484     SDValue FIN;
2485     int FI = 0;
2486     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2487       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2488         CCValAssign &VA = ArgLocs[i];
2489         if (VA.isRegLoc())
2490           continue;
2491         assert(VA.isMemLoc());
2492         SDValue Arg = OutVals[i];
2493         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2494         // Create frame index.
2495         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2496         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2497         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2498         FIN = DAG.getFrameIndex(FI, getPointerTy());
2499
2500         if (Flags.isByVal()) {
2501           // Copy relative to framepointer.
2502           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2503           if (StackPtr.getNode() == 0)
2504             StackPtr = DAG.getCopyFromReg(Chain, dl,
2505                                           RegInfo->getStackRegister(),
2506                                           getPointerTy());
2507           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2508
2509           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2510                                                            ArgChain,
2511                                                            Flags, DAG, dl));
2512         } else {
2513           // Store relative to framepointer.
2514           MemOpChains2.push_back(
2515             DAG.getStore(ArgChain, dl, Arg, FIN,
2516                          MachinePointerInfo::getFixedStack(FI),
2517                          false, false, 0));
2518         }
2519       }
2520     }
2521
2522     if (!MemOpChains2.empty())
2523       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2524                           &MemOpChains2[0], MemOpChains2.size());
2525
2526     // Store the return address to the appropriate stack slot.
2527     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2528                                      getPointerTy(), RegInfo->getSlotSize(),
2529                                      FPDiff, dl);
2530   }
2531
2532   // Build a sequence of copy-to-reg nodes chained together with token chain
2533   // and flag operands which copy the outgoing args into registers.
2534   SDValue InFlag;
2535   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2536     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2537                              RegsToPass[i].second, InFlag);
2538     InFlag = Chain.getValue(1);
2539   }
2540
2541   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2542     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2543     // In the 64-bit large code model, we have to make all calls
2544     // through a register, since the call instruction's 32-bit
2545     // pc-relative offset may not be large enough to hold the whole
2546     // address.
2547   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2548     // If the callee is a GlobalAddress node (quite common, every direct call
2549     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2550     // it.
2551
2552     // We should use extra load for direct calls to dllimported functions in
2553     // non-JIT mode.
2554     const GlobalValue *GV = G->getGlobal();
2555     if (!GV->hasDLLImportLinkage()) {
2556       unsigned char OpFlags = 0;
2557       bool ExtraLoad = false;
2558       unsigned WrapperKind = ISD::DELETED_NODE;
2559
2560       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2561       // external symbols most go through the PLT in PIC mode.  If the symbol
2562       // has hidden or protected visibility, or if it is static or local, then
2563       // we don't need to use the PLT - we can directly call it.
2564       if (Subtarget->isTargetELF() &&
2565           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2566           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2567         OpFlags = X86II::MO_PLT;
2568       } else if (Subtarget->isPICStyleStubAny() &&
2569                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2570                  (!Subtarget->getTargetTriple().isMacOSX() ||
2571                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2572         // PC-relative references to external symbols should go through $stub,
2573         // unless we're building with the leopard linker or later, which
2574         // automatically synthesizes these stubs.
2575         OpFlags = X86II::MO_DARWIN_STUB;
2576       } else if (Subtarget->isPICStyleRIPRel() &&
2577                  isa<Function>(GV) &&
2578                  cast<Function>(GV)->getAttributes().
2579                    hasAttribute(AttributeSet::FunctionIndex,
2580                                 Attribute::NonLazyBind)) {
2581         // If the function is marked as non-lazy, generate an indirect call
2582         // which loads from the GOT directly. This avoids runtime overhead
2583         // at the cost of eager binding (and one extra byte of encoding).
2584         OpFlags = X86II::MO_GOTPCREL;
2585         WrapperKind = X86ISD::WrapperRIP;
2586         ExtraLoad = true;
2587       }
2588
2589       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2590                                           G->getOffset(), OpFlags);
2591
2592       // Add a wrapper if needed.
2593       if (WrapperKind != ISD::DELETED_NODE)
2594         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2595       // Add extra indirection if needed.
2596       if (ExtraLoad)
2597         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2598                              MachinePointerInfo::getGOT(),
2599                              false, false, false, 0);
2600     }
2601   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2602     unsigned char OpFlags = 0;
2603
2604     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2605     // external symbols should go through the PLT.
2606     if (Subtarget->isTargetELF() &&
2607         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2608       OpFlags = X86II::MO_PLT;
2609     } else if (Subtarget->isPICStyleStubAny() &&
2610                (!Subtarget->getTargetTriple().isMacOSX() ||
2611                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2612       // PC-relative references to external symbols should go through $stub,
2613       // unless we're building with the leopard linker or later, which
2614       // automatically synthesizes these stubs.
2615       OpFlags = X86II::MO_DARWIN_STUB;
2616     }
2617
2618     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2619                                          OpFlags);
2620   }
2621
2622   // Returns a chain & a flag for retval copy to use.
2623   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2624   SmallVector<SDValue, 8> Ops;
2625
2626   if (!IsSibcall && isTailCall) {
2627     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2628                            DAG.getIntPtrConstant(0, true), InFlag);
2629     InFlag = Chain.getValue(1);
2630   }
2631
2632   Ops.push_back(Chain);
2633   Ops.push_back(Callee);
2634
2635   if (isTailCall)
2636     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2637
2638   // Add argument registers to the end of the list so that they are known live
2639   // into the call.
2640   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2641     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2642                                   RegsToPass[i].second.getValueType()));
2643
2644   // Add a register mask operand representing the call-preserved registers.
2645   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2646   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2647   assert(Mask && "Missing call preserved mask for calling convention");
2648   Ops.push_back(DAG.getRegisterMask(Mask));
2649
2650   if (InFlag.getNode())
2651     Ops.push_back(InFlag);
2652
2653   if (isTailCall) {
2654     // We used to do:
2655     //// If this is the first return lowered for this function, add the regs
2656     //// to the liveout set for the function.
2657     // This isn't right, although it's probably harmless on x86; liveouts
2658     // should be computed from returns not tail calls.  Consider a void
2659     // function making a tail call to a function returning int.
2660     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2661   }
2662
2663   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2664   InFlag = Chain.getValue(1);
2665
2666   // Create the CALLSEQ_END node.
2667   unsigned NumBytesForCalleeToPush;
2668   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2669                        getTargetMachine().Options.GuaranteedTailCallOpt))
2670     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2671   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2672            SR == StackStructReturn)
2673     // If this is a call to a struct-return function, the callee
2674     // pops the hidden struct pointer, so we have to push it back.
2675     // This is common for Darwin/X86, Linux & Mingw32 targets.
2676     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2677     NumBytesForCalleeToPush = 4;
2678   else
2679     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2680
2681   // Returns a flag for retval copy to use.
2682   if (!IsSibcall) {
2683     Chain = DAG.getCALLSEQ_END(Chain,
2684                                DAG.getIntPtrConstant(NumBytes, true),
2685                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2686                                                      true),
2687                                InFlag);
2688     InFlag = Chain.getValue(1);
2689   }
2690
2691   // Handle result values, copying them out of physregs into vregs that we
2692   // return.
2693   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2694                          Ins, dl, DAG, InVals);
2695 }
2696
2697 //===----------------------------------------------------------------------===//
2698 //                Fast Calling Convention (tail call) implementation
2699 //===----------------------------------------------------------------------===//
2700
2701 //  Like std call, callee cleans arguments, convention except that ECX is
2702 //  reserved for storing the tail called function address. Only 2 registers are
2703 //  free for argument passing (inreg). Tail call optimization is performed
2704 //  provided:
2705 //                * tailcallopt is enabled
2706 //                * caller/callee are fastcc
2707 //  On X86_64 architecture with GOT-style position independent code only local
2708 //  (within module) calls are supported at the moment.
2709 //  To keep the stack aligned according to platform abi the function
2710 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2711 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2712 //  If a tail called function callee has more arguments than the caller the
2713 //  caller needs to make sure that there is room to move the RETADDR to. This is
2714 //  achieved by reserving an area the size of the argument delta right after the
2715 //  original REtADDR, but before the saved framepointer or the spilled registers
2716 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2717 //  stack layout:
2718 //    arg1
2719 //    arg2
2720 //    RETADDR
2721 //    [ new RETADDR
2722 //      move area ]
2723 //    (possible EBP)
2724 //    ESI
2725 //    EDI
2726 //    local1 ..
2727
2728 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2729 /// for a 16 byte align requirement.
2730 unsigned
2731 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2732                                                SelectionDAG& DAG) const {
2733   MachineFunction &MF = DAG.getMachineFunction();
2734   const TargetMachine &TM = MF.getTarget();
2735   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2736   unsigned StackAlignment = TFI.getStackAlignment();
2737   uint64_t AlignMask = StackAlignment - 1;
2738   int64_t Offset = StackSize;
2739   unsigned SlotSize = RegInfo->getSlotSize();
2740   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2741     // Number smaller than 12 so just add the difference.
2742     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2743   } else {
2744     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2745     Offset = ((~AlignMask) & Offset) + StackAlignment +
2746       (StackAlignment-SlotSize);
2747   }
2748   return Offset;
2749 }
2750
2751 /// MatchingStackOffset - Return true if the given stack call argument is
2752 /// already available in the same position (relatively) of the caller's
2753 /// incoming argument stack.
2754 static
2755 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2756                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2757                          const X86InstrInfo *TII) {
2758   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2759   int FI = INT_MAX;
2760   if (Arg.getOpcode() == ISD::CopyFromReg) {
2761     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2762     if (!TargetRegisterInfo::isVirtualRegister(VR))
2763       return false;
2764     MachineInstr *Def = MRI->getVRegDef(VR);
2765     if (!Def)
2766       return false;
2767     if (!Flags.isByVal()) {
2768       if (!TII->isLoadFromStackSlot(Def, FI))
2769         return false;
2770     } else {
2771       unsigned Opcode = Def->getOpcode();
2772       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2773           Def->getOperand(1).isFI()) {
2774         FI = Def->getOperand(1).getIndex();
2775         Bytes = Flags.getByValSize();
2776       } else
2777         return false;
2778     }
2779   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2780     if (Flags.isByVal())
2781       // ByVal argument is passed in as a pointer but it's now being
2782       // dereferenced. e.g.
2783       // define @foo(%struct.X* %A) {
2784       //   tail call @bar(%struct.X* byval %A)
2785       // }
2786       return false;
2787     SDValue Ptr = Ld->getBasePtr();
2788     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2789     if (!FINode)
2790       return false;
2791     FI = FINode->getIndex();
2792   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2793     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2794     FI = FINode->getIndex();
2795     Bytes = Flags.getByValSize();
2796   } else
2797     return false;
2798
2799   assert(FI != INT_MAX);
2800   if (!MFI->isFixedObjectIndex(FI))
2801     return false;
2802   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2803 }
2804
2805 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2806 /// for tail call optimization. Targets which want to do tail call
2807 /// optimization should implement this function.
2808 bool
2809 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2810                                                      CallingConv::ID CalleeCC,
2811                                                      bool isVarArg,
2812                                                      bool isCalleeStructRet,
2813                                                      bool isCallerStructRet,
2814                                                      Type *RetTy,
2815                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2816                                     const SmallVectorImpl<SDValue> &OutVals,
2817                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2818                                                      SelectionDAG &DAG) const {
2819   if (!IsTailCallConvention(CalleeCC) &&
2820       CalleeCC != CallingConv::C)
2821     return false;
2822
2823   // If -tailcallopt is specified, make fastcc functions tail-callable.
2824   const MachineFunction &MF = DAG.getMachineFunction();
2825   const Function *CallerF = DAG.getMachineFunction().getFunction();
2826
2827   // If the function return type is x86_fp80 and the callee return type is not,
2828   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2829   // perform a tailcall optimization here.
2830   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2831     return false;
2832
2833   CallingConv::ID CallerCC = CallerF->getCallingConv();
2834   bool CCMatch = CallerCC == CalleeCC;
2835
2836   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2837     if (IsTailCallConvention(CalleeCC) && CCMatch)
2838       return true;
2839     return false;
2840   }
2841
2842   // Look for obvious safe cases to perform tail call optimization that do not
2843   // require ABI changes. This is what gcc calls sibcall.
2844
2845   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2846   // emit a special epilogue.
2847   if (RegInfo->needsStackRealignment(MF))
2848     return false;
2849
2850   // Also avoid sibcall optimization if either caller or callee uses struct
2851   // return semantics.
2852   if (isCalleeStructRet || isCallerStructRet)
2853     return false;
2854
2855   // An stdcall caller is expected to clean up its arguments; the callee
2856   // isn't going to do that.
2857   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2858     return false;
2859
2860   // Do not sibcall optimize vararg calls unless all arguments are passed via
2861   // registers.
2862   if (isVarArg && !Outs.empty()) {
2863
2864     // Optimizing for varargs on Win64 is unlikely to be safe without
2865     // additional testing.
2866     if (Subtarget->isTargetWin64())
2867       return false;
2868
2869     SmallVector<CCValAssign, 16> ArgLocs;
2870     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2871                    getTargetMachine(), ArgLocs, *DAG.getContext());
2872
2873     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2874     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2875       if (!ArgLocs[i].isRegLoc())
2876         return false;
2877   }
2878
2879   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2880   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2881   // this into a sibcall.
2882   bool Unused = false;
2883   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2884     if (!Ins[i].Used) {
2885       Unused = true;
2886       break;
2887     }
2888   }
2889   if (Unused) {
2890     SmallVector<CCValAssign, 16> RVLocs;
2891     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2892                    getTargetMachine(), RVLocs, *DAG.getContext());
2893     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2894     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2895       CCValAssign &VA = RVLocs[i];
2896       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2897         return false;
2898     }
2899   }
2900
2901   // If the calling conventions do not match, then we'd better make sure the
2902   // results are returned in the same way as what the caller expects.
2903   if (!CCMatch) {
2904     SmallVector<CCValAssign, 16> RVLocs1;
2905     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2906                     getTargetMachine(), RVLocs1, *DAG.getContext());
2907     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2908
2909     SmallVector<CCValAssign, 16> RVLocs2;
2910     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2911                     getTargetMachine(), RVLocs2, *DAG.getContext());
2912     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2913
2914     if (RVLocs1.size() != RVLocs2.size())
2915       return false;
2916     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2917       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2918         return false;
2919       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2920         return false;
2921       if (RVLocs1[i].isRegLoc()) {
2922         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2923           return false;
2924       } else {
2925         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2926           return false;
2927       }
2928     }
2929   }
2930
2931   // If the callee takes no arguments then go on to check the results of the
2932   // call.
2933   if (!Outs.empty()) {
2934     // Check if stack adjustment is needed. For now, do not do this if any
2935     // argument is passed on the stack.
2936     SmallVector<CCValAssign, 16> ArgLocs;
2937     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2938                    getTargetMachine(), ArgLocs, *DAG.getContext());
2939
2940     // Allocate shadow area for Win64
2941     if (Subtarget->isTargetWin64()) {
2942       CCInfo.AllocateStack(32, 8);
2943     }
2944
2945     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2946     if (CCInfo.getNextStackOffset()) {
2947       MachineFunction &MF = DAG.getMachineFunction();
2948       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2949         return false;
2950
2951       // Check if the arguments are already laid out in the right way as
2952       // the caller's fixed stack objects.
2953       MachineFrameInfo *MFI = MF.getFrameInfo();
2954       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2955       const X86InstrInfo *TII =
2956         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2957       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2958         CCValAssign &VA = ArgLocs[i];
2959         SDValue Arg = OutVals[i];
2960         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2961         if (VA.getLocInfo() == CCValAssign::Indirect)
2962           return false;
2963         if (!VA.isRegLoc()) {
2964           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2965                                    MFI, MRI, TII))
2966             return false;
2967         }
2968       }
2969     }
2970
2971     // If the tailcall address may be in a register, then make sure it's
2972     // possible to register allocate for it. In 32-bit, the call address can
2973     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2974     // callee-saved registers are restored. These happen to be the same
2975     // registers used to pass 'inreg' arguments so watch out for those.
2976     if (!Subtarget->is64Bit() &&
2977         ((!isa<GlobalAddressSDNode>(Callee) &&
2978           !isa<ExternalSymbolSDNode>(Callee)) ||
2979          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2980       unsigned NumInRegs = 0;
2981       // In PIC we need an extra register to formulate the address computation
2982       // for the callee.
2983       unsigned MaxInRegs =
2984           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
2985
2986       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2987         CCValAssign &VA = ArgLocs[i];
2988         if (!VA.isRegLoc())
2989           continue;
2990         unsigned Reg = VA.getLocReg();
2991         switch (Reg) {
2992         default: break;
2993         case X86::EAX: case X86::EDX: case X86::ECX:
2994           if (++NumInRegs == MaxInRegs)
2995             return false;
2996           break;
2997         }
2998       }
2999     }
3000   }
3001
3002   return true;
3003 }
3004
3005 FastISel *
3006 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3007                                   const TargetLibraryInfo *libInfo) const {
3008   return X86::createFastISel(funcInfo, libInfo);
3009 }
3010
3011 //===----------------------------------------------------------------------===//
3012 //                           Other Lowering Hooks
3013 //===----------------------------------------------------------------------===//
3014
3015 static bool MayFoldLoad(SDValue Op) {
3016   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3017 }
3018
3019 static bool MayFoldIntoStore(SDValue Op) {
3020   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3021 }
3022
3023 static bool isTargetShuffle(unsigned Opcode) {
3024   switch(Opcode) {
3025   default: return false;
3026   case X86ISD::PSHUFD:
3027   case X86ISD::PSHUFHW:
3028   case X86ISD::PSHUFLW:
3029   case X86ISD::SHUFP:
3030   case X86ISD::PALIGNR:
3031   case X86ISD::MOVLHPS:
3032   case X86ISD::MOVLHPD:
3033   case X86ISD::MOVHLPS:
3034   case X86ISD::MOVLPS:
3035   case X86ISD::MOVLPD:
3036   case X86ISD::MOVSHDUP:
3037   case X86ISD::MOVSLDUP:
3038   case X86ISD::MOVDDUP:
3039   case X86ISD::MOVSS:
3040   case X86ISD::MOVSD:
3041   case X86ISD::UNPCKL:
3042   case X86ISD::UNPCKH:
3043   case X86ISD::VPERMILP:
3044   case X86ISD::VPERM2X128:
3045   case X86ISD::VPERMI:
3046     return true;
3047   }
3048 }
3049
3050 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3051                                     SDValue V1, SelectionDAG &DAG) {
3052   switch(Opc) {
3053   default: llvm_unreachable("Unknown x86 shuffle node");
3054   case X86ISD::MOVSHDUP:
3055   case X86ISD::MOVSLDUP:
3056   case X86ISD::MOVDDUP:
3057     return DAG.getNode(Opc, dl, VT, V1);
3058   }
3059 }
3060
3061 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3062                                     SDValue V1, unsigned TargetMask,
3063                                     SelectionDAG &DAG) {
3064   switch(Opc) {
3065   default: llvm_unreachable("Unknown x86 shuffle node");
3066   case X86ISD::PSHUFD:
3067   case X86ISD::PSHUFHW:
3068   case X86ISD::PSHUFLW:
3069   case X86ISD::VPERMILP:
3070   case X86ISD::VPERMI:
3071     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3072   }
3073 }
3074
3075 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3076                                     SDValue V1, SDValue V2, unsigned TargetMask,
3077                                     SelectionDAG &DAG) {
3078   switch(Opc) {
3079   default: llvm_unreachable("Unknown x86 shuffle node");
3080   case X86ISD::PALIGNR:
3081   case X86ISD::SHUFP:
3082   case X86ISD::VPERM2X128:
3083     return DAG.getNode(Opc, dl, VT, V1, V2,
3084                        DAG.getConstant(TargetMask, MVT::i8));
3085   }
3086 }
3087
3088 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3089                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3090   switch(Opc) {
3091   default: llvm_unreachable("Unknown x86 shuffle node");
3092   case X86ISD::MOVLHPS:
3093   case X86ISD::MOVLHPD:
3094   case X86ISD::MOVHLPS:
3095   case X86ISD::MOVLPS:
3096   case X86ISD::MOVLPD:
3097   case X86ISD::MOVSS:
3098   case X86ISD::MOVSD:
3099   case X86ISD::UNPCKL:
3100   case X86ISD::UNPCKH:
3101     return DAG.getNode(Opc, dl, VT, V1, V2);
3102   }
3103 }
3104
3105 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3106   MachineFunction &MF = DAG.getMachineFunction();
3107   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3108   int ReturnAddrIndex = FuncInfo->getRAIndex();
3109
3110   if (ReturnAddrIndex == 0) {
3111     // Set up a frame object for the return address.
3112     unsigned SlotSize = RegInfo->getSlotSize();
3113     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3114                                                            false);
3115     FuncInfo->setRAIndex(ReturnAddrIndex);
3116   }
3117
3118   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3119 }
3120
3121 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3122                                        bool hasSymbolicDisplacement) {
3123   // Offset should fit into 32 bit immediate field.
3124   if (!isInt<32>(Offset))
3125     return false;
3126
3127   // If we don't have a symbolic displacement - we don't have any extra
3128   // restrictions.
3129   if (!hasSymbolicDisplacement)
3130     return true;
3131
3132   // FIXME: Some tweaks might be needed for medium code model.
3133   if (M != CodeModel::Small && M != CodeModel::Kernel)
3134     return false;
3135
3136   // For small code model we assume that latest object is 16MB before end of 31
3137   // bits boundary. We may also accept pretty large negative constants knowing
3138   // that all objects are in the positive half of address space.
3139   if (M == CodeModel::Small && Offset < 16*1024*1024)
3140     return true;
3141
3142   // For kernel code model we know that all object resist in the negative half
3143   // of 32bits address space. We may not accept negative offsets, since they may
3144   // be just off and we may accept pretty large positive ones.
3145   if (M == CodeModel::Kernel && Offset > 0)
3146     return true;
3147
3148   return false;
3149 }
3150
3151 /// isCalleePop - Determines whether the callee is required to pop its
3152 /// own arguments. Callee pop is necessary to support tail calls.
3153 bool X86::isCalleePop(CallingConv::ID CallingConv,
3154                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3155   if (IsVarArg)
3156     return false;
3157
3158   switch (CallingConv) {
3159   default:
3160     return false;
3161   case CallingConv::X86_StdCall:
3162     return !is64Bit;
3163   case CallingConv::X86_FastCall:
3164     return !is64Bit;
3165   case CallingConv::X86_ThisCall:
3166     return !is64Bit;
3167   case CallingConv::Fast:
3168     return TailCallOpt;
3169   case CallingConv::GHC:
3170     return TailCallOpt;
3171   case CallingConv::HiPE:
3172     return TailCallOpt;
3173   }
3174 }
3175
3176 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3177 /// specific condition code, returning the condition code and the LHS/RHS of the
3178 /// comparison to make.
3179 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3180                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3181   if (!isFP) {
3182     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3183       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3184         // X > -1   -> X == 0, jump !sign.
3185         RHS = DAG.getConstant(0, RHS.getValueType());
3186         return X86::COND_NS;
3187       }
3188       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3189         // X < 0   -> X == 0, jump on sign.
3190         return X86::COND_S;
3191       }
3192       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3193         // X < 1   -> X <= 0
3194         RHS = DAG.getConstant(0, RHS.getValueType());
3195         return X86::COND_LE;
3196       }
3197     }
3198
3199     switch (SetCCOpcode) {
3200     default: llvm_unreachable("Invalid integer condition!");
3201     case ISD::SETEQ:  return X86::COND_E;
3202     case ISD::SETGT:  return X86::COND_G;
3203     case ISD::SETGE:  return X86::COND_GE;
3204     case ISD::SETLT:  return X86::COND_L;
3205     case ISD::SETLE:  return X86::COND_LE;
3206     case ISD::SETNE:  return X86::COND_NE;
3207     case ISD::SETULT: return X86::COND_B;
3208     case ISD::SETUGT: return X86::COND_A;
3209     case ISD::SETULE: return X86::COND_BE;
3210     case ISD::SETUGE: return X86::COND_AE;
3211     }
3212   }
3213
3214   // First determine if it is required or is profitable to flip the operands.
3215
3216   // If LHS is a foldable load, but RHS is not, flip the condition.
3217   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3218       !ISD::isNON_EXTLoad(RHS.getNode())) {
3219     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3220     std::swap(LHS, RHS);
3221   }
3222
3223   switch (SetCCOpcode) {
3224   default: break;
3225   case ISD::SETOLT:
3226   case ISD::SETOLE:
3227   case ISD::SETUGT:
3228   case ISD::SETUGE:
3229     std::swap(LHS, RHS);
3230     break;
3231   }
3232
3233   // On a floating point condition, the flags are set as follows:
3234   // ZF  PF  CF   op
3235   //  0 | 0 | 0 | X > Y
3236   //  0 | 0 | 1 | X < Y
3237   //  1 | 0 | 0 | X == Y
3238   //  1 | 1 | 1 | unordered
3239   switch (SetCCOpcode) {
3240   default: llvm_unreachable("Condcode should be pre-legalized away");
3241   case ISD::SETUEQ:
3242   case ISD::SETEQ:   return X86::COND_E;
3243   case ISD::SETOLT:              // flipped
3244   case ISD::SETOGT:
3245   case ISD::SETGT:   return X86::COND_A;
3246   case ISD::SETOLE:              // flipped
3247   case ISD::SETOGE:
3248   case ISD::SETGE:   return X86::COND_AE;
3249   case ISD::SETUGT:              // flipped
3250   case ISD::SETULT:
3251   case ISD::SETLT:   return X86::COND_B;
3252   case ISD::SETUGE:              // flipped
3253   case ISD::SETULE:
3254   case ISD::SETLE:   return X86::COND_BE;
3255   case ISD::SETONE:
3256   case ISD::SETNE:   return X86::COND_NE;
3257   case ISD::SETUO:   return X86::COND_P;
3258   case ISD::SETO:    return X86::COND_NP;
3259   case ISD::SETOEQ:
3260   case ISD::SETUNE:  return X86::COND_INVALID;
3261   }
3262 }
3263
3264 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3265 /// code. Current x86 isa includes the following FP cmov instructions:
3266 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3267 static bool hasFPCMov(unsigned X86CC) {
3268   switch (X86CC) {
3269   default:
3270     return false;
3271   case X86::COND_B:
3272   case X86::COND_BE:
3273   case X86::COND_E:
3274   case X86::COND_P:
3275   case X86::COND_A:
3276   case X86::COND_AE:
3277   case X86::COND_NE:
3278   case X86::COND_NP:
3279     return true;
3280   }
3281 }
3282
3283 /// isFPImmLegal - Returns true if the target can instruction select the
3284 /// specified FP immediate natively. If false, the legalizer will
3285 /// materialize the FP immediate as a load from a constant pool.
3286 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3287   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3288     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3289       return true;
3290   }
3291   return false;
3292 }
3293
3294 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3295 /// the specified range (L, H].
3296 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3297   return (Val < 0) || (Val >= Low && Val < Hi);
3298 }
3299
3300 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3301 /// specified value.
3302 static bool isUndefOrEqual(int Val, int CmpVal) {
3303   return (Val < 0 || Val == CmpVal);
3304 }
3305
3306 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3307 /// from position Pos and ending in Pos+Size, falls within the specified
3308 /// sequential range (L, L+Pos]. or is undef.
3309 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3310                                        unsigned Pos, unsigned Size, int Low) {
3311   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3312     if (!isUndefOrEqual(Mask[i], Low))
3313       return false;
3314   return true;
3315 }
3316
3317 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3318 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3319 /// the second operand.
3320 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3321   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3322     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3323   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3324     return (Mask[0] < 2 && Mask[1] < 2);
3325   return false;
3326 }
3327
3328 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3329 /// is suitable for input to PSHUFHW.
3330 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3331   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3332     return false;
3333
3334   // Lower quadword copied in order or undef.
3335   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3336     return false;
3337
3338   // Upper quadword shuffled.
3339   for (unsigned i = 4; i != 8; ++i)
3340     if (!isUndefOrInRange(Mask[i], 4, 8))
3341       return false;
3342
3343   if (VT == MVT::v16i16) {
3344     // Lower quadword copied in order or undef.
3345     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3346       return false;
3347
3348     // Upper quadword shuffled.
3349     for (unsigned i = 12; i != 16; ++i)
3350       if (!isUndefOrInRange(Mask[i], 12, 16))
3351         return false;
3352   }
3353
3354   return true;
3355 }
3356
3357 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3358 /// is suitable for input to PSHUFLW.
3359 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3360   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3361     return false;
3362
3363   // Upper quadword copied in order.
3364   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3365     return false;
3366
3367   // Lower quadword shuffled.
3368   for (unsigned i = 0; i != 4; ++i)
3369     if (!isUndefOrInRange(Mask[i], 0, 4))
3370       return false;
3371
3372   if (VT == MVT::v16i16) {
3373     // Upper quadword copied in order.
3374     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3375       return false;
3376
3377     // Lower quadword shuffled.
3378     for (unsigned i = 8; i != 12; ++i)
3379       if (!isUndefOrInRange(Mask[i], 8, 12))
3380         return false;
3381   }
3382
3383   return true;
3384 }
3385
3386 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3387 /// is suitable for input to PALIGNR.
3388 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3389                           const X86Subtarget *Subtarget) {
3390   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3391       (VT.is256BitVector() && !Subtarget->hasInt256()))
3392     return false;
3393
3394   unsigned NumElts = VT.getVectorNumElements();
3395   unsigned NumLanes = VT.getSizeInBits()/128;
3396   unsigned NumLaneElts = NumElts/NumLanes;
3397
3398   // Do not handle 64-bit element shuffles with palignr.
3399   if (NumLaneElts == 2)
3400     return false;
3401
3402   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3403     unsigned i;
3404     for (i = 0; i != NumLaneElts; ++i) {
3405       if (Mask[i+l] >= 0)
3406         break;
3407     }
3408
3409     // Lane is all undef, go to next lane
3410     if (i == NumLaneElts)
3411       continue;
3412
3413     int Start = Mask[i+l];
3414
3415     // Make sure its in this lane in one of the sources
3416     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3417         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3418       return false;
3419
3420     // If not lane 0, then we must match lane 0
3421     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3422       return false;
3423
3424     // Correct second source to be contiguous with first source
3425     if (Start >= (int)NumElts)
3426       Start -= NumElts - NumLaneElts;
3427
3428     // Make sure we're shifting in the right direction.
3429     if (Start <= (int)(i+l))
3430       return false;
3431
3432     Start -= i;
3433
3434     // Check the rest of the elements to see if they are consecutive.
3435     for (++i; i != NumLaneElts; ++i) {
3436       int Idx = Mask[i+l];
3437
3438       // Make sure its in this lane
3439       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3440           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3441         return false;
3442
3443       // If not lane 0, then we must match lane 0
3444       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3445         return false;
3446
3447       if (Idx >= (int)NumElts)
3448         Idx -= NumElts - NumLaneElts;
3449
3450       if (!isUndefOrEqual(Idx, Start+i))
3451         return false;
3452
3453     }
3454   }
3455
3456   return true;
3457 }
3458
3459 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3460 /// the two vector operands have swapped position.
3461 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3462                                      unsigned NumElems) {
3463   for (unsigned i = 0; i != NumElems; ++i) {
3464     int idx = Mask[i];
3465     if (idx < 0)
3466       continue;
3467     else if (idx < (int)NumElems)
3468       Mask[i] = idx + NumElems;
3469     else
3470       Mask[i] = idx - NumElems;
3471   }
3472 }
3473
3474 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3475 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3476 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3477 /// reverse of what x86 shuffles want.
3478 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3479                         bool Commuted = false) {
3480   if (!HasFp256 && VT.is256BitVector())
3481     return false;
3482
3483   unsigned NumElems = VT.getVectorNumElements();
3484   unsigned NumLanes = VT.getSizeInBits()/128;
3485   unsigned NumLaneElems = NumElems/NumLanes;
3486
3487   if (NumLaneElems != 2 && NumLaneElems != 4)
3488     return false;
3489
3490   // VSHUFPSY divides the resulting vector into 4 chunks.
3491   // The sources are also splitted into 4 chunks, and each destination
3492   // chunk must come from a different source chunk.
3493   //
3494   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3495   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3496   //
3497   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3498   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3499   //
3500   // VSHUFPDY divides the resulting vector into 4 chunks.
3501   // The sources are also splitted into 4 chunks, and each destination
3502   // chunk must come from a different source chunk.
3503   //
3504   //  SRC1 =>      X3       X2       X1       X0
3505   //  SRC2 =>      Y3       Y2       Y1       Y0
3506   //
3507   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3508   //
3509   unsigned HalfLaneElems = NumLaneElems/2;
3510   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3511     for (unsigned i = 0; i != NumLaneElems; ++i) {
3512       int Idx = Mask[i+l];
3513       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3514       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3515         return false;
3516       // For VSHUFPSY, the mask of the second half must be the same as the
3517       // first but with the appropriate offsets. This works in the same way as
3518       // VPERMILPS works with masks.
3519       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3520         continue;
3521       if (!isUndefOrEqual(Idx, Mask[i]+l))
3522         return false;
3523     }
3524   }
3525
3526   return true;
3527 }
3528
3529 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3530 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3531 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3532   if (!VT.is128BitVector())
3533     return false;
3534
3535   unsigned NumElems = VT.getVectorNumElements();
3536
3537   if (NumElems != 4)
3538     return false;
3539
3540   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3541   return isUndefOrEqual(Mask[0], 6) &&
3542          isUndefOrEqual(Mask[1], 7) &&
3543          isUndefOrEqual(Mask[2], 2) &&
3544          isUndefOrEqual(Mask[3], 3);
3545 }
3546
3547 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3548 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3549 /// <2, 3, 2, 3>
3550 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3551   if (!VT.is128BitVector())
3552     return false;
3553
3554   unsigned NumElems = VT.getVectorNumElements();
3555
3556   if (NumElems != 4)
3557     return false;
3558
3559   return isUndefOrEqual(Mask[0], 2) &&
3560          isUndefOrEqual(Mask[1], 3) &&
3561          isUndefOrEqual(Mask[2], 2) &&
3562          isUndefOrEqual(Mask[3], 3);
3563 }
3564
3565 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3566 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3567 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3568   if (!VT.is128BitVector())
3569     return false;
3570
3571   unsigned NumElems = VT.getVectorNumElements();
3572
3573   if (NumElems != 2 && NumElems != 4)
3574     return false;
3575
3576   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3577     if (!isUndefOrEqual(Mask[i], i + NumElems))
3578       return false;
3579
3580   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3581     if (!isUndefOrEqual(Mask[i], i))
3582       return false;
3583
3584   return true;
3585 }
3586
3587 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3588 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3589 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3590   if (!VT.is128BitVector())
3591     return false;
3592
3593   unsigned NumElems = VT.getVectorNumElements();
3594
3595   if (NumElems != 2 && NumElems != 4)
3596     return false;
3597
3598   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3599     if (!isUndefOrEqual(Mask[i], i))
3600       return false;
3601
3602   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3603     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3604       return false;
3605
3606   return true;
3607 }
3608
3609 //
3610 // Some special combinations that can be optimized.
3611 //
3612 static
3613 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3614                                SelectionDAG &DAG) {
3615   MVT VT = SVOp->getValueType(0).getSimpleVT();
3616   DebugLoc dl = SVOp->getDebugLoc();
3617
3618   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3619     return SDValue();
3620
3621   ArrayRef<int> Mask = SVOp->getMask();
3622
3623   // These are the special masks that may be optimized.
3624   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3625   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3626   bool MatchEvenMask = true;
3627   bool MatchOddMask  = true;
3628   for (int i=0; i<8; ++i) {
3629     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3630       MatchEvenMask = false;
3631     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3632       MatchOddMask = false;
3633   }
3634
3635   if (!MatchEvenMask && !MatchOddMask)
3636     return SDValue();
3637
3638   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3639
3640   SDValue Op0 = SVOp->getOperand(0);
3641   SDValue Op1 = SVOp->getOperand(1);
3642
3643   if (MatchEvenMask) {
3644     // Shift the second operand right to 32 bits.
3645     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3646     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3647   } else {
3648     // Shift the first operand left to 32 bits.
3649     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3650     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3651   }
3652   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3653   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3654 }
3655
3656 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3657 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3658 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3659                          bool HasInt256, bool V2IsSplat = false) {
3660   unsigned NumElts = VT.getVectorNumElements();
3661
3662   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3663          "Unsupported vector type for unpckh");
3664
3665   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3666       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3667     return false;
3668
3669   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3670   // independently on 128-bit lanes.
3671   unsigned NumLanes = VT.getSizeInBits()/128;
3672   unsigned NumLaneElts = NumElts/NumLanes;
3673
3674   for (unsigned l = 0; l != NumLanes; ++l) {
3675     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3676          i != (l+1)*NumLaneElts;
3677          i += 2, ++j) {
3678       int BitI  = Mask[i];
3679       int BitI1 = Mask[i+1];
3680       if (!isUndefOrEqual(BitI, j))
3681         return false;
3682       if (V2IsSplat) {
3683         if (!isUndefOrEqual(BitI1, NumElts))
3684           return false;
3685       } else {
3686         if (!isUndefOrEqual(BitI1, j + NumElts))
3687           return false;
3688       }
3689     }
3690   }
3691
3692   return true;
3693 }
3694
3695 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3696 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3697 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3698                          bool HasInt256, bool V2IsSplat = false) {
3699   unsigned NumElts = VT.getVectorNumElements();
3700
3701   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3702          "Unsupported vector type for unpckh");
3703
3704   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3705       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3706     return false;
3707
3708   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3709   // independently on 128-bit lanes.
3710   unsigned NumLanes = VT.getSizeInBits()/128;
3711   unsigned NumLaneElts = NumElts/NumLanes;
3712
3713   for (unsigned l = 0; l != NumLanes; ++l) {
3714     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3715          i != (l+1)*NumLaneElts; i += 2, ++j) {
3716       int BitI  = Mask[i];
3717       int BitI1 = Mask[i+1];
3718       if (!isUndefOrEqual(BitI, j))
3719         return false;
3720       if (V2IsSplat) {
3721         if (isUndefOrEqual(BitI1, NumElts))
3722           return false;
3723       } else {
3724         if (!isUndefOrEqual(BitI1, j+NumElts))
3725           return false;
3726       }
3727     }
3728   }
3729   return true;
3730 }
3731
3732 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3733 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3734 /// <0, 0, 1, 1>
3735 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3736   unsigned NumElts = VT.getVectorNumElements();
3737   bool Is256BitVec = VT.is256BitVector();
3738
3739   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3740          "Unsupported vector type for unpckh");
3741
3742   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3743       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3744     return false;
3745
3746   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3747   // FIXME: Need a better way to get rid of this, there's no latency difference
3748   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3749   // the former later. We should also remove the "_undef" special mask.
3750   if (NumElts == 4 && Is256BitVec)
3751     return false;
3752
3753   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3754   // independently on 128-bit lanes.
3755   unsigned NumLanes = VT.getSizeInBits()/128;
3756   unsigned NumLaneElts = NumElts/NumLanes;
3757
3758   for (unsigned l = 0; l != NumLanes; ++l) {
3759     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3760          i != (l+1)*NumLaneElts;
3761          i += 2, ++j) {
3762       int BitI  = Mask[i];
3763       int BitI1 = Mask[i+1];
3764
3765       if (!isUndefOrEqual(BitI, j))
3766         return false;
3767       if (!isUndefOrEqual(BitI1, j))
3768         return false;
3769     }
3770   }
3771
3772   return true;
3773 }
3774
3775 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3776 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3777 /// <2, 2, 3, 3>
3778 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3779   unsigned NumElts = VT.getVectorNumElements();
3780
3781   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3782          "Unsupported vector type for unpckh");
3783
3784   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3785       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3786     return false;
3787
3788   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3789   // independently on 128-bit lanes.
3790   unsigned NumLanes = VT.getSizeInBits()/128;
3791   unsigned NumLaneElts = NumElts/NumLanes;
3792
3793   for (unsigned l = 0; l != NumLanes; ++l) {
3794     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3795          i != (l+1)*NumLaneElts; i += 2, ++j) {
3796       int BitI  = Mask[i];
3797       int BitI1 = Mask[i+1];
3798       if (!isUndefOrEqual(BitI, j))
3799         return false;
3800       if (!isUndefOrEqual(BitI1, j))
3801         return false;
3802     }
3803   }
3804   return true;
3805 }
3806
3807 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3808 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3809 /// MOVSD, and MOVD, i.e. setting the lowest element.
3810 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3811   if (VT.getVectorElementType().getSizeInBits() < 32)
3812     return false;
3813   if (!VT.is128BitVector())
3814     return false;
3815
3816   unsigned NumElts = VT.getVectorNumElements();
3817
3818   if (!isUndefOrEqual(Mask[0], NumElts))
3819     return false;
3820
3821   for (unsigned i = 1; i != NumElts; ++i)
3822     if (!isUndefOrEqual(Mask[i], i))
3823       return false;
3824
3825   return true;
3826 }
3827
3828 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3829 /// as permutations between 128-bit chunks or halves. As an example: this
3830 /// shuffle bellow:
3831 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3832 /// The first half comes from the second half of V1 and the second half from the
3833 /// the second half of V2.
3834 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3835   if (!HasFp256 || !VT.is256BitVector())
3836     return false;
3837
3838   // The shuffle result is divided into half A and half B. In total the two
3839   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3840   // B must come from C, D, E or F.
3841   unsigned HalfSize = VT.getVectorNumElements()/2;
3842   bool MatchA = false, MatchB = false;
3843
3844   // Check if A comes from one of C, D, E, F.
3845   for (unsigned Half = 0; Half != 4; ++Half) {
3846     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3847       MatchA = true;
3848       break;
3849     }
3850   }
3851
3852   // Check if B comes from one of C, D, E, F.
3853   for (unsigned Half = 0; Half != 4; ++Half) {
3854     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3855       MatchB = true;
3856       break;
3857     }
3858   }
3859
3860   return MatchA && MatchB;
3861 }
3862
3863 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3864 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3865 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3866   MVT VT = SVOp->getValueType(0).getSimpleVT();
3867
3868   unsigned HalfSize = VT.getVectorNumElements()/2;
3869
3870   unsigned FstHalf = 0, SndHalf = 0;
3871   for (unsigned i = 0; i < HalfSize; ++i) {
3872     if (SVOp->getMaskElt(i) > 0) {
3873       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3874       break;
3875     }
3876   }
3877   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3878     if (SVOp->getMaskElt(i) > 0) {
3879       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3880       break;
3881     }
3882   }
3883
3884   return (FstHalf | (SndHalf << 4));
3885 }
3886
3887 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3888 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3889 /// Note that VPERMIL mask matching is different depending whether theunderlying
3890 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3891 /// to the same elements of the low, but to the higher half of the source.
3892 /// In VPERMILPD the two lanes could be shuffled independently of each other
3893 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3894 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3895   if (!HasFp256)
3896     return false;
3897
3898   unsigned NumElts = VT.getVectorNumElements();
3899   // Only match 256-bit with 32/64-bit types
3900   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3901     return false;
3902
3903   unsigned NumLanes = VT.getSizeInBits()/128;
3904   unsigned LaneSize = NumElts/NumLanes;
3905   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3906     for (unsigned i = 0; i != LaneSize; ++i) {
3907       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3908         return false;
3909       if (NumElts != 8 || l == 0)
3910         continue;
3911       // VPERMILPS handling
3912       if (Mask[i] < 0)
3913         continue;
3914       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3915         return false;
3916     }
3917   }
3918
3919   return true;
3920 }
3921
3922 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3923 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3924 /// element of vector 2 and the other elements to come from vector 1 in order.
3925 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3926                                bool V2IsSplat = false, bool V2IsUndef = false) {
3927   if (!VT.is128BitVector())
3928     return false;
3929
3930   unsigned NumOps = VT.getVectorNumElements();
3931   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3932     return false;
3933
3934   if (!isUndefOrEqual(Mask[0], 0))
3935     return false;
3936
3937   for (unsigned i = 1; i != NumOps; ++i)
3938     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3939           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3940           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3941       return false;
3942
3943   return true;
3944 }
3945
3946 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3947 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3948 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3949 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3950                            const X86Subtarget *Subtarget) {
3951   if (!Subtarget->hasSSE3())
3952     return false;
3953
3954   unsigned NumElems = VT.getVectorNumElements();
3955
3956   if ((VT.is128BitVector() && NumElems != 4) ||
3957       (VT.is256BitVector() && NumElems != 8))
3958     return false;
3959
3960   // "i+1" is the value the indexed mask element must have
3961   for (unsigned i = 0; i != NumElems; i += 2)
3962     if (!isUndefOrEqual(Mask[i], i+1) ||
3963         !isUndefOrEqual(Mask[i+1], i+1))
3964       return false;
3965
3966   return true;
3967 }
3968
3969 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3970 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3971 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3972 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3973                            const X86Subtarget *Subtarget) {
3974   if (!Subtarget->hasSSE3())
3975     return false;
3976
3977   unsigned NumElems = VT.getVectorNumElements();
3978
3979   if ((VT.is128BitVector() && NumElems != 4) ||
3980       (VT.is256BitVector() && NumElems != 8))
3981     return false;
3982
3983   // "i" is the value the indexed mask element must have
3984   for (unsigned i = 0; i != NumElems; i += 2)
3985     if (!isUndefOrEqual(Mask[i], i) ||
3986         !isUndefOrEqual(Mask[i+1], i))
3987       return false;
3988
3989   return true;
3990 }
3991
3992 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
3993 /// specifies a shuffle of elements that is suitable for input to 256-bit
3994 /// version of MOVDDUP.
3995 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3996   if (!HasFp256 || !VT.is256BitVector())
3997     return false;
3998
3999   unsigned NumElts = VT.getVectorNumElements();
4000   if (NumElts != 4)
4001     return false;
4002
4003   for (unsigned i = 0; i != NumElts/2; ++i)
4004     if (!isUndefOrEqual(Mask[i], 0))
4005       return false;
4006   for (unsigned i = NumElts/2; i != NumElts; ++i)
4007     if (!isUndefOrEqual(Mask[i], NumElts/2))
4008       return false;
4009   return true;
4010 }
4011
4012 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4013 /// specifies a shuffle of elements that is suitable for input to 128-bit
4014 /// version of MOVDDUP.
4015 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4016   if (!VT.is128BitVector())
4017     return false;
4018
4019   unsigned e = VT.getVectorNumElements() / 2;
4020   for (unsigned i = 0; i != e; ++i)
4021     if (!isUndefOrEqual(Mask[i], i))
4022       return false;
4023   for (unsigned i = 0; i != e; ++i)
4024     if (!isUndefOrEqual(Mask[e+i], i))
4025       return false;
4026   return true;
4027 }
4028
4029 /// isVEXTRACTF128Index - Return true if the specified
4030 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4031 /// suitable for input to VEXTRACTF128.
4032 bool X86::isVEXTRACTF128Index(SDNode *N) {
4033   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4034     return false;
4035
4036   // The index should be aligned on a 128-bit boundary.
4037   uint64_t Index =
4038     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4039
4040   MVT VT = N->getValueType(0).getSimpleVT();
4041   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4042   bool Result = (Index * ElSize) % 128 == 0;
4043
4044   return Result;
4045 }
4046
4047 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4048 /// operand specifies a subvector insert that is suitable for input to
4049 /// VINSERTF128.
4050 bool X86::isVINSERTF128Index(SDNode *N) {
4051   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4052     return false;
4053
4054   // The index should be aligned on a 128-bit boundary.
4055   uint64_t Index =
4056     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4057
4058   MVT VT = N->getValueType(0).getSimpleVT();
4059   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4060   bool Result = (Index * ElSize) % 128 == 0;
4061
4062   return Result;
4063 }
4064
4065 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4066 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4067 /// Handles 128-bit and 256-bit.
4068 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4069   MVT VT = N->getValueType(0).getSimpleVT();
4070
4071   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4072          "Unsupported vector type for PSHUF/SHUFP");
4073
4074   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4075   // independently on 128-bit lanes.
4076   unsigned NumElts = VT.getVectorNumElements();
4077   unsigned NumLanes = VT.getSizeInBits()/128;
4078   unsigned NumLaneElts = NumElts/NumLanes;
4079
4080   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4081          "Only supports 2 or 4 elements per lane");
4082
4083   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4084   unsigned Mask = 0;
4085   for (unsigned i = 0; i != NumElts; ++i) {
4086     int Elt = N->getMaskElt(i);
4087     if (Elt < 0) continue;
4088     Elt &= NumLaneElts - 1;
4089     unsigned ShAmt = (i << Shift) % 8;
4090     Mask |= Elt << ShAmt;
4091   }
4092
4093   return Mask;
4094 }
4095
4096 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4097 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4098 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4099   MVT VT = N->getValueType(0).getSimpleVT();
4100
4101   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4102          "Unsupported vector type for PSHUFHW");
4103
4104   unsigned NumElts = VT.getVectorNumElements();
4105
4106   unsigned Mask = 0;
4107   for (unsigned l = 0; l != NumElts; l += 8) {
4108     // 8 nodes per lane, but we only care about the last 4.
4109     for (unsigned i = 0; i < 4; ++i) {
4110       int Elt = N->getMaskElt(l+i+4);
4111       if (Elt < 0) continue;
4112       Elt &= 0x3; // only 2-bits.
4113       Mask |= Elt << (i * 2);
4114     }
4115   }
4116
4117   return Mask;
4118 }
4119
4120 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4121 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4122 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4123   MVT VT = N->getValueType(0).getSimpleVT();
4124
4125   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4126          "Unsupported vector type for PSHUFHW");
4127
4128   unsigned NumElts = VT.getVectorNumElements();
4129
4130   unsigned Mask = 0;
4131   for (unsigned l = 0; l != NumElts; l += 8) {
4132     // 8 nodes per lane, but we only care about the first 4.
4133     for (unsigned i = 0; i < 4; ++i) {
4134       int Elt = N->getMaskElt(l+i);
4135       if (Elt < 0) continue;
4136       Elt &= 0x3; // only 2-bits
4137       Mask |= Elt << (i * 2);
4138     }
4139   }
4140
4141   return Mask;
4142 }
4143
4144 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4145 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4146 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4147   MVT VT = SVOp->getValueType(0).getSimpleVT();
4148   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4149
4150   unsigned NumElts = VT.getVectorNumElements();
4151   unsigned NumLanes = VT.getSizeInBits()/128;
4152   unsigned NumLaneElts = NumElts/NumLanes;
4153
4154   int Val = 0;
4155   unsigned i;
4156   for (i = 0; i != NumElts; ++i) {
4157     Val = SVOp->getMaskElt(i);
4158     if (Val >= 0)
4159       break;
4160   }
4161   if (Val >= (int)NumElts)
4162     Val -= NumElts - NumLaneElts;
4163
4164   assert(Val - i > 0 && "PALIGNR imm should be positive");
4165   return (Val - i) * EltSize;
4166 }
4167
4168 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4169 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4170 /// instructions.
4171 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4172   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4173     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4174
4175   uint64_t Index =
4176     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4177
4178   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4179   MVT ElVT = VecVT.getVectorElementType();
4180
4181   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4182   return Index / NumElemsPerChunk;
4183 }
4184
4185 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4186 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4187 /// instructions.
4188 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4189   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4190     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4191
4192   uint64_t Index =
4193     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4194
4195   MVT VecVT = N->getValueType(0).getSimpleVT();
4196   MVT ElVT = VecVT.getVectorElementType();
4197
4198   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4199   return Index / NumElemsPerChunk;
4200 }
4201
4202 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4203 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4204 /// Handles 256-bit.
4205 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4206   MVT VT = N->getValueType(0).getSimpleVT();
4207
4208   unsigned NumElts = VT.getVectorNumElements();
4209
4210   assert((VT.is256BitVector() && NumElts == 4) &&
4211          "Unsupported vector type for VPERMQ/VPERMPD");
4212
4213   unsigned Mask = 0;
4214   for (unsigned i = 0; i != NumElts; ++i) {
4215     int Elt = N->getMaskElt(i);
4216     if (Elt < 0)
4217       continue;
4218     Mask |= Elt << (i*2);
4219   }
4220
4221   return Mask;
4222 }
4223 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4224 /// constant +0.0.
4225 bool X86::isZeroNode(SDValue Elt) {
4226   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4227     return CN->isNullValue();
4228   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4229     return CFP->getValueAPF().isPosZero();
4230   return false;
4231 }
4232
4233 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4234 /// their permute mask.
4235 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4236                                     SelectionDAG &DAG) {
4237   MVT VT = SVOp->getValueType(0).getSimpleVT();
4238   unsigned NumElems = VT.getVectorNumElements();
4239   SmallVector<int, 8> MaskVec;
4240
4241   for (unsigned i = 0; i != NumElems; ++i) {
4242     int Idx = SVOp->getMaskElt(i);
4243     if (Idx >= 0) {
4244       if (Idx < (int)NumElems)
4245         Idx += NumElems;
4246       else
4247         Idx -= NumElems;
4248     }
4249     MaskVec.push_back(Idx);
4250   }
4251   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4252                               SVOp->getOperand(0), &MaskVec[0]);
4253 }
4254
4255 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4256 /// match movhlps. The lower half elements should come from upper half of
4257 /// V1 (and in order), and the upper half elements should come from the upper
4258 /// half of V2 (and in order).
4259 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4260   if (!VT.is128BitVector())
4261     return false;
4262   if (VT.getVectorNumElements() != 4)
4263     return false;
4264   for (unsigned i = 0, e = 2; i != e; ++i)
4265     if (!isUndefOrEqual(Mask[i], i+2))
4266       return false;
4267   for (unsigned i = 2; i != 4; ++i)
4268     if (!isUndefOrEqual(Mask[i], i+4))
4269       return false;
4270   return true;
4271 }
4272
4273 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4274 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4275 /// required.
4276 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4277   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4278     return false;
4279   N = N->getOperand(0).getNode();
4280   if (!ISD::isNON_EXTLoad(N))
4281     return false;
4282   if (LD)
4283     *LD = cast<LoadSDNode>(N);
4284   return true;
4285 }
4286
4287 // Test whether the given value is a vector value which will be legalized
4288 // into a load.
4289 static bool WillBeConstantPoolLoad(SDNode *N) {
4290   if (N->getOpcode() != ISD::BUILD_VECTOR)
4291     return false;
4292
4293   // Check for any non-constant elements.
4294   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4295     switch (N->getOperand(i).getNode()->getOpcode()) {
4296     case ISD::UNDEF:
4297     case ISD::ConstantFP:
4298     case ISD::Constant:
4299       break;
4300     default:
4301       return false;
4302     }
4303
4304   // Vectors of all-zeros and all-ones are materialized with special
4305   // instructions rather than being loaded.
4306   return !ISD::isBuildVectorAllZeros(N) &&
4307          !ISD::isBuildVectorAllOnes(N);
4308 }
4309
4310 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4311 /// match movlp{s|d}. The lower half elements should come from lower half of
4312 /// V1 (and in order), and the upper half elements should come from the upper
4313 /// half of V2 (and in order). And since V1 will become the source of the
4314 /// MOVLP, it must be either a vector load or a scalar load to vector.
4315 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4316                                ArrayRef<int> Mask, EVT VT) {
4317   if (!VT.is128BitVector())
4318     return false;
4319
4320   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4321     return false;
4322   // Is V2 is a vector load, don't do this transformation. We will try to use
4323   // load folding shufps op.
4324   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4325     return false;
4326
4327   unsigned NumElems = VT.getVectorNumElements();
4328
4329   if (NumElems != 2 && NumElems != 4)
4330     return false;
4331   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4332     if (!isUndefOrEqual(Mask[i], i))
4333       return false;
4334   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4335     if (!isUndefOrEqual(Mask[i], i+NumElems))
4336       return false;
4337   return true;
4338 }
4339
4340 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4341 /// all the same.
4342 static bool isSplatVector(SDNode *N) {
4343   if (N->getOpcode() != ISD::BUILD_VECTOR)
4344     return false;
4345
4346   SDValue SplatValue = N->getOperand(0);
4347   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4348     if (N->getOperand(i) != SplatValue)
4349       return false;
4350   return true;
4351 }
4352
4353 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4354 /// to an zero vector.
4355 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4356 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4357   SDValue V1 = N->getOperand(0);
4358   SDValue V2 = N->getOperand(1);
4359   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4360   for (unsigned i = 0; i != NumElems; ++i) {
4361     int Idx = N->getMaskElt(i);
4362     if (Idx >= (int)NumElems) {
4363       unsigned Opc = V2.getOpcode();
4364       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4365         continue;
4366       if (Opc != ISD::BUILD_VECTOR ||
4367           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4368         return false;
4369     } else if (Idx >= 0) {
4370       unsigned Opc = V1.getOpcode();
4371       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4372         continue;
4373       if (Opc != ISD::BUILD_VECTOR ||
4374           !X86::isZeroNode(V1.getOperand(Idx)))
4375         return false;
4376     }
4377   }
4378   return true;
4379 }
4380
4381 /// getZeroVector - Returns a vector of specified type with all zero elements.
4382 ///
4383 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4384                              SelectionDAG &DAG, DebugLoc dl) {
4385   assert(VT.isVector() && "Expected a vector type");
4386
4387   // Always build SSE zero vectors as <4 x i32> bitcasted
4388   // to their dest type. This ensures they get CSE'd.
4389   SDValue Vec;
4390   if (VT.is128BitVector()) {  // SSE
4391     if (Subtarget->hasSSE2()) {  // SSE2
4392       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4393       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4394     } else { // SSE1
4395       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4396       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4397     }
4398   } else if (VT.is256BitVector()) { // AVX
4399     if (Subtarget->hasInt256()) { // AVX2
4400       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4401       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4402       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4403     } else {
4404       // 256-bit logic and arithmetic instructions in AVX are all
4405       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4406       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4407       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4408       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4409     }
4410   } else
4411     llvm_unreachable("Unexpected vector type");
4412
4413   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4414 }
4415
4416 /// getOnesVector - Returns a vector of specified type with all bits set.
4417 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4418 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4419 /// Then bitcast to their original type, ensuring they get CSE'd.
4420 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4421                              DebugLoc dl) {
4422   assert(VT.isVector() && "Expected a vector type");
4423
4424   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4425   SDValue Vec;
4426   if (VT.is256BitVector()) {
4427     if (HasInt256) { // AVX2
4428       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4429       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4430     } else { // AVX
4431       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4432       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4433     }
4434   } else if (VT.is128BitVector()) {
4435     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4436   } else
4437     llvm_unreachable("Unexpected vector type");
4438
4439   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4440 }
4441
4442 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4443 /// that point to V2 points to its first element.
4444 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4445   for (unsigned i = 0; i != NumElems; ++i) {
4446     if (Mask[i] > (int)NumElems) {
4447       Mask[i] = NumElems;
4448     }
4449   }
4450 }
4451
4452 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4453 /// operation of specified width.
4454 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4455                        SDValue V2) {
4456   unsigned NumElems = VT.getVectorNumElements();
4457   SmallVector<int, 8> Mask;
4458   Mask.push_back(NumElems);
4459   for (unsigned i = 1; i != NumElems; ++i)
4460     Mask.push_back(i);
4461   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4462 }
4463
4464 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4465 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4466                           SDValue V2) {
4467   unsigned NumElems = VT.getVectorNumElements();
4468   SmallVector<int, 8> Mask;
4469   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4470     Mask.push_back(i);
4471     Mask.push_back(i + NumElems);
4472   }
4473   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4474 }
4475
4476 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4477 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4478                           SDValue V2) {
4479   unsigned NumElems = VT.getVectorNumElements();
4480   SmallVector<int, 8> Mask;
4481   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4482     Mask.push_back(i + Half);
4483     Mask.push_back(i + NumElems + Half);
4484   }
4485   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4486 }
4487
4488 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4489 // a generic shuffle instruction because the target has no such instructions.
4490 // Generate shuffles which repeat i16 and i8 several times until they can be
4491 // represented by v4f32 and then be manipulated by target suported shuffles.
4492 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4493   EVT VT = V.getValueType();
4494   int NumElems = VT.getVectorNumElements();
4495   DebugLoc dl = V.getDebugLoc();
4496
4497   while (NumElems > 4) {
4498     if (EltNo < NumElems/2) {
4499       V = getUnpackl(DAG, dl, VT, V, V);
4500     } else {
4501       V = getUnpackh(DAG, dl, VT, V, V);
4502       EltNo -= NumElems/2;
4503     }
4504     NumElems >>= 1;
4505   }
4506   return V;
4507 }
4508
4509 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4510 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4511   EVT VT = V.getValueType();
4512   DebugLoc dl = V.getDebugLoc();
4513
4514   if (VT.is128BitVector()) {
4515     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4516     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4517     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4518                              &SplatMask[0]);
4519   } else if (VT.is256BitVector()) {
4520     // To use VPERMILPS to splat scalars, the second half of indicies must
4521     // refer to the higher part, which is a duplication of the lower one,
4522     // because VPERMILPS can only handle in-lane permutations.
4523     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4524                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4525
4526     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4527     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4528                              &SplatMask[0]);
4529   } else
4530     llvm_unreachable("Vector size not supported");
4531
4532   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4533 }
4534
4535 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4536 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4537   EVT SrcVT = SV->getValueType(0);
4538   SDValue V1 = SV->getOperand(0);
4539   DebugLoc dl = SV->getDebugLoc();
4540
4541   int EltNo = SV->getSplatIndex();
4542   int NumElems = SrcVT.getVectorNumElements();
4543   bool Is256BitVec = SrcVT.is256BitVector();
4544
4545   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4546          "Unknown how to promote splat for type");
4547
4548   // Extract the 128-bit part containing the splat element and update
4549   // the splat element index when it refers to the higher register.
4550   if (Is256BitVec) {
4551     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4552     if (EltNo >= NumElems/2)
4553       EltNo -= NumElems/2;
4554   }
4555
4556   // All i16 and i8 vector types can't be used directly by a generic shuffle
4557   // instruction because the target has no such instruction. Generate shuffles
4558   // which repeat i16 and i8 several times until they fit in i32, and then can
4559   // be manipulated by target suported shuffles.
4560   EVT EltVT = SrcVT.getVectorElementType();
4561   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4562     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4563
4564   // Recreate the 256-bit vector and place the same 128-bit vector
4565   // into the low and high part. This is necessary because we want
4566   // to use VPERM* to shuffle the vectors
4567   if (Is256BitVec) {
4568     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4569   }
4570
4571   return getLegalSplat(DAG, V1, EltNo);
4572 }
4573
4574 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4575 /// vector of zero or undef vector.  This produces a shuffle where the low
4576 /// element of V2 is swizzled into the zero/undef vector, landing at element
4577 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4578 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4579                                            bool IsZero,
4580                                            const X86Subtarget *Subtarget,
4581                                            SelectionDAG &DAG) {
4582   EVT VT = V2.getValueType();
4583   SDValue V1 = IsZero
4584     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4585   unsigned NumElems = VT.getVectorNumElements();
4586   SmallVector<int, 16> MaskVec;
4587   for (unsigned i = 0; i != NumElems; ++i)
4588     // If this is the insertion idx, put the low elt of V2 here.
4589     MaskVec.push_back(i == Idx ? NumElems : i);
4590   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4591 }
4592
4593 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4594 /// target specific opcode. Returns true if the Mask could be calculated.
4595 /// Sets IsUnary to true if only uses one source.
4596 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4597                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4598   unsigned NumElems = VT.getVectorNumElements();
4599   SDValue ImmN;
4600
4601   IsUnary = false;
4602   switch(N->getOpcode()) {
4603   case X86ISD::SHUFP:
4604     ImmN = N->getOperand(N->getNumOperands()-1);
4605     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4606     break;
4607   case X86ISD::UNPCKH:
4608     DecodeUNPCKHMask(VT, Mask);
4609     break;
4610   case X86ISD::UNPCKL:
4611     DecodeUNPCKLMask(VT, Mask);
4612     break;
4613   case X86ISD::MOVHLPS:
4614     DecodeMOVHLPSMask(NumElems, Mask);
4615     break;
4616   case X86ISD::MOVLHPS:
4617     DecodeMOVLHPSMask(NumElems, Mask);
4618     break;
4619   case X86ISD::PALIGNR:
4620     ImmN = N->getOperand(N->getNumOperands()-1);
4621     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4622     break;
4623   case X86ISD::PSHUFD:
4624   case X86ISD::VPERMILP:
4625     ImmN = N->getOperand(N->getNumOperands()-1);
4626     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4627     IsUnary = true;
4628     break;
4629   case X86ISD::PSHUFHW:
4630     ImmN = N->getOperand(N->getNumOperands()-1);
4631     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4632     IsUnary = true;
4633     break;
4634   case X86ISD::PSHUFLW:
4635     ImmN = N->getOperand(N->getNumOperands()-1);
4636     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4637     IsUnary = true;
4638     break;
4639   case X86ISD::VPERMI:
4640     ImmN = N->getOperand(N->getNumOperands()-1);
4641     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4642     IsUnary = true;
4643     break;
4644   case X86ISD::MOVSS:
4645   case X86ISD::MOVSD: {
4646     // The index 0 always comes from the first element of the second source,
4647     // this is why MOVSS and MOVSD are used in the first place. The other
4648     // elements come from the other positions of the first source vector
4649     Mask.push_back(NumElems);
4650     for (unsigned i = 1; i != NumElems; ++i) {
4651       Mask.push_back(i);
4652     }
4653     break;
4654   }
4655   case X86ISD::VPERM2X128:
4656     ImmN = N->getOperand(N->getNumOperands()-1);
4657     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4658     if (Mask.empty()) return false;
4659     break;
4660   case X86ISD::MOVDDUP:
4661   case X86ISD::MOVLHPD:
4662   case X86ISD::MOVLPD:
4663   case X86ISD::MOVLPS:
4664   case X86ISD::MOVSHDUP:
4665   case X86ISD::MOVSLDUP:
4666     // Not yet implemented
4667     return false;
4668   default: llvm_unreachable("unknown target shuffle node");
4669   }
4670
4671   return true;
4672 }
4673
4674 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4675 /// element of the result of the vector shuffle.
4676 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4677                                    unsigned Depth) {
4678   if (Depth == 6)
4679     return SDValue();  // Limit search depth.
4680
4681   SDValue V = SDValue(N, 0);
4682   EVT VT = V.getValueType();
4683   unsigned Opcode = V.getOpcode();
4684
4685   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4686   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4687     int Elt = SV->getMaskElt(Index);
4688
4689     if (Elt < 0)
4690       return DAG.getUNDEF(VT.getVectorElementType());
4691
4692     unsigned NumElems = VT.getVectorNumElements();
4693     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4694                                          : SV->getOperand(1);
4695     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4696   }
4697
4698   // Recurse into target specific vector shuffles to find scalars.
4699   if (isTargetShuffle(Opcode)) {
4700     MVT ShufVT = V.getValueType().getSimpleVT();
4701     unsigned NumElems = ShufVT.getVectorNumElements();
4702     SmallVector<int, 16> ShuffleMask;
4703     bool IsUnary;
4704
4705     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4706       return SDValue();
4707
4708     int Elt = ShuffleMask[Index];
4709     if (Elt < 0)
4710       return DAG.getUNDEF(ShufVT.getVectorElementType());
4711
4712     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4713                                          : N->getOperand(1);
4714     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4715                                Depth+1);
4716   }
4717
4718   // Actual nodes that may contain scalar elements
4719   if (Opcode == ISD::BITCAST) {
4720     V = V.getOperand(0);
4721     EVT SrcVT = V.getValueType();
4722     unsigned NumElems = VT.getVectorNumElements();
4723
4724     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4725       return SDValue();
4726   }
4727
4728   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4729     return (Index == 0) ? V.getOperand(0)
4730                         : DAG.getUNDEF(VT.getVectorElementType());
4731
4732   if (V.getOpcode() == ISD::BUILD_VECTOR)
4733     return V.getOperand(Index);
4734
4735   return SDValue();
4736 }
4737
4738 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4739 /// shuffle operation which come from a consecutively from a zero. The
4740 /// search can start in two different directions, from left or right.
4741 static
4742 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4743                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4744   unsigned i;
4745   for (i = 0; i != NumElems; ++i) {
4746     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4747     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4748     if (!(Elt.getNode() &&
4749          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4750       break;
4751   }
4752
4753   return i;
4754 }
4755
4756 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4757 /// correspond consecutively to elements from one of the vector operands,
4758 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4759 static
4760 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4761                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4762                               unsigned NumElems, unsigned &OpNum) {
4763   bool SeenV1 = false;
4764   bool SeenV2 = false;
4765
4766   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4767     int Idx = SVOp->getMaskElt(i);
4768     // Ignore undef indicies
4769     if (Idx < 0)
4770       continue;
4771
4772     if (Idx < (int)NumElems)
4773       SeenV1 = true;
4774     else
4775       SeenV2 = true;
4776
4777     // Only accept consecutive elements from the same vector
4778     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4779       return false;
4780   }
4781
4782   OpNum = SeenV1 ? 0 : 1;
4783   return true;
4784 }
4785
4786 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4787 /// logical left shift of a vector.
4788 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4789                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4790   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4791   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4792               false /* check zeros from right */, DAG);
4793   unsigned OpSrc;
4794
4795   if (!NumZeros)
4796     return false;
4797
4798   // Considering the elements in the mask that are not consecutive zeros,
4799   // check if they consecutively come from only one of the source vectors.
4800   //
4801   //               V1 = {X, A, B, C}     0
4802   //                         \  \  \    /
4803   //   vector_shuffle V1, V2 <1, 2, 3, X>
4804   //
4805   if (!isShuffleMaskConsecutive(SVOp,
4806             0,                   // Mask Start Index
4807             NumElems-NumZeros,   // Mask End Index(exclusive)
4808             NumZeros,            // Where to start looking in the src vector
4809             NumElems,            // Number of elements in vector
4810             OpSrc))              // Which source operand ?
4811     return false;
4812
4813   isLeft = false;
4814   ShAmt = NumZeros;
4815   ShVal = SVOp->getOperand(OpSrc);
4816   return true;
4817 }
4818
4819 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4820 /// logical left shift of a vector.
4821 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4822                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4823   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4824   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4825               true /* check zeros from left */, DAG);
4826   unsigned OpSrc;
4827
4828   if (!NumZeros)
4829     return false;
4830
4831   // Considering the elements in the mask that are not consecutive zeros,
4832   // check if they consecutively come from only one of the source vectors.
4833   //
4834   //                           0    { A, B, X, X } = V2
4835   //                          / \    /  /
4836   //   vector_shuffle V1, V2 <X, X, 4, 5>
4837   //
4838   if (!isShuffleMaskConsecutive(SVOp,
4839             NumZeros,     // Mask Start Index
4840             NumElems,     // Mask End Index(exclusive)
4841             0,            // Where to start looking in the src vector
4842             NumElems,     // Number of elements in vector
4843             OpSrc))       // Which source operand ?
4844     return false;
4845
4846   isLeft = true;
4847   ShAmt = NumZeros;
4848   ShVal = SVOp->getOperand(OpSrc);
4849   return true;
4850 }
4851
4852 /// isVectorShift - Returns true if the shuffle can be implemented as a
4853 /// logical left or right shift of a vector.
4854 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4855                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4856   // Although the logic below support any bitwidth size, there are no
4857   // shift instructions which handle more than 128-bit vectors.
4858   if (!SVOp->getValueType(0).is128BitVector())
4859     return false;
4860
4861   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4862       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4863     return true;
4864
4865   return false;
4866 }
4867
4868 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4869 ///
4870 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4871                                        unsigned NumNonZero, unsigned NumZero,
4872                                        SelectionDAG &DAG,
4873                                        const X86Subtarget* Subtarget,
4874                                        const TargetLowering &TLI) {
4875   if (NumNonZero > 8)
4876     return SDValue();
4877
4878   DebugLoc dl = Op.getDebugLoc();
4879   SDValue V(0, 0);
4880   bool First = true;
4881   for (unsigned i = 0; i < 16; ++i) {
4882     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4883     if (ThisIsNonZero && First) {
4884       if (NumZero)
4885         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4886       else
4887         V = DAG.getUNDEF(MVT::v8i16);
4888       First = false;
4889     }
4890
4891     if ((i & 1) != 0) {
4892       SDValue ThisElt(0, 0), LastElt(0, 0);
4893       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4894       if (LastIsNonZero) {
4895         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4896                               MVT::i16, Op.getOperand(i-1));
4897       }
4898       if (ThisIsNonZero) {
4899         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4900         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4901                               ThisElt, DAG.getConstant(8, MVT::i8));
4902         if (LastIsNonZero)
4903           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4904       } else
4905         ThisElt = LastElt;
4906
4907       if (ThisElt.getNode())
4908         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4909                         DAG.getIntPtrConstant(i/2));
4910     }
4911   }
4912
4913   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4914 }
4915
4916 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4917 ///
4918 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4919                                      unsigned NumNonZero, unsigned NumZero,
4920                                      SelectionDAG &DAG,
4921                                      const X86Subtarget* Subtarget,
4922                                      const TargetLowering &TLI) {
4923   if (NumNonZero > 4)
4924     return SDValue();
4925
4926   DebugLoc dl = Op.getDebugLoc();
4927   SDValue V(0, 0);
4928   bool First = true;
4929   for (unsigned i = 0; i < 8; ++i) {
4930     bool isNonZero = (NonZeros & (1 << i)) != 0;
4931     if (isNonZero) {
4932       if (First) {
4933         if (NumZero)
4934           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4935         else
4936           V = DAG.getUNDEF(MVT::v8i16);
4937         First = false;
4938       }
4939       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4940                       MVT::v8i16, V, Op.getOperand(i),
4941                       DAG.getIntPtrConstant(i));
4942     }
4943   }
4944
4945   return V;
4946 }
4947
4948 /// getVShift - Return a vector logical shift node.
4949 ///
4950 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4951                          unsigned NumBits, SelectionDAG &DAG,
4952                          const TargetLowering &TLI, DebugLoc dl) {
4953   assert(VT.is128BitVector() && "Unknown type for VShift");
4954   EVT ShVT = MVT::v2i64;
4955   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4956   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4957   return DAG.getNode(ISD::BITCAST, dl, VT,
4958                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4959                              DAG.getConstant(NumBits,
4960                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4961 }
4962
4963 SDValue
4964 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4965                                           SelectionDAG &DAG) const {
4966
4967   // Check if the scalar load can be widened into a vector load. And if
4968   // the address is "base + cst" see if the cst can be "absorbed" into
4969   // the shuffle mask.
4970   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4971     SDValue Ptr = LD->getBasePtr();
4972     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4973       return SDValue();
4974     EVT PVT = LD->getValueType(0);
4975     if (PVT != MVT::i32 && PVT != MVT::f32)
4976       return SDValue();
4977
4978     int FI = -1;
4979     int64_t Offset = 0;
4980     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4981       FI = FINode->getIndex();
4982       Offset = 0;
4983     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4984                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4985       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4986       Offset = Ptr.getConstantOperandVal(1);
4987       Ptr = Ptr.getOperand(0);
4988     } else {
4989       return SDValue();
4990     }
4991
4992     // FIXME: 256-bit vector instructions don't require a strict alignment,
4993     // improve this code to support it better.
4994     unsigned RequiredAlign = VT.getSizeInBits()/8;
4995     SDValue Chain = LD->getChain();
4996     // Make sure the stack object alignment is at least 16 or 32.
4997     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4998     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4999       if (MFI->isFixedObjectIndex(FI)) {
5000         // Can't change the alignment. FIXME: It's possible to compute
5001         // the exact stack offset and reference FI + adjust offset instead.
5002         // If someone *really* cares about this. That's the way to implement it.
5003         return SDValue();
5004       } else {
5005         MFI->setObjectAlignment(FI, RequiredAlign);
5006       }
5007     }
5008
5009     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5010     // Ptr + (Offset & ~15).
5011     if (Offset < 0)
5012       return SDValue();
5013     if ((Offset % RequiredAlign) & 3)
5014       return SDValue();
5015     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5016     if (StartOffset)
5017       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5018                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5019
5020     int EltNo = (Offset - StartOffset) >> 2;
5021     unsigned NumElems = VT.getVectorNumElements();
5022
5023     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5024     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5025                              LD->getPointerInfo().getWithOffset(StartOffset),
5026                              false, false, false, 0);
5027
5028     SmallVector<int, 8> Mask;
5029     for (unsigned i = 0; i != NumElems; ++i)
5030       Mask.push_back(EltNo);
5031
5032     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5033   }
5034
5035   return SDValue();
5036 }
5037
5038 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5039 /// vector of type 'VT', see if the elements can be replaced by a single large
5040 /// load which has the same value as a build_vector whose operands are 'elts'.
5041 ///
5042 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5043 ///
5044 /// FIXME: we'd also like to handle the case where the last elements are zero
5045 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5046 /// There's even a handy isZeroNode for that purpose.
5047 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5048                                         DebugLoc &DL, SelectionDAG &DAG) {
5049   EVT EltVT = VT.getVectorElementType();
5050   unsigned NumElems = Elts.size();
5051
5052   LoadSDNode *LDBase = NULL;
5053   unsigned LastLoadedElt = -1U;
5054
5055   // For each element in the initializer, see if we've found a load or an undef.
5056   // If we don't find an initial load element, or later load elements are
5057   // non-consecutive, bail out.
5058   for (unsigned i = 0; i < NumElems; ++i) {
5059     SDValue Elt = Elts[i];
5060
5061     if (!Elt.getNode() ||
5062         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5063       return SDValue();
5064     if (!LDBase) {
5065       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5066         return SDValue();
5067       LDBase = cast<LoadSDNode>(Elt.getNode());
5068       LastLoadedElt = i;
5069       continue;
5070     }
5071     if (Elt.getOpcode() == ISD::UNDEF)
5072       continue;
5073
5074     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5075     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5076       return SDValue();
5077     LastLoadedElt = i;
5078   }
5079
5080   // If we have found an entire vector of loads and undefs, then return a large
5081   // load of the entire vector width starting at the base pointer.  If we found
5082   // consecutive loads for the low half, generate a vzext_load node.
5083   if (LastLoadedElt == NumElems - 1) {
5084     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5085       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5086                          LDBase->getPointerInfo(),
5087                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5088                          LDBase->isInvariant(), 0);
5089     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5090                        LDBase->getPointerInfo(),
5091                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5092                        LDBase->isInvariant(), LDBase->getAlignment());
5093   }
5094   if (NumElems == 4 && LastLoadedElt == 1 &&
5095       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5096     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5097     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5098     SDValue ResNode =
5099         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5100                                 LDBase->getPointerInfo(),
5101                                 LDBase->getAlignment(),
5102                                 false/*isVolatile*/, true/*ReadMem*/,
5103                                 false/*WriteMem*/);
5104
5105     // Make sure the newly-created LOAD is in the same position as LDBase in
5106     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5107     // update uses of LDBase's output chain to use the TokenFactor.
5108     if (LDBase->hasAnyUseOfValue(1)) {
5109       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5110                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5111       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5112       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5113                              SDValue(ResNode.getNode(), 1));
5114     }
5115
5116     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5117   }
5118   return SDValue();
5119 }
5120
5121 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5122 /// to generate a splat value for the following cases:
5123 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5124 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5125 /// a scalar load, or a constant.
5126 /// The VBROADCAST node is returned when a pattern is found,
5127 /// or SDValue() otherwise.
5128 SDValue
5129 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5130   if (!Subtarget->hasFp256())
5131     return SDValue();
5132
5133   MVT VT = Op.getValueType().getSimpleVT();
5134   DebugLoc dl = Op.getDebugLoc();
5135
5136   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5137          "Unsupported vector type for broadcast.");
5138
5139   SDValue Ld;
5140   bool ConstSplatVal;
5141
5142   switch (Op.getOpcode()) {
5143     default:
5144       // Unknown pattern found.
5145       return SDValue();
5146
5147     case ISD::BUILD_VECTOR: {
5148       // The BUILD_VECTOR node must be a splat.
5149       if (!isSplatVector(Op.getNode()))
5150         return SDValue();
5151
5152       Ld = Op.getOperand(0);
5153       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5154                      Ld.getOpcode() == ISD::ConstantFP);
5155
5156       // The suspected load node has several users. Make sure that all
5157       // of its users are from the BUILD_VECTOR node.
5158       // Constants may have multiple users.
5159       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5160         return SDValue();
5161       break;
5162     }
5163
5164     case ISD::VECTOR_SHUFFLE: {
5165       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5166
5167       // Shuffles must have a splat mask where the first element is
5168       // broadcasted.
5169       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5170         return SDValue();
5171
5172       SDValue Sc = Op.getOperand(0);
5173       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5174           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5175
5176         if (!Subtarget->hasInt256())
5177           return SDValue();
5178
5179         // Use the register form of the broadcast instruction available on AVX2.
5180         if (VT.is256BitVector())
5181           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5182         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5183       }
5184
5185       Ld = Sc.getOperand(0);
5186       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5187                        Ld.getOpcode() == ISD::ConstantFP);
5188
5189       // The scalar_to_vector node and the suspected
5190       // load node must have exactly one user.
5191       // Constants may have multiple users.
5192       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5193         return SDValue();
5194       break;
5195     }
5196   }
5197
5198   bool Is256 = VT.is256BitVector();
5199
5200   // Handle the broadcasting a single constant scalar from the constant pool
5201   // into a vector. On Sandybridge it is still better to load a constant vector
5202   // from the constant pool and not to broadcast it from a scalar.
5203   if (ConstSplatVal && Subtarget->hasInt256()) {
5204     EVT CVT = Ld.getValueType();
5205     assert(!CVT.isVector() && "Must not broadcast a vector type");
5206     unsigned ScalarSize = CVT.getSizeInBits();
5207
5208     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5209       const Constant *C = 0;
5210       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5211         C = CI->getConstantIntValue();
5212       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5213         C = CF->getConstantFPValue();
5214
5215       assert(C && "Invalid constant type");
5216
5217       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5218       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5219       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5220                        MachinePointerInfo::getConstantPool(),
5221                        false, false, false, Alignment);
5222
5223       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5224     }
5225   }
5226
5227   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5228   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5229
5230   // Handle AVX2 in-register broadcasts.
5231   if (!IsLoad && Subtarget->hasInt256() &&
5232       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5233     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5234
5235   // The scalar source must be a normal load.
5236   if (!IsLoad)
5237     return SDValue();
5238
5239   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5240     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5241
5242   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5243   // double since there is no vbroadcastsd xmm
5244   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5245     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5246       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5247   }
5248
5249   // Unsupported broadcast.
5250   return SDValue();
5251 }
5252
5253 SDValue
5254 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5255   EVT VT = Op.getValueType();
5256
5257   // Skip if insert_vec_elt is not supported.
5258   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5259     return SDValue();
5260
5261   DebugLoc DL = Op.getDebugLoc();
5262   unsigned NumElems = Op.getNumOperands();
5263
5264   SDValue VecIn1;
5265   SDValue VecIn2;
5266   SmallVector<unsigned, 4> InsertIndices;
5267   SmallVector<int, 8> Mask(NumElems, -1);
5268
5269   for (unsigned i = 0; i != NumElems; ++i) {
5270     unsigned Opc = Op.getOperand(i).getOpcode();
5271
5272     if (Opc == ISD::UNDEF)
5273       continue;
5274
5275     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5276       // Quit if more than 1 elements need inserting.
5277       if (InsertIndices.size() > 1)
5278         return SDValue();
5279
5280       InsertIndices.push_back(i);
5281       continue;
5282     }
5283
5284     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5285     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5286
5287     // Quit if extracted from vector of different type.
5288     if (ExtractedFromVec.getValueType() != VT)
5289       return SDValue();
5290
5291     // Quit if non-constant index.
5292     if (!isa<ConstantSDNode>(ExtIdx))
5293       return SDValue();
5294
5295     if (VecIn1.getNode() == 0)
5296       VecIn1 = ExtractedFromVec;
5297     else if (VecIn1 != ExtractedFromVec) {
5298       if (VecIn2.getNode() == 0)
5299         VecIn2 = ExtractedFromVec;
5300       else if (VecIn2 != ExtractedFromVec)
5301         // Quit if more than 2 vectors to shuffle
5302         return SDValue();
5303     }
5304
5305     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5306
5307     if (ExtractedFromVec == VecIn1)
5308       Mask[i] = Idx;
5309     else if (ExtractedFromVec == VecIn2)
5310       Mask[i] = Idx + NumElems;
5311   }
5312
5313   if (VecIn1.getNode() == 0)
5314     return SDValue();
5315
5316   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5317   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5318   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5319     unsigned Idx = InsertIndices[i];
5320     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5321                      DAG.getIntPtrConstant(Idx));
5322   }
5323
5324   return NV;
5325 }
5326
5327 SDValue
5328 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5329   DebugLoc dl = Op.getDebugLoc();
5330
5331   MVT VT = Op.getValueType().getSimpleVT();
5332   MVT ExtVT = VT.getVectorElementType();
5333   unsigned NumElems = Op.getNumOperands();
5334
5335   // Vectors containing all zeros can be matched by pxor and xorps later
5336   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5337     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5338     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5339     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5340       return Op;
5341
5342     return getZeroVector(VT, Subtarget, DAG, dl);
5343   }
5344
5345   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5346   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5347   // vpcmpeqd on 256-bit vectors.
5348   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5349     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5350       return Op;
5351
5352     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5353   }
5354
5355   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5356   if (Broadcast.getNode())
5357     return Broadcast;
5358
5359   unsigned EVTBits = ExtVT.getSizeInBits();
5360
5361   unsigned NumZero  = 0;
5362   unsigned NumNonZero = 0;
5363   unsigned NonZeros = 0;
5364   bool IsAllConstants = true;
5365   SmallSet<SDValue, 8> Values;
5366   for (unsigned i = 0; i < NumElems; ++i) {
5367     SDValue Elt = Op.getOperand(i);
5368     if (Elt.getOpcode() == ISD::UNDEF)
5369       continue;
5370     Values.insert(Elt);
5371     if (Elt.getOpcode() != ISD::Constant &&
5372         Elt.getOpcode() != ISD::ConstantFP)
5373       IsAllConstants = false;
5374     if (X86::isZeroNode(Elt))
5375       NumZero++;
5376     else {
5377       NonZeros |= (1 << i);
5378       NumNonZero++;
5379     }
5380   }
5381
5382   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5383   if (NumNonZero == 0)
5384     return DAG.getUNDEF(VT);
5385
5386   // Special case for single non-zero, non-undef, element.
5387   if (NumNonZero == 1) {
5388     unsigned Idx = CountTrailingZeros_32(NonZeros);
5389     SDValue Item = Op.getOperand(Idx);
5390
5391     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5392     // the value are obviously zero, truncate the value to i32 and do the
5393     // insertion that way.  Only do this if the value is non-constant or if the
5394     // value is a constant being inserted into element 0.  It is cheaper to do
5395     // a constant pool load than it is to do a movd + shuffle.
5396     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5397         (!IsAllConstants || Idx == 0)) {
5398       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5399         // Handle SSE only.
5400         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5401         EVT VecVT = MVT::v4i32;
5402         unsigned VecElts = 4;
5403
5404         // Truncate the value (which may itself be a constant) to i32, and
5405         // convert it to a vector with movd (S2V+shuffle to zero extend).
5406         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5407         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5408         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5409
5410         // Now we have our 32-bit value zero extended in the low element of
5411         // a vector.  If Idx != 0, swizzle it into place.
5412         if (Idx != 0) {
5413           SmallVector<int, 4> Mask;
5414           Mask.push_back(Idx);
5415           for (unsigned i = 1; i != VecElts; ++i)
5416             Mask.push_back(i);
5417           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5418                                       &Mask[0]);
5419         }
5420         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5421       }
5422     }
5423
5424     // If we have a constant or non-constant insertion into the low element of
5425     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5426     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5427     // depending on what the source datatype is.
5428     if (Idx == 0) {
5429       if (NumZero == 0)
5430         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5431
5432       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5433           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5434         if (VT.is256BitVector()) {
5435           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5436           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5437                              Item, DAG.getIntPtrConstant(0));
5438         }
5439         assert(VT.is128BitVector() && "Expected an SSE value type!");
5440         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5441         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5442         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5443       }
5444
5445       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5446         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5447         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5448         if (VT.is256BitVector()) {
5449           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5450           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5451         } else {
5452           assert(VT.is128BitVector() && "Expected an SSE value type!");
5453           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5454         }
5455         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5456       }
5457     }
5458
5459     // Is it a vector logical left shift?
5460     if (NumElems == 2 && Idx == 1 &&
5461         X86::isZeroNode(Op.getOperand(0)) &&
5462         !X86::isZeroNode(Op.getOperand(1))) {
5463       unsigned NumBits = VT.getSizeInBits();
5464       return getVShift(true, VT,
5465                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5466                                    VT, Op.getOperand(1)),
5467                        NumBits/2, DAG, *this, dl);
5468     }
5469
5470     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5471       return SDValue();
5472
5473     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5474     // is a non-constant being inserted into an element other than the low one,
5475     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5476     // movd/movss) to move this into the low element, then shuffle it into
5477     // place.
5478     if (EVTBits == 32) {
5479       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5480
5481       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5482       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5483       SmallVector<int, 8> MaskVec;
5484       for (unsigned i = 0; i != NumElems; ++i)
5485         MaskVec.push_back(i == Idx ? 0 : 1);
5486       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5487     }
5488   }
5489
5490   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5491   if (Values.size() == 1) {
5492     if (EVTBits == 32) {
5493       // Instead of a shuffle like this:
5494       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5495       // Check if it's possible to issue this instead.
5496       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5497       unsigned Idx = CountTrailingZeros_32(NonZeros);
5498       SDValue Item = Op.getOperand(Idx);
5499       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5500         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5501     }
5502     return SDValue();
5503   }
5504
5505   // A vector full of immediates; various special cases are already
5506   // handled, so this is best done with a single constant-pool load.
5507   if (IsAllConstants)
5508     return SDValue();
5509
5510   // For AVX-length vectors, build the individual 128-bit pieces and use
5511   // shuffles to put them in place.
5512   if (VT.is256BitVector()) {
5513     SmallVector<SDValue, 32> V;
5514     for (unsigned i = 0; i != NumElems; ++i)
5515       V.push_back(Op.getOperand(i));
5516
5517     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5518
5519     // Build both the lower and upper subvector.
5520     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5521     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5522                                 NumElems/2);
5523
5524     // Recreate the wider vector with the lower and upper part.
5525     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5526   }
5527
5528   // Let legalizer expand 2-wide build_vectors.
5529   if (EVTBits == 64) {
5530     if (NumNonZero == 1) {
5531       // One half is zero or undef.
5532       unsigned Idx = CountTrailingZeros_32(NonZeros);
5533       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5534                                  Op.getOperand(Idx));
5535       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5536     }
5537     return SDValue();
5538   }
5539
5540   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5541   if (EVTBits == 8 && NumElems == 16) {
5542     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5543                                         Subtarget, *this);
5544     if (V.getNode()) return V;
5545   }
5546
5547   if (EVTBits == 16 && NumElems == 8) {
5548     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5549                                       Subtarget, *this);
5550     if (V.getNode()) return V;
5551   }
5552
5553   // If element VT is == 32 bits, turn it into a number of shuffles.
5554   SmallVector<SDValue, 8> V(NumElems);
5555   if (NumElems == 4 && NumZero > 0) {
5556     for (unsigned i = 0; i < 4; ++i) {
5557       bool isZero = !(NonZeros & (1 << i));
5558       if (isZero)
5559         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5560       else
5561         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5562     }
5563
5564     for (unsigned i = 0; i < 2; ++i) {
5565       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5566         default: break;
5567         case 0:
5568           V[i] = V[i*2];  // Must be a zero vector.
5569           break;
5570         case 1:
5571           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5572           break;
5573         case 2:
5574           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5575           break;
5576         case 3:
5577           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5578           break;
5579       }
5580     }
5581
5582     bool Reverse1 = (NonZeros & 0x3) == 2;
5583     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5584     int MaskVec[] = {
5585       Reverse1 ? 1 : 0,
5586       Reverse1 ? 0 : 1,
5587       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5588       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5589     };
5590     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5591   }
5592
5593   if (Values.size() > 1 && VT.is128BitVector()) {
5594     // Check for a build vector of consecutive loads.
5595     for (unsigned i = 0; i < NumElems; ++i)
5596       V[i] = Op.getOperand(i);
5597
5598     // Check for elements which are consecutive loads.
5599     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5600     if (LD.getNode())
5601       return LD;
5602
5603     // Check for a build vector from mostly shuffle plus few inserting.
5604     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5605     if (Sh.getNode())
5606       return Sh;
5607
5608     // For SSE 4.1, use insertps to put the high elements into the low element.
5609     if (getSubtarget()->hasSSE41()) {
5610       SDValue Result;
5611       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5612         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5613       else
5614         Result = DAG.getUNDEF(VT);
5615
5616       for (unsigned i = 1; i < NumElems; ++i) {
5617         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5618         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5619                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5620       }
5621       return Result;
5622     }
5623
5624     // Otherwise, expand into a number of unpckl*, start by extending each of
5625     // our (non-undef) elements to the full vector width with the element in the
5626     // bottom slot of the vector (which generates no code for SSE).
5627     for (unsigned i = 0; i < NumElems; ++i) {
5628       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5629         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5630       else
5631         V[i] = DAG.getUNDEF(VT);
5632     }
5633
5634     // Next, we iteratively mix elements, e.g. for v4f32:
5635     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5636     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5637     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5638     unsigned EltStride = NumElems >> 1;
5639     while (EltStride != 0) {
5640       for (unsigned i = 0; i < EltStride; ++i) {
5641         // If V[i+EltStride] is undef and this is the first round of mixing,
5642         // then it is safe to just drop this shuffle: V[i] is already in the
5643         // right place, the one element (since it's the first round) being
5644         // inserted as undef can be dropped.  This isn't safe for successive
5645         // rounds because they will permute elements within both vectors.
5646         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5647             EltStride == NumElems/2)
5648           continue;
5649
5650         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5651       }
5652       EltStride >>= 1;
5653     }
5654     return V[0];
5655   }
5656   return SDValue();
5657 }
5658
5659 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5660 // to create 256-bit vectors from two other 128-bit ones.
5661 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5662   DebugLoc dl = Op.getDebugLoc();
5663   MVT ResVT = Op.getValueType().getSimpleVT();
5664
5665   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5666
5667   SDValue V1 = Op.getOperand(0);
5668   SDValue V2 = Op.getOperand(1);
5669   unsigned NumElems = ResVT.getVectorNumElements();
5670
5671   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5672 }
5673
5674 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5675   assert(Op.getNumOperands() == 2);
5676
5677   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5678   // from two other 128-bit ones.
5679   return LowerAVXCONCAT_VECTORS(Op, DAG);
5680 }
5681
5682 // Try to lower a shuffle node into a simple blend instruction.
5683 static SDValue
5684 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5685                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5686   SDValue V1 = SVOp->getOperand(0);
5687   SDValue V2 = SVOp->getOperand(1);
5688   DebugLoc dl = SVOp->getDebugLoc();
5689   MVT VT = SVOp->getValueType(0).getSimpleVT();
5690   MVT EltVT = VT.getVectorElementType();
5691   unsigned NumElems = VT.getVectorNumElements();
5692
5693   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5694     return SDValue();
5695   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5696     return SDValue();
5697
5698   // Check the mask for BLEND and build the value.
5699   unsigned MaskValue = 0;
5700   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5701   unsigned NumLanes = (NumElems-1)/8 + 1;
5702   unsigned NumElemsInLane = NumElems / NumLanes;
5703
5704   // Blend for v16i16 should be symetric for the both lanes.
5705   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5706
5707     int SndLaneEltIdx = (NumLanes == 2) ?
5708       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5709     int EltIdx = SVOp->getMaskElt(i);
5710
5711     if ((EltIdx < 0 || EltIdx == (int)i) &&
5712         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5713       continue;
5714
5715     if (((unsigned)EltIdx == (i + NumElems)) &&
5716         (SndLaneEltIdx < 0 ||
5717          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5718       MaskValue |= (1<<i);
5719     else
5720       return SDValue();
5721   }
5722
5723   // Convert i32 vectors to floating point if it is not AVX2.
5724   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5725   MVT BlendVT = VT;
5726   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5727     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5728                                NumElems);
5729     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5730     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5731   }
5732
5733   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5734                             DAG.getConstant(MaskValue, MVT::i32));
5735   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5736 }
5737
5738 // v8i16 shuffles - Prefer shuffles in the following order:
5739 // 1. [all]   pshuflw, pshufhw, optional move
5740 // 2. [ssse3] 1 x pshufb
5741 // 3. [ssse3] 2 x pshufb + 1 x por
5742 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5743 static SDValue
5744 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5745                          SelectionDAG &DAG) {
5746   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5747   SDValue V1 = SVOp->getOperand(0);
5748   SDValue V2 = SVOp->getOperand(1);
5749   DebugLoc dl = SVOp->getDebugLoc();
5750   SmallVector<int, 8> MaskVals;
5751
5752   // Determine if more than 1 of the words in each of the low and high quadwords
5753   // of the result come from the same quadword of one of the two inputs.  Undef
5754   // mask values count as coming from any quadword, for better codegen.
5755   unsigned LoQuad[] = { 0, 0, 0, 0 };
5756   unsigned HiQuad[] = { 0, 0, 0, 0 };
5757   std::bitset<4> InputQuads;
5758   for (unsigned i = 0; i < 8; ++i) {
5759     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5760     int EltIdx = SVOp->getMaskElt(i);
5761     MaskVals.push_back(EltIdx);
5762     if (EltIdx < 0) {
5763       ++Quad[0];
5764       ++Quad[1];
5765       ++Quad[2];
5766       ++Quad[3];
5767       continue;
5768     }
5769     ++Quad[EltIdx / 4];
5770     InputQuads.set(EltIdx / 4);
5771   }
5772
5773   int BestLoQuad = -1;
5774   unsigned MaxQuad = 1;
5775   for (unsigned i = 0; i < 4; ++i) {
5776     if (LoQuad[i] > MaxQuad) {
5777       BestLoQuad = i;
5778       MaxQuad = LoQuad[i];
5779     }
5780   }
5781
5782   int BestHiQuad = -1;
5783   MaxQuad = 1;
5784   for (unsigned i = 0; i < 4; ++i) {
5785     if (HiQuad[i] > MaxQuad) {
5786       BestHiQuad = i;
5787       MaxQuad = HiQuad[i];
5788     }
5789   }
5790
5791   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5792   // of the two input vectors, shuffle them into one input vector so only a
5793   // single pshufb instruction is necessary. If There are more than 2 input
5794   // quads, disable the next transformation since it does not help SSSE3.
5795   bool V1Used = InputQuads[0] || InputQuads[1];
5796   bool V2Used = InputQuads[2] || InputQuads[3];
5797   if (Subtarget->hasSSSE3()) {
5798     if (InputQuads.count() == 2 && V1Used && V2Used) {
5799       BestLoQuad = InputQuads[0] ? 0 : 1;
5800       BestHiQuad = InputQuads[2] ? 2 : 3;
5801     }
5802     if (InputQuads.count() > 2) {
5803       BestLoQuad = -1;
5804       BestHiQuad = -1;
5805     }
5806   }
5807
5808   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5809   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5810   // words from all 4 input quadwords.
5811   SDValue NewV;
5812   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5813     int MaskV[] = {
5814       BestLoQuad < 0 ? 0 : BestLoQuad,
5815       BestHiQuad < 0 ? 1 : BestHiQuad
5816     };
5817     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5818                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5819                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5820     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5821
5822     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5823     // source words for the shuffle, to aid later transformations.
5824     bool AllWordsInNewV = true;
5825     bool InOrder[2] = { true, true };
5826     for (unsigned i = 0; i != 8; ++i) {
5827       int idx = MaskVals[i];
5828       if (idx != (int)i)
5829         InOrder[i/4] = false;
5830       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5831         continue;
5832       AllWordsInNewV = false;
5833       break;
5834     }
5835
5836     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5837     if (AllWordsInNewV) {
5838       for (int i = 0; i != 8; ++i) {
5839         int idx = MaskVals[i];
5840         if (idx < 0)
5841           continue;
5842         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5843         if ((idx != i) && idx < 4)
5844           pshufhw = false;
5845         if ((idx != i) && idx > 3)
5846           pshuflw = false;
5847       }
5848       V1 = NewV;
5849       V2Used = false;
5850       BestLoQuad = 0;
5851       BestHiQuad = 1;
5852     }
5853
5854     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5855     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5856     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5857       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5858       unsigned TargetMask = 0;
5859       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5860                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5861       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5862       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5863                              getShufflePSHUFLWImmediate(SVOp);
5864       V1 = NewV.getOperand(0);
5865       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5866     }
5867   }
5868
5869   // Promote splats to a larger type which usually leads to more efficient code.
5870   // FIXME: Is this true if pshufb is available?
5871   if (SVOp->isSplat())
5872     return PromoteSplat(SVOp, DAG);
5873
5874   // If we have SSSE3, and all words of the result are from 1 input vector,
5875   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5876   // is present, fall back to case 4.
5877   if (Subtarget->hasSSSE3()) {
5878     SmallVector<SDValue,16> pshufbMask;
5879
5880     // If we have elements from both input vectors, set the high bit of the
5881     // shuffle mask element to zero out elements that come from V2 in the V1
5882     // mask, and elements that come from V1 in the V2 mask, so that the two
5883     // results can be OR'd together.
5884     bool TwoInputs = V1Used && V2Used;
5885     for (unsigned i = 0; i != 8; ++i) {
5886       int EltIdx = MaskVals[i] * 2;
5887       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5888       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5889       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5890       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5891     }
5892     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5893     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5894                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5895                                  MVT::v16i8, &pshufbMask[0], 16));
5896     if (!TwoInputs)
5897       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5898
5899     // Calculate the shuffle mask for the second input, shuffle it, and
5900     // OR it with the first shuffled input.
5901     pshufbMask.clear();
5902     for (unsigned i = 0; i != 8; ++i) {
5903       int EltIdx = MaskVals[i] * 2;
5904       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5905       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5906       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5907       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5908     }
5909     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5910     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5911                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5912                                  MVT::v16i8, &pshufbMask[0], 16));
5913     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5914     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5915   }
5916
5917   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5918   // and update MaskVals with new element order.
5919   std::bitset<8> InOrder;
5920   if (BestLoQuad >= 0) {
5921     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5922     for (int i = 0; i != 4; ++i) {
5923       int idx = MaskVals[i];
5924       if (idx < 0) {
5925         InOrder.set(i);
5926       } else if ((idx / 4) == BestLoQuad) {
5927         MaskV[i] = idx & 3;
5928         InOrder.set(i);
5929       }
5930     }
5931     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5932                                 &MaskV[0]);
5933
5934     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5935       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5936       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5937                                   NewV.getOperand(0),
5938                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5939     }
5940   }
5941
5942   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5943   // and update MaskVals with the new element order.
5944   if (BestHiQuad >= 0) {
5945     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5946     for (unsigned i = 4; i != 8; ++i) {
5947       int idx = MaskVals[i];
5948       if (idx < 0) {
5949         InOrder.set(i);
5950       } else if ((idx / 4) == BestHiQuad) {
5951         MaskV[i] = (idx & 3) + 4;
5952         InOrder.set(i);
5953       }
5954     }
5955     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5956                                 &MaskV[0]);
5957
5958     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5959       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5960       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5961                                   NewV.getOperand(0),
5962                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5963     }
5964   }
5965
5966   // In case BestHi & BestLo were both -1, which means each quadword has a word
5967   // from each of the four input quadwords, calculate the InOrder bitvector now
5968   // before falling through to the insert/extract cleanup.
5969   if (BestLoQuad == -1 && BestHiQuad == -1) {
5970     NewV = V1;
5971     for (int i = 0; i != 8; ++i)
5972       if (MaskVals[i] < 0 || MaskVals[i] == i)
5973         InOrder.set(i);
5974   }
5975
5976   // The other elements are put in the right place using pextrw and pinsrw.
5977   for (unsigned i = 0; i != 8; ++i) {
5978     if (InOrder[i])
5979       continue;
5980     int EltIdx = MaskVals[i];
5981     if (EltIdx < 0)
5982       continue;
5983     SDValue ExtOp = (EltIdx < 8) ?
5984       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5985                   DAG.getIntPtrConstant(EltIdx)) :
5986       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5987                   DAG.getIntPtrConstant(EltIdx - 8));
5988     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5989                        DAG.getIntPtrConstant(i));
5990   }
5991   return NewV;
5992 }
5993
5994 // v16i8 shuffles - Prefer shuffles in the following order:
5995 // 1. [ssse3] 1 x pshufb
5996 // 2. [ssse3] 2 x pshufb + 1 x por
5997 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5998 static
5999 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6000                                  SelectionDAG &DAG,
6001                                  const X86TargetLowering &TLI) {
6002   SDValue V1 = SVOp->getOperand(0);
6003   SDValue V2 = SVOp->getOperand(1);
6004   DebugLoc dl = SVOp->getDebugLoc();
6005   ArrayRef<int> MaskVals = SVOp->getMask();
6006
6007   // Promote splats to a larger type which usually leads to more efficient code.
6008   // FIXME: Is this true if pshufb is available?
6009   if (SVOp->isSplat())
6010     return PromoteSplat(SVOp, DAG);
6011
6012   // If we have SSSE3, case 1 is generated when all result bytes come from
6013   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6014   // present, fall back to case 3.
6015
6016   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6017   if (TLI.getSubtarget()->hasSSSE3()) {
6018     SmallVector<SDValue,16> pshufbMask;
6019
6020     // If all result elements are from one input vector, then only translate
6021     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6022     //
6023     // Otherwise, we have elements from both input vectors, and must zero out
6024     // elements that come from V2 in the first mask, and V1 in the second mask
6025     // so that we can OR them together.
6026     for (unsigned i = 0; i != 16; ++i) {
6027       int EltIdx = MaskVals[i];
6028       if (EltIdx < 0 || EltIdx >= 16)
6029         EltIdx = 0x80;
6030       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6031     }
6032     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6033                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6034                                  MVT::v16i8, &pshufbMask[0], 16));
6035
6036     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6037     // the 2nd operand if it's undefined or zero.
6038     if (V2.getOpcode() == ISD::UNDEF ||
6039         ISD::isBuildVectorAllZeros(V2.getNode()))
6040       return V1;
6041
6042     // Calculate the shuffle mask for the second input, shuffle it, and
6043     // OR it with the first shuffled input.
6044     pshufbMask.clear();
6045     for (unsigned i = 0; i != 16; ++i) {
6046       int EltIdx = MaskVals[i];
6047       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6048       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6049     }
6050     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6051                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6052                                  MVT::v16i8, &pshufbMask[0], 16));
6053     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6054   }
6055
6056   // No SSSE3 - Calculate in place words and then fix all out of place words
6057   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6058   // the 16 different words that comprise the two doublequadword input vectors.
6059   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6060   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6061   SDValue NewV = V1;
6062   for (int i = 0; i != 8; ++i) {
6063     int Elt0 = MaskVals[i*2];
6064     int Elt1 = MaskVals[i*2+1];
6065
6066     // This word of the result is all undef, skip it.
6067     if (Elt0 < 0 && Elt1 < 0)
6068       continue;
6069
6070     // This word of the result is already in the correct place, skip it.
6071     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6072       continue;
6073
6074     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6075     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6076     SDValue InsElt;
6077
6078     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6079     // using a single extract together, load it and store it.
6080     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6081       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6082                            DAG.getIntPtrConstant(Elt1 / 2));
6083       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6084                         DAG.getIntPtrConstant(i));
6085       continue;
6086     }
6087
6088     // If Elt1 is defined, extract it from the appropriate source.  If the
6089     // source byte is not also odd, shift the extracted word left 8 bits
6090     // otherwise clear the bottom 8 bits if we need to do an or.
6091     if (Elt1 >= 0) {
6092       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6093                            DAG.getIntPtrConstant(Elt1 / 2));
6094       if ((Elt1 & 1) == 0)
6095         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6096                              DAG.getConstant(8,
6097                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6098       else if (Elt0 >= 0)
6099         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6100                              DAG.getConstant(0xFF00, MVT::i16));
6101     }
6102     // If Elt0 is defined, extract it from the appropriate source.  If the
6103     // source byte is not also even, shift the extracted word right 8 bits. If
6104     // Elt1 was also defined, OR the extracted values together before
6105     // inserting them in the result.
6106     if (Elt0 >= 0) {
6107       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6108                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6109       if ((Elt0 & 1) != 0)
6110         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6111                               DAG.getConstant(8,
6112                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6113       else if (Elt1 >= 0)
6114         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6115                              DAG.getConstant(0x00FF, MVT::i16));
6116       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6117                          : InsElt0;
6118     }
6119     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6120                        DAG.getIntPtrConstant(i));
6121   }
6122   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6123 }
6124
6125 // v32i8 shuffles - Translate to VPSHUFB if possible.
6126 static
6127 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6128                                  const X86Subtarget *Subtarget,
6129                                  SelectionDAG &DAG) {
6130   MVT VT = SVOp->getValueType(0).getSimpleVT();
6131   SDValue V1 = SVOp->getOperand(0);
6132   SDValue V2 = SVOp->getOperand(1);
6133   DebugLoc dl = SVOp->getDebugLoc();
6134   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6135
6136   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6137   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6138   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6139
6140   // VPSHUFB may be generated if
6141   // (1) one of input vector is undefined or zeroinitializer.
6142   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6143   // And (2) the mask indexes don't cross the 128-bit lane.
6144   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6145       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6146     return SDValue();
6147
6148   if (V1IsAllZero && !V2IsAllZero) {
6149     CommuteVectorShuffleMask(MaskVals, 32);
6150     V1 = V2;
6151   }
6152   SmallVector<SDValue, 32> pshufbMask;
6153   for (unsigned i = 0; i != 32; i++) {
6154     int EltIdx = MaskVals[i];
6155     if (EltIdx < 0 || EltIdx >= 32)
6156       EltIdx = 0x80;
6157     else {
6158       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6159         // Cross lane is not allowed.
6160         return SDValue();
6161       EltIdx &= 0xf;
6162     }
6163     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6164   }
6165   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6166                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6167                                   MVT::v32i8, &pshufbMask[0], 32));
6168 }
6169
6170 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6171 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6172 /// done when every pair / quad of shuffle mask elements point to elements in
6173 /// the right sequence. e.g.
6174 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6175 static
6176 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6177                                  SelectionDAG &DAG) {
6178   MVT VT = SVOp->getValueType(0).getSimpleVT();
6179   DebugLoc dl = SVOp->getDebugLoc();
6180   unsigned NumElems = VT.getVectorNumElements();
6181   MVT NewVT;
6182   unsigned Scale;
6183   switch (VT.SimpleTy) {
6184   default: llvm_unreachable("Unexpected!");
6185   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6186   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6187   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6188   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6189   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6190   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6191   }
6192
6193   SmallVector<int, 8> MaskVec;
6194   for (unsigned i = 0; i != NumElems; i += Scale) {
6195     int StartIdx = -1;
6196     for (unsigned j = 0; j != Scale; ++j) {
6197       int EltIdx = SVOp->getMaskElt(i+j);
6198       if (EltIdx < 0)
6199         continue;
6200       if (StartIdx < 0)
6201         StartIdx = (EltIdx / Scale);
6202       if (EltIdx != (int)(StartIdx*Scale + j))
6203         return SDValue();
6204     }
6205     MaskVec.push_back(StartIdx);
6206   }
6207
6208   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6209   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6210   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6211 }
6212
6213 /// getVZextMovL - Return a zero-extending vector move low node.
6214 ///
6215 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6216                             SDValue SrcOp, SelectionDAG &DAG,
6217                             const X86Subtarget *Subtarget, DebugLoc dl) {
6218   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6219     LoadSDNode *LD = NULL;
6220     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6221       LD = dyn_cast<LoadSDNode>(SrcOp);
6222     if (!LD) {
6223       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6224       // instead.
6225       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6226       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6227           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6228           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6229           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6230         // PR2108
6231         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6232         return DAG.getNode(ISD::BITCAST, dl, VT,
6233                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6234                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6235                                                    OpVT,
6236                                                    SrcOp.getOperand(0)
6237                                                           .getOperand(0))));
6238       }
6239     }
6240   }
6241
6242   return DAG.getNode(ISD::BITCAST, dl, VT,
6243                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6244                                  DAG.getNode(ISD::BITCAST, dl,
6245                                              OpVT, SrcOp)));
6246 }
6247
6248 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6249 /// which could not be matched by any known target speficic shuffle
6250 static SDValue
6251 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6252
6253   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6254   if (NewOp.getNode())
6255     return NewOp;
6256
6257   MVT VT = SVOp->getValueType(0).getSimpleVT();
6258
6259   unsigned NumElems = VT.getVectorNumElements();
6260   unsigned NumLaneElems = NumElems / 2;
6261
6262   DebugLoc dl = SVOp->getDebugLoc();
6263   MVT EltVT = VT.getVectorElementType();
6264   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6265   SDValue Output[2];
6266
6267   SmallVector<int, 16> Mask;
6268   for (unsigned l = 0; l < 2; ++l) {
6269     // Build a shuffle mask for the output, discovering on the fly which
6270     // input vectors to use as shuffle operands (recorded in InputUsed).
6271     // If building a suitable shuffle vector proves too hard, then bail
6272     // out with UseBuildVector set.
6273     bool UseBuildVector = false;
6274     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6275     unsigned LaneStart = l * NumLaneElems;
6276     for (unsigned i = 0; i != NumLaneElems; ++i) {
6277       // The mask element.  This indexes into the input.
6278       int Idx = SVOp->getMaskElt(i+LaneStart);
6279       if (Idx < 0) {
6280         // the mask element does not index into any input vector.
6281         Mask.push_back(-1);
6282         continue;
6283       }
6284
6285       // The input vector this mask element indexes into.
6286       int Input = Idx / NumLaneElems;
6287
6288       // Turn the index into an offset from the start of the input vector.
6289       Idx -= Input * NumLaneElems;
6290
6291       // Find or create a shuffle vector operand to hold this input.
6292       unsigned OpNo;
6293       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6294         if (InputUsed[OpNo] == Input)
6295           // This input vector is already an operand.
6296           break;
6297         if (InputUsed[OpNo] < 0) {
6298           // Create a new operand for this input vector.
6299           InputUsed[OpNo] = Input;
6300           break;
6301         }
6302       }
6303
6304       if (OpNo >= array_lengthof(InputUsed)) {
6305         // More than two input vectors used!  Give up on trying to create a
6306         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6307         UseBuildVector = true;
6308         break;
6309       }
6310
6311       // Add the mask index for the new shuffle vector.
6312       Mask.push_back(Idx + OpNo * NumLaneElems);
6313     }
6314
6315     if (UseBuildVector) {
6316       SmallVector<SDValue, 16> SVOps;
6317       for (unsigned i = 0; i != NumLaneElems; ++i) {
6318         // The mask element.  This indexes into the input.
6319         int Idx = SVOp->getMaskElt(i+LaneStart);
6320         if (Idx < 0) {
6321           SVOps.push_back(DAG.getUNDEF(EltVT));
6322           continue;
6323         }
6324
6325         // The input vector this mask element indexes into.
6326         int Input = Idx / NumElems;
6327
6328         // Turn the index into an offset from the start of the input vector.
6329         Idx -= Input * NumElems;
6330
6331         // Extract the vector element by hand.
6332         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6333                                     SVOp->getOperand(Input),
6334                                     DAG.getIntPtrConstant(Idx)));
6335       }
6336
6337       // Construct the output using a BUILD_VECTOR.
6338       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6339                               SVOps.size());
6340     } else if (InputUsed[0] < 0) {
6341       // No input vectors were used! The result is undefined.
6342       Output[l] = DAG.getUNDEF(NVT);
6343     } else {
6344       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6345                                         (InputUsed[0] % 2) * NumLaneElems,
6346                                         DAG, dl);
6347       // If only one input was used, use an undefined vector for the other.
6348       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6349         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6350                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6351       // At least one input vector was used. Create a new shuffle vector.
6352       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6353     }
6354
6355     Mask.clear();
6356   }
6357
6358   // Concatenate the result back
6359   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6360 }
6361
6362 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6363 /// 4 elements, and match them with several different shuffle types.
6364 static SDValue
6365 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6366   SDValue V1 = SVOp->getOperand(0);
6367   SDValue V2 = SVOp->getOperand(1);
6368   DebugLoc dl = SVOp->getDebugLoc();
6369   MVT VT = SVOp->getValueType(0).getSimpleVT();
6370
6371   assert(VT.is128BitVector() && "Unsupported vector size");
6372
6373   std::pair<int, int> Locs[4];
6374   int Mask1[] = { -1, -1, -1, -1 };
6375   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6376
6377   unsigned NumHi = 0;
6378   unsigned NumLo = 0;
6379   for (unsigned i = 0; i != 4; ++i) {
6380     int Idx = PermMask[i];
6381     if (Idx < 0) {
6382       Locs[i] = std::make_pair(-1, -1);
6383     } else {
6384       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6385       if (Idx < 4) {
6386         Locs[i] = std::make_pair(0, NumLo);
6387         Mask1[NumLo] = Idx;
6388         NumLo++;
6389       } else {
6390         Locs[i] = std::make_pair(1, NumHi);
6391         if (2+NumHi < 4)
6392           Mask1[2+NumHi] = Idx;
6393         NumHi++;
6394       }
6395     }
6396   }
6397
6398   if (NumLo <= 2 && NumHi <= 2) {
6399     // If no more than two elements come from either vector. This can be
6400     // implemented with two shuffles. First shuffle gather the elements.
6401     // The second shuffle, which takes the first shuffle as both of its
6402     // vector operands, put the elements into the right order.
6403     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6404
6405     int Mask2[] = { -1, -1, -1, -1 };
6406
6407     for (unsigned i = 0; i != 4; ++i)
6408       if (Locs[i].first != -1) {
6409         unsigned Idx = (i < 2) ? 0 : 4;
6410         Idx += Locs[i].first * 2 + Locs[i].second;
6411         Mask2[i] = Idx;
6412       }
6413
6414     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6415   }
6416
6417   if (NumLo == 3 || NumHi == 3) {
6418     // Otherwise, we must have three elements from one vector, call it X, and
6419     // one element from the other, call it Y.  First, use a shufps to build an
6420     // intermediate vector with the one element from Y and the element from X
6421     // that will be in the same half in the final destination (the indexes don't
6422     // matter). Then, use a shufps to build the final vector, taking the half
6423     // containing the element from Y from the intermediate, and the other half
6424     // from X.
6425     if (NumHi == 3) {
6426       // Normalize it so the 3 elements come from V1.
6427       CommuteVectorShuffleMask(PermMask, 4);
6428       std::swap(V1, V2);
6429     }
6430
6431     // Find the element from V2.
6432     unsigned HiIndex;
6433     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6434       int Val = PermMask[HiIndex];
6435       if (Val < 0)
6436         continue;
6437       if (Val >= 4)
6438         break;
6439     }
6440
6441     Mask1[0] = PermMask[HiIndex];
6442     Mask1[1] = -1;
6443     Mask1[2] = PermMask[HiIndex^1];
6444     Mask1[3] = -1;
6445     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6446
6447     if (HiIndex >= 2) {
6448       Mask1[0] = PermMask[0];
6449       Mask1[1] = PermMask[1];
6450       Mask1[2] = HiIndex & 1 ? 6 : 4;
6451       Mask1[3] = HiIndex & 1 ? 4 : 6;
6452       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6453     }
6454
6455     Mask1[0] = HiIndex & 1 ? 2 : 0;
6456     Mask1[1] = HiIndex & 1 ? 0 : 2;
6457     Mask1[2] = PermMask[2];
6458     Mask1[3] = PermMask[3];
6459     if (Mask1[2] >= 0)
6460       Mask1[2] += 4;
6461     if (Mask1[3] >= 0)
6462       Mask1[3] += 4;
6463     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6464   }
6465
6466   // Break it into (shuffle shuffle_hi, shuffle_lo).
6467   int LoMask[] = { -1, -1, -1, -1 };
6468   int HiMask[] = { -1, -1, -1, -1 };
6469
6470   int *MaskPtr = LoMask;
6471   unsigned MaskIdx = 0;
6472   unsigned LoIdx = 0;
6473   unsigned HiIdx = 2;
6474   for (unsigned i = 0; i != 4; ++i) {
6475     if (i == 2) {
6476       MaskPtr = HiMask;
6477       MaskIdx = 1;
6478       LoIdx = 0;
6479       HiIdx = 2;
6480     }
6481     int Idx = PermMask[i];
6482     if (Idx < 0) {
6483       Locs[i] = std::make_pair(-1, -1);
6484     } else if (Idx < 4) {
6485       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6486       MaskPtr[LoIdx] = Idx;
6487       LoIdx++;
6488     } else {
6489       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6490       MaskPtr[HiIdx] = Idx;
6491       HiIdx++;
6492     }
6493   }
6494
6495   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6496   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6497   int MaskOps[] = { -1, -1, -1, -1 };
6498   for (unsigned i = 0; i != 4; ++i)
6499     if (Locs[i].first != -1)
6500       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6501   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6502 }
6503
6504 static bool MayFoldVectorLoad(SDValue V) {
6505   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6506     V = V.getOperand(0);
6507
6508   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6509     V = V.getOperand(0);
6510   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6511       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6512     // BUILD_VECTOR (load), undef
6513     V = V.getOperand(0);
6514
6515   return MayFoldLoad(V);
6516 }
6517
6518 static
6519 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6520   EVT VT = Op.getValueType();
6521
6522   // Canonizalize to v2f64.
6523   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6524   return DAG.getNode(ISD::BITCAST, dl, VT,
6525                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6526                                           V1, DAG));
6527 }
6528
6529 static
6530 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6531                         bool HasSSE2) {
6532   SDValue V1 = Op.getOperand(0);
6533   SDValue V2 = Op.getOperand(1);
6534   EVT VT = Op.getValueType();
6535
6536   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6537
6538   if (HasSSE2 && VT == MVT::v2f64)
6539     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6540
6541   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6542   return DAG.getNode(ISD::BITCAST, dl, VT,
6543                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6544                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6545                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6546 }
6547
6548 static
6549 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6550   SDValue V1 = Op.getOperand(0);
6551   SDValue V2 = Op.getOperand(1);
6552   EVT VT = Op.getValueType();
6553
6554   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6555          "unsupported shuffle type");
6556
6557   if (V2.getOpcode() == ISD::UNDEF)
6558     V2 = V1;
6559
6560   // v4i32 or v4f32
6561   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6562 }
6563
6564 static
6565 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6566   SDValue V1 = Op.getOperand(0);
6567   SDValue V2 = Op.getOperand(1);
6568   EVT VT = Op.getValueType();
6569   unsigned NumElems = VT.getVectorNumElements();
6570
6571   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6572   // operand of these instructions is only memory, so check if there's a
6573   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6574   // same masks.
6575   bool CanFoldLoad = false;
6576
6577   // Trivial case, when V2 comes from a load.
6578   if (MayFoldVectorLoad(V2))
6579     CanFoldLoad = true;
6580
6581   // When V1 is a load, it can be folded later into a store in isel, example:
6582   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6583   //    turns into:
6584   //  (MOVLPSmr addr:$src1, VR128:$src2)
6585   // So, recognize this potential and also use MOVLPS or MOVLPD
6586   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6587     CanFoldLoad = true;
6588
6589   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6590   if (CanFoldLoad) {
6591     if (HasSSE2 && NumElems == 2)
6592       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6593
6594     if (NumElems == 4)
6595       // If we don't care about the second element, proceed to use movss.
6596       if (SVOp->getMaskElt(1) != -1)
6597         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6598   }
6599
6600   // movl and movlp will both match v2i64, but v2i64 is never matched by
6601   // movl earlier because we make it strict to avoid messing with the movlp load
6602   // folding logic (see the code above getMOVLP call). Match it here then,
6603   // this is horrible, but will stay like this until we move all shuffle
6604   // matching to x86 specific nodes. Note that for the 1st condition all
6605   // types are matched with movsd.
6606   if (HasSSE2) {
6607     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6608     // as to remove this logic from here, as much as possible
6609     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6610       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6611     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6612   }
6613
6614   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6615
6616   // Invert the operand order and use SHUFPS to match it.
6617   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6618                               getShuffleSHUFImmediate(SVOp), DAG);
6619 }
6620
6621 // Reduce a vector shuffle to zext.
6622 SDValue
6623 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6624   // PMOVZX is only available from SSE41.
6625   if (!Subtarget->hasSSE41())
6626     return SDValue();
6627
6628   EVT VT = Op.getValueType();
6629
6630   // Only AVX2 support 256-bit vector integer extending.
6631   if (!Subtarget->hasInt256() && VT.is256BitVector())
6632     return SDValue();
6633
6634   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6635   DebugLoc DL = Op.getDebugLoc();
6636   SDValue V1 = Op.getOperand(0);
6637   SDValue V2 = Op.getOperand(1);
6638   unsigned NumElems = VT.getVectorNumElements();
6639
6640   // Extending is an unary operation and the element type of the source vector
6641   // won't be equal to or larger than i64.
6642   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6643       VT.getVectorElementType() == MVT::i64)
6644     return SDValue();
6645
6646   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6647   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6648   while ((1U << Shift) < NumElems) {
6649     if (SVOp->getMaskElt(1U << Shift) == 1)
6650       break;
6651     Shift += 1;
6652     // The maximal ratio is 8, i.e. from i8 to i64.
6653     if (Shift > 3)
6654       return SDValue();
6655   }
6656
6657   // Check the shuffle mask.
6658   unsigned Mask = (1U << Shift) - 1;
6659   for (unsigned i = 0; i != NumElems; ++i) {
6660     int EltIdx = SVOp->getMaskElt(i);
6661     if ((i & Mask) != 0 && EltIdx != -1)
6662       return SDValue();
6663     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6664       return SDValue();
6665   }
6666
6667   LLVMContext *Context = DAG.getContext();
6668   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6669   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6670   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6671
6672   if (!isTypeLegal(NVT))
6673     return SDValue();
6674
6675   // Simplify the operand as it's prepared to be fed into shuffle.
6676   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6677   if (V1.getOpcode() == ISD::BITCAST &&
6678       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6679       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6680       V1.getOperand(0)
6681         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6682     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6683     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6684     ConstantSDNode *CIdx =
6685       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6686     // If it's foldable, i.e. normal load with single use, we will let code
6687     // selection to fold it. Otherwise, we will short the conversion sequence.
6688     if (CIdx && CIdx->getZExtValue() == 0 &&
6689         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6690       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6691         // The "ext_vec_elt" node is wider than the result node.
6692         // In this case we should extract subvector from V.
6693         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6694         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6695         EVT FullVT = V.getValueType();
6696         EVT SubVecVT = EVT::getVectorVT(*Context, 
6697                                         FullVT.getVectorElementType(),
6698                                         FullVT.getVectorNumElements()/Ratio);
6699         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V, 
6700                         DAG.getIntPtrConstant(0));
6701       }
6702       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6703     }
6704   }
6705
6706   return DAG.getNode(ISD::BITCAST, DL, VT,
6707                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6708 }
6709
6710 SDValue
6711 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6712   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6713   MVT VT = Op.getValueType().getSimpleVT();
6714   DebugLoc dl = Op.getDebugLoc();
6715   SDValue V1 = Op.getOperand(0);
6716   SDValue V2 = Op.getOperand(1);
6717
6718   if (isZeroShuffle(SVOp))
6719     return getZeroVector(VT, Subtarget, DAG, dl);
6720
6721   // Handle splat operations
6722   if (SVOp->isSplat()) {
6723     // Use vbroadcast whenever the splat comes from a foldable load
6724     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6725     if (Broadcast.getNode())
6726       return Broadcast;
6727   }
6728
6729   // Check integer expanding shuffles.
6730   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6731   if (NewOp.getNode())
6732     return NewOp;
6733
6734   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6735   // do it!
6736   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6737       VT == MVT::v16i16 || VT == MVT::v32i8) {
6738     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6739     if (NewOp.getNode())
6740       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6741   } else if ((VT == MVT::v4i32 ||
6742              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6743     // FIXME: Figure out a cleaner way to do this.
6744     // Try to make use of movq to zero out the top part.
6745     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6746       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6747       if (NewOp.getNode()) {
6748         MVT NewVT = NewOp.getValueType().getSimpleVT();
6749         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6750                                NewVT, true, false))
6751           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6752                               DAG, Subtarget, dl);
6753       }
6754     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6755       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6756       if (NewOp.getNode()) {
6757         MVT NewVT = NewOp.getValueType().getSimpleVT();
6758         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6759           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6760                               DAG, Subtarget, dl);
6761       }
6762     }
6763   }
6764   return SDValue();
6765 }
6766
6767 SDValue
6768 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6769   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6770   SDValue V1 = Op.getOperand(0);
6771   SDValue V2 = Op.getOperand(1);
6772   MVT VT = Op.getValueType().getSimpleVT();
6773   DebugLoc dl = Op.getDebugLoc();
6774   unsigned NumElems = VT.getVectorNumElements();
6775   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6776   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6777   bool V1IsSplat = false;
6778   bool V2IsSplat = false;
6779   bool HasSSE2 = Subtarget->hasSSE2();
6780   bool HasFp256    = Subtarget->hasFp256();
6781   bool HasInt256   = Subtarget->hasInt256();
6782   MachineFunction &MF = DAG.getMachineFunction();
6783   bool OptForSize = MF.getFunction()->getAttributes().
6784     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6785
6786   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6787
6788   if (V1IsUndef && V2IsUndef)
6789     return DAG.getUNDEF(VT);
6790
6791   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6792
6793   // Vector shuffle lowering takes 3 steps:
6794   //
6795   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6796   //    narrowing and commutation of operands should be handled.
6797   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6798   //    shuffle nodes.
6799   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6800   //    so the shuffle can be broken into other shuffles and the legalizer can
6801   //    try the lowering again.
6802   //
6803   // The general idea is that no vector_shuffle operation should be left to
6804   // be matched during isel, all of them must be converted to a target specific
6805   // node here.
6806
6807   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6808   // narrowing and commutation of operands should be handled. The actual code
6809   // doesn't include all of those, work in progress...
6810   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6811   if (NewOp.getNode())
6812     return NewOp;
6813
6814   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6815
6816   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6817   // unpckh_undef). Only use pshufd if speed is more important than size.
6818   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6819     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6820   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6821     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6822
6823   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6824       V2IsUndef && MayFoldVectorLoad(V1))
6825     return getMOVDDup(Op, dl, V1, DAG);
6826
6827   if (isMOVHLPS_v_undef_Mask(M, VT))
6828     return getMOVHighToLow(Op, dl, DAG);
6829
6830   // Use to match splats
6831   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6832       (VT == MVT::v2f64 || VT == MVT::v2i64))
6833     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6834
6835   if (isPSHUFDMask(M, VT)) {
6836     // The actual implementation will match the mask in the if above and then
6837     // during isel it can match several different instructions, not only pshufd
6838     // as its name says, sad but true, emulate the behavior for now...
6839     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6840       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6841
6842     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6843
6844     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6845       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6846
6847     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6848       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6849                                   DAG);
6850
6851     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6852                                 TargetMask, DAG);
6853   }
6854
6855   // Check if this can be converted into a logical shift.
6856   bool isLeft = false;
6857   unsigned ShAmt = 0;
6858   SDValue ShVal;
6859   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6860   if (isShift && ShVal.hasOneUse()) {
6861     // If the shifted value has multiple uses, it may be cheaper to use
6862     // v_set0 + movlhps or movhlps, etc.
6863     MVT EltVT = VT.getVectorElementType();
6864     ShAmt *= EltVT.getSizeInBits();
6865     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6866   }
6867
6868   if (isMOVLMask(M, VT)) {
6869     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6870       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6871     if (!isMOVLPMask(M, VT)) {
6872       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6873         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6874
6875       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6876         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6877     }
6878   }
6879
6880   // FIXME: fold these into legal mask.
6881   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6882     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6883
6884   if (isMOVHLPSMask(M, VT))
6885     return getMOVHighToLow(Op, dl, DAG);
6886
6887   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6888     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6889
6890   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6891     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6892
6893   if (isMOVLPMask(M, VT))
6894     return getMOVLP(Op, dl, DAG, HasSSE2);
6895
6896   if (ShouldXformToMOVHLPS(M, VT) ||
6897       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6898     return CommuteVectorShuffle(SVOp, DAG);
6899
6900   if (isShift) {
6901     // No better options. Use a vshldq / vsrldq.
6902     MVT EltVT = VT.getVectorElementType();
6903     ShAmt *= EltVT.getSizeInBits();
6904     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6905   }
6906
6907   bool Commuted = false;
6908   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6909   // 1,1,1,1 -> v8i16 though.
6910   V1IsSplat = isSplatVector(V1.getNode());
6911   V2IsSplat = isSplatVector(V2.getNode());
6912
6913   // Canonicalize the splat or undef, if present, to be on the RHS.
6914   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6915     CommuteVectorShuffleMask(M, NumElems);
6916     std::swap(V1, V2);
6917     std::swap(V1IsSplat, V2IsSplat);
6918     Commuted = true;
6919   }
6920
6921   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6922     // Shuffling low element of v1 into undef, just return v1.
6923     if (V2IsUndef)
6924       return V1;
6925     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6926     // the instruction selector will not match, so get a canonical MOVL with
6927     // swapped operands to undo the commute.
6928     return getMOVL(DAG, dl, VT, V2, V1);
6929   }
6930
6931   if (isUNPCKLMask(M, VT, HasInt256))
6932     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6933
6934   if (isUNPCKHMask(M, VT, HasInt256))
6935     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6936
6937   if (V2IsSplat) {
6938     // Normalize mask so all entries that point to V2 points to its first
6939     // element then try to match unpck{h|l} again. If match, return a
6940     // new vector_shuffle with the corrected mask.p
6941     SmallVector<int, 8> NewMask(M.begin(), M.end());
6942     NormalizeMask(NewMask, NumElems);
6943     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6944       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6945     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6946       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6947   }
6948
6949   if (Commuted) {
6950     // Commute is back and try unpck* again.
6951     // FIXME: this seems wrong.
6952     CommuteVectorShuffleMask(M, NumElems);
6953     std::swap(V1, V2);
6954     std::swap(V1IsSplat, V2IsSplat);
6955     Commuted = false;
6956
6957     if (isUNPCKLMask(M, VT, HasInt256))
6958       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6959
6960     if (isUNPCKHMask(M, VT, HasInt256))
6961       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6962   }
6963
6964   // Normalize the node to match x86 shuffle ops if needed
6965   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6966     return CommuteVectorShuffle(SVOp, DAG);
6967
6968   // The checks below are all present in isShuffleMaskLegal, but they are
6969   // inlined here right now to enable us to directly emit target specific
6970   // nodes, and remove one by one until they don't return Op anymore.
6971
6972   if (isPALIGNRMask(M, VT, Subtarget))
6973     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6974                                 getShufflePALIGNRImmediate(SVOp),
6975                                 DAG);
6976
6977   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6978       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6979     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6980       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6981   }
6982
6983   if (isPSHUFHWMask(M, VT, HasInt256))
6984     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6985                                 getShufflePSHUFHWImmediate(SVOp),
6986                                 DAG);
6987
6988   if (isPSHUFLWMask(M, VT, HasInt256))
6989     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6990                                 getShufflePSHUFLWImmediate(SVOp),
6991                                 DAG);
6992
6993   if (isSHUFPMask(M, VT, HasFp256))
6994     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
6995                                 getShuffleSHUFImmediate(SVOp), DAG);
6996
6997   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6998     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6999   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7000     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7001
7002   //===--------------------------------------------------------------------===//
7003   // Generate target specific nodes for 128 or 256-bit shuffles only
7004   // supported in the AVX instruction set.
7005   //
7006
7007   // Handle VMOVDDUPY permutations
7008   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7009     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7010
7011   // Handle VPERMILPS/D* permutations
7012   if (isVPERMILPMask(M, VT, HasFp256)) {
7013     if (HasInt256 && VT == MVT::v8i32)
7014       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7015                                   getShuffleSHUFImmediate(SVOp), DAG);
7016     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7017                                 getShuffleSHUFImmediate(SVOp), DAG);
7018   }
7019
7020   // Handle VPERM2F128/VPERM2I128 permutations
7021   if (isVPERM2X128Mask(M, VT, HasFp256))
7022     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7023                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7024
7025   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7026   if (BlendOp.getNode())
7027     return BlendOp;
7028
7029   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7030     SmallVector<SDValue, 8> permclMask;
7031     for (unsigned i = 0; i != 8; ++i) {
7032       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7033     }
7034     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7035                                &permclMask[0], 8);
7036     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7037     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7038                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7039   }
7040
7041   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7042     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7043                                 getShuffleCLImmediate(SVOp), DAG);
7044
7045   //===--------------------------------------------------------------------===//
7046   // Since no target specific shuffle was selected for this generic one,
7047   // lower it into other known shuffles. FIXME: this isn't true yet, but
7048   // this is the plan.
7049   //
7050
7051   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7052   if (VT == MVT::v8i16) {
7053     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7054     if (NewOp.getNode())
7055       return NewOp;
7056   }
7057
7058   if (VT == MVT::v16i8) {
7059     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7060     if (NewOp.getNode())
7061       return NewOp;
7062   }
7063
7064   if (VT == MVT::v32i8) {
7065     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7066     if (NewOp.getNode())
7067       return NewOp;
7068   }
7069
7070   // Handle all 128-bit wide vectors with 4 elements, and match them with
7071   // several different shuffle types.
7072   if (NumElems == 4 && VT.is128BitVector())
7073     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7074
7075   // Handle general 256-bit shuffles
7076   if (VT.is256BitVector())
7077     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7078
7079   return SDValue();
7080 }
7081
7082 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7083   MVT VT = Op.getValueType().getSimpleVT();
7084   DebugLoc dl = Op.getDebugLoc();
7085
7086   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7087     return SDValue();
7088
7089   if (VT.getSizeInBits() == 8) {
7090     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7091                                   Op.getOperand(0), Op.getOperand(1));
7092     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7093                                   DAG.getValueType(VT));
7094     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7095   }
7096
7097   if (VT.getSizeInBits() == 16) {
7098     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7099     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7100     if (Idx == 0)
7101       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7102                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7103                                      DAG.getNode(ISD::BITCAST, dl,
7104                                                  MVT::v4i32,
7105                                                  Op.getOperand(0)),
7106                                      Op.getOperand(1)));
7107     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7108                                   Op.getOperand(0), Op.getOperand(1));
7109     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7110                                   DAG.getValueType(VT));
7111     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7112   }
7113
7114   if (VT == MVT::f32) {
7115     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7116     // the result back to FR32 register. It's only worth matching if the
7117     // result has a single use which is a store or a bitcast to i32.  And in
7118     // the case of a store, it's not worth it if the index is a constant 0,
7119     // because a MOVSSmr can be used instead, which is smaller and faster.
7120     if (!Op.hasOneUse())
7121       return SDValue();
7122     SDNode *User = *Op.getNode()->use_begin();
7123     if ((User->getOpcode() != ISD::STORE ||
7124          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7125           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7126         (User->getOpcode() != ISD::BITCAST ||
7127          User->getValueType(0) != MVT::i32))
7128       return SDValue();
7129     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7130                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7131                                               Op.getOperand(0)),
7132                                               Op.getOperand(1));
7133     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7134   }
7135
7136   if (VT == MVT::i32 || VT == MVT::i64) {
7137     // ExtractPS/pextrq works with constant index.
7138     if (isa<ConstantSDNode>(Op.getOperand(1)))
7139       return Op;
7140   }
7141   return SDValue();
7142 }
7143
7144 SDValue
7145 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7146                                            SelectionDAG &DAG) const {
7147   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7148     return SDValue();
7149
7150   SDValue Vec = Op.getOperand(0);
7151   MVT VecVT = Vec.getValueType().getSimpleVT();
7152
7153   // If this is a 256-bit vector result, first extract the 128-bit vector and
7154   // then extract the element from the 128-bit vector.
7155   if (VecVT.is256BitVector()) {
7156     DebugLoc dl = Op.getNode()->getDebugLoc();
7157     unsigned NumElems = VecVT.getVectorNumElements();
7158     SDValue Idx = Op.getOperand(1);
7159     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7160
7161     // Get the 128-bit vector.
7162     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7163
7164     if (IdxVal >= NumElems/2)
7165       IdxVal -= NumElems/2;
7166     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7167                        DAG.getConstant(IdxVal, MVT::i32));
7168   }
7169
7170   assert(VecVT.is128BitVector() && "Unexpected vector length");
7171
7172   if (Subtarget->hasSSE41()) {
7173     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7174     if (Res.getNode())
7175       return Res;
7176   }
7177
7178   MVT VT = Op.getValueType().getSimpleVT();
7179   DebugLoc dl = Op.getDebugLoc();
7180   // TODO: handle v16i8.
7181   if (VT.getSizeInBits() == 16) {
7182     SDValue Vec = Op.getOperand(0);
7183     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7184     if (Idx == 0)
7185       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7186                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7187                                      DAG.getNode(ISD::BITCAST, dl,
7188                                                  MVT::v4i32, Vec),
7189                                      Op.getOperand(1)));
7190     // Transform it so it match pextrw which produces a 32-bit result.
7191     MVT EltVT = MVT::i32;
7192     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7193                                   Op.getOperand(0), Op.getOperand(1));
7194     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7195                                   DAG.getValueType(VT));
7196     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7197   }
7198
7199   if (VT.getSizeInBits() == 32) {
7200     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7201     if (Idx == 0)
7202       return Op;
7203
7204     // SHUFPS the element to the lowest double word, then movss.
7205     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7206     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7207     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7208                                        DAG.getUNDEF(VVT), Mask);
7209     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7210                        DAG.getIntPtrConstant(0));
7211   }
7212
7213   if (VT.getSizeInBits() == 64) {
7214     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7215     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7216     //        to match extract_elt for f64.
7217     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7218     if (Idx == 0)
7219       return Op;
7220
7221     // UNPCKHPD the element to the lowest double word, then movsd.
7222     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7223     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7224     int Mask[2] = { 1, -1 };
7225     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7226     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7227                                        DAG.getUNDEF(VVT), Mask);
7228     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7229                        DAG.getIntPtrConstant(0));
7230   }
7231
7232   return SDValue();
7233 }
7234
7235 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7236   MVT VT = Op.getValueType().getSimpleVT();
7237   MVT EltVT = VT.getVectorElementType();
7238   DebugLoc dl = Op.getDebugLoc();
7239
7240   SDValue N0 = Op.getOperand(0);
7241   SDValue N1 = Op.getOperand(1);
7242   SDValue N2 = Op.getOperand(2);
7243
7244   if (!VT.is128BitVector())
7245     return SDValue();
7246
7247   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7248       isa<ConstantSDNode>(N2)) {
7249     unsigned Opc;
7250     if (VT == MVT::v8i16)
7251       Opc = X86ISD::PINSRW;
7252     else if (VT == MVT::v16i8)
7253       Opc = X86ISD::PINSRB;
7254     else
7255       Opc = X86ISD::PINSRB;
7256
7257     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7258     // argument.
7259     if (N1.getValueType() != MVT::i32)
7260       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7261     if (N2.getValueType() != MVT::i32)
7262       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7263     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7264   }
7265
7266   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7267     // Bits [7:6] of the constant are the source select.  This will always be
7268     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7269     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7270     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7271     // Bits [5:4] of the constant are the destination select.  This is the
7272     //  value of the incoming immediate.
7273     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7274     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7275     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7276     // Create this as a scalar to vector..
7277     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7278     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7279   }
7280
7281   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7282     // PINSR* works with constant index.
7283     return Op;
7284   }
7285   return SDValue();
7286 }
7287
7288 SDValue
7289 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7290   MVT VT = Op.getValueType().getSimpleVT();
7291   MVT EltVT = VT.getVectorElementType();
7292
7293   DebugLoc dl = Op.getDebugLoc();
7294   SDValue N0 = Op.getOperand(0);
7295   SDValue N1 = Op.getOperand(1);
7296   SDValue N2 = Op.getOperand(2);
7297
7298   // If this is a 256-bit vector result, first extract the 128-bit vector,
7299   // insert the element into the extracted half and then place it back.
7300   if (VT.is256BitVector()) {
7301     if (!isa<ConstantSDNode>(N2))
7302       return SDValue();
7303
7304     // Get the desired 128-bit vector half.
7305     unsigned NumElems = VT.getVectorNumElements();
7306     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7307     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7308
7309     // Insert the element into the desired half.
7310     bool Upper = IdxVal >= NumElems/2;
7311     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7312                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7313
7314     // Insert the changed part back to the 256-bit vector
7315     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7316   }
7317
7318   if (Subtarget->hasSSE41())
7319     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7320
7321   if (EltVT == MVT::i8)
7322     return SDValue();
7323
7324   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7325     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7326     // as its second argument.
7327     if (N1.getValueType() != MVT::i32)
7328       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7329     if (N2.getValueType() != MVT::i32)
7330       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7331     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7332   }
7333   return SDValue();
7334 }
7335
7336 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7337   LLVMContext *Context = DAG.getContext();
7338   DebugLoc dl = Op.getDebugLoc();
7339   MVT OpVT = Op.getValueType().getSimpleVT();
7340
7341   // If this is a 256-bit vector result, first insert into a 128-bit
7342   // vector and then insert into the 256-bit vector.
7343   if (!OpVT.is128BitVector()) {
7344     // Insert into a 128-bit vector.
7345     EVT VT128 = EVT::getVectorVT(*Context,
7346                                  OpVT.getVectorElementType(),
7347                                  OpVT.getVectorNumElements() / 2);
7348
7349     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7350
7351     // Insert the 128-bit vector.
7352     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7353   }
7354
7355   if (OpVT == MVT::v1i64 &&
7356       Op.getOperand(0).getValueType() == MVT::i64)
7357     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7358
7359   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7360   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7361   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7362                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7363 }
7364
7365 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7366 // a simple subregister reference or explicit instructions to grab
7367 // upper bits of a vector.
7368 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7369                                       SelectionDAG &DAG) {
7370   if (Subtarget->hasFp256()) {
7371     DebugLoc dl = Op.getNode()->getDebugLoc();
7372     SDValue Vec = Op.getNode()->getOperand(0);
7373     SDValue Idx = Op.getNode()->getOperand(1);
7374
7375     if (Op.getNode()->getValueType(0).is128BitVector() &&
7376         Vec.getNode()->getValueType(0).is256BitVector() &&
7377         isa<ConstantSDNode>(Idx)) {
7378       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7379       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7380     }
7381   }
7382   return SDValue();
7383 }
7384
7385 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7386 // simple superregister reference or explicit instructions to insert
7387 // the upper bits of a vector.
7388 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7389                                      SelectionDAG &DAG) {
7390   if (Subtarget->hasFp256()) {
7391     DebugLoc dl = Op.getNode()->getDebugLoc();
7392     SDValue Vec = Op.getNode()->getOperand(0);
7393     SDValue SubVec = Op.getNode()->getOperand(1);
7394     SDValue Idx = Op.getNode()->getOperand(2);
7395
7396     if (Op.getNode()->getValueType(0).is256BitVector() &&
7397         SubVec.getNode()->getValueType(0).is128BitVector() &&
7398         isa<ConstantSDNode>(Idx)) {
7399       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7400       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7401     }
7402   }
7403   return SDValue();
7404 }
7405
7406 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7407 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7408 // one of the above mentioned nodes. It has to be wrapped because otherwise
7409 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7410 // be used to form addressing mode. These wrapped nodes will be selected
7411 // into MOV32ri.
7412 SDValue
7413 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7414   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7415
7416   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7417   // global base reg.
7418   unsigned char OpFlag = 0;
7419   unsigned WrapperKind = X86ISD::Wrapper;
7420   CodeModel::Model M = getTargetMachine().getCodeModel();
7421
7422   if (Subtarget->isPICStyleRIPRel() &&
7423       (M == CodeModel::Small || M == CodeModel::Kernel))
7424     WrapperKind = X86ISD::WrapperRIP;
7425   else if (Subtarget->isPICStyleGOT())
7426     OpFlag = X86II::MO_GOTOFF;
7427   else if (Subtarget->isPICStyleStubPIC())
7428     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7429
7430   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7431                                              CP->getAlignment(),
7432                                              CP->getOffset(), OpFlag);
7433   DebugLoc DL = CP->getDebugLoc();
7434   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7435   // With PIC, the address is actually $g + Offset.
7436   if (OpFlag) {
7437     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7438                          DAG.getNode(X86ISD::GlobalBaseReg,
7439                                      DebugLoc(), getPointerTy()),
7440                          Result);
7441   }
7442
7443   return Result;
7444 }
7445
7446 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7447   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7448
7449   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7450   // global base reg.
7451   unsigned char OpFlag = 0;
7452   unsigned WrapperKind = X86ISD::Wrapper;
7453   CodeModel::Model M = getTargetMachine().getCodeModel();
7454
7455   if (Subtarget->isPICStyleRIPRel() &&
7456       (M == CodeModel::Small || M == CodeModel::Kernel))
7457     WrapperKind = X86ISD::WrapperRIP;
7458   else if (Subtarget->isPICStyleGOT())
7459     OpFlag = X86II::MO_GOTOFF;
7460   else if (Subtarget->isPICStyleStubPIC())
7461     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7462
7463   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7464                                           OpFlag);
7465   DebugLoc DL = JT->getDebugLoc();
7466   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7467
7468   // With PIC, the address is actually $g + Offset.
7469   if (OpFlag)
7470     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7471                          DAG.getNode(X86ISD::GlobalBaseReg,
7472                                      DebugLoc(), getPointerTy()),
7473                          Result);
7474
7475   return Result;
7476 }
7477
7478 SDValue
7479 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7480   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7481
7482   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7483   // global base reg.
7484   unsigned char OpFlag = 0;
7485   unsigned WrapperKind = X86ISD::Wrapper;
7486   CodeModel::Model M = getTargetMachine().getCodeModel();
7487
7488   if (Subtarget->isPICStyleRIPRel() &&
7489       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7490     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7491       OpFlag = X86II::MO_GOTPCREL;
7492     WrapperKind = X86ISD::WrapperRIP;
7493   } else if (Subtarget->isPICStyleGOT()) {
7494     OpFlag = X86II::MO_GOT;
7495   } else if (Subtarget->isPICStyleStubPIC()) {
7496     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7497   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7498     OpFlag = X86II::MO_DARWIN_NONLAZY;
7499   }
7500
7501   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7502
7503   DebugLoc DL = Op.getDebugLoc();
7504   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7505
7506   // With PIC, the address is actually $g + Offset.
7507   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7508       !Subtarget->is64Bit()) {
7509     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7510                          DAG.getNode(X86ISD::GlobalBaseReg,
7511                                      DebugLoc(), getPointerTy()),
7512                          Result);
7513   }
7514
7515   // For symbols that require a load from a stub to get the address, emit the
7516   // load.
7517   if (isGlobalStubReference(OpFlag))
7518     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7519                          MachinePointerInfo::getGOT(), false, false, false, 0);
7520
7521   return Result;
7522 }
7523
7524 SDValue
7525 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7526   // Create the TargetBlockAddressAddress node.
7527   unsigned char OpFlags =
7528     Subtarget->ClassifyBlockAddressReference();
7529   CodeModel::Model M = getTargetMachine().getCodeModel();
7530   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7531   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7532   DebugLoc dl = Op.getDebugLoc();
7533   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7534                                              OpFlags);
7535
7536   if (Subtarget->isPICStyleRIPRel() &&
7537       (M == CodeModel::Small || M == CodeModel::Kernel))
7538     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7539   else
7540     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7541
7542   // With PIC, the address is actually $g + Offset.
7543   if (isGlobalRelativeToPICBase(OpFlags)) {
7544     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7545                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7546                          Result);
7547   }
7548
7549   return Result;
7550 }
7551
7552 SDValue
7553 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7554                                       int64_t Offset, SelectionDAG &DAG) const {
7555   // Create the TargetGlobalAddress node, folding in the constant
7556   // offset if it is legal.
7557   unsigned char OpFlags =
7558     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7559   CodeModel::Model M = getTargetMachine().getCodeModel();
7560   SDValue Result;
7561   if (OpFlags == X86II::MO_NO_FLAG &&
7562       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7563     // A direct static reference to a global.
7564     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7565     Offset = 0;
7566   } else {
7567     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7568   }
7569
7570   if (Subtarget->isPICStyleRIPRel() &&
7571       (M == CodeModel::Small || M == CodeModel::Kernel))
7572     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7573   else
7574     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7575
7576   // With PIC, the address is actually $g + Offset.
7577   if (isGlobalRelativeToPICBase(OpFlags)) {
7578     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7579                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7580                          Result);
7581   }
7582
7583   // For globals that require a load from a stub to get the address, emit the
7584   // load.
7585   if (isGlobalStubReference(OpFlags))
7586     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7587                          MachinePointerInfo::getGOT(), false, false, false, 0);
7588
7589   // If there was a non-zero offset that we didn't fold, create an explicit
7590   // addition for it.
7591   if (Offset != 0)
7592     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7593                          DAG.getConstant(Offset, getPointerTy()));
7594
7595   return Result;
7596 }
7597
7598 SDValue
7599 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7600   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7601   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7602   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7603 }
7604
7605 static SDValue
7606 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7607            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7608            unsigned char OperandFlags, bool LocalDynamic = false) {
7609   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7610   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7611   DebugLoc dl = GA->getDebugLoc();
7612   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7613                                            GA->getValueType(0),
7614                                            GA->getOffset(),
7615                                            OperandFlags);
7616
7617   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7618                                            : X86ISD::TLSADDR;
7619
7620   if (InFlag) {
7621     SDValue Ops[] = { Chain,  TGA, *InFlag };
7622     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7623   } else {
7624     SDValue Ops[]  = { Chain, TGA };
7625     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7626   }
7627
7628   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7629   MFI->setAdjustsStack(true);
7630
7631   SDValue Flag = Chain.getValue(1);
7632   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7633 }
7634
7635 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7636 static SDValue
7637 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7638                                 const EVT PtrVT) {
7639   SDValue InFlag;
7640   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7641   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7642                                    DAG.getNode(X86ISD::GlobalBaseReg,
7643                                                DebugLoc(), PtrVT), InFlag);
7644   InFlag = Chain.getValue(1);
7645
7646   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7647 }
7648
7649 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7650 static SDValue
7651 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7652                                 const EVT PtrVT) {
7653   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7654                     X86::RAX, X86II::MO_TLSGD);
7655 }
7656
7657 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7658                                            SelectionDAG &DAG,
7659                                            const EVT PtrVT,
7660                                            bool is64Bit) {
7661   DebugLoc dl = GA->getDebugLoc();
7662
7663   // Get the start address of the TLS block for this module.
7664   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7665       .getInfo<X86MachineFunctionInfo>();
7666   MFI->incNumLocalDynamicTLSAccesses();
7667
7668   SDValue Base;
7669   if (is64Bit) {
7670     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7671                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7672   } else {
7673     SDValue InFlag;
7674     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7675         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7676     InFlag = Chain.getValue(1);
7677     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7678                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7679   }
7680
7681   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7682   // of Base.
7683
7684   // Build x@dtpoff.
7685   unsigned char OperandFlags = X86II::MO_DTPOFF;
7686   unsigned WrapperKind = X86ISD::Wrapper;
7687   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7688                                            GA->getValueType(0),
7689                                            GA->getOffset(), OperandFlags);
7690   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7691
7692   // Add x@dtpoff with the base.
7693   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7694 }
7695
7696 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7697 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7698                                    const EVT PtrVT, TLSModel::Model model,
7699                                    bool is64Bit, bool isPIC) {
7700   DebugLoc dl = GA->getDebugLoc();
7701
7702   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7703   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7704                                                          is64Bit ? 257 : 256));
7705
7706   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7707                                       DAG.getIntPtrConstant(0),
7708                                       MachinePointerInfo(Ptr),
7709                                       false, false, false, 0);
7710
7711   unsigned char OperandFlags = 0;
7712   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7713   // initialexec.
7714   unsigned WrapperKind = X86ISD::Wrapper;
7715   if (model == TLSModel::LocalExec) {
7716     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7717   } else if (model == TLSModel::InitialExec) {
7718     if (is64Bit) {
7719       OperandFlags = X86II::MO_GOTTPOFF;
7720       WrapperKind = X86ISD::WrapperRIP;
7721     } else {
7722       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7723     }
7724   } else {
7725     llvm_unreachable("Unexpected model");
7726   }
7727
7728   // emit "addl x@ntpoff,%eax" (local exec)
7729   // or "addl x@indntpoff,%eax" (initial exec)
7730   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7731   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7732                                            GA->getValueType(0),
7733                                            GA->getOffset(), OperandFlags);
7734   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7735
7736   if (model == TLSModel::InitialExec) {
7737     if (isPIC && !is64Bit) {
7738       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7739                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7740                            Offset);
7741     }
7742
7743     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7744                          MachinePointerInfo::getGOT(), false, false, false,
7745                          0);
7746   }
7747
7748   // The address of the thread local variable is the add of the thread
7749   // pointer with the offset of the variable.
7750   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7751 }
7752
7753 SDValue
7754 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7755
7756   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7757   const GlobalValue *GV = GA->getGlobal();
7758
7759   if (Subtarget->isTargetELF()) {
7760     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7761
7762     switch (model) {
7763       case TLSModel::GeneralDynamic:
7764         if (Subtarget->is64Bit())
7765           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7766         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7767       case TLSModel::LocalDynamic:
7768         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7769                                            Subtarget->is64Bit());
7770       case TLSModel::InitialExec:
7771       case TLSModel::LocalExec:
7772         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7773                                    Subtarget->is64Bit(),
7774                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7775     }
7776     llvm_unreachable("Unknown TLS model.");
7777   }
7778
7779   if (Subtarget->isTargetDarwin()) {
7780     // Darwin only has one model of TLS.  Lower to that.
7781     unsigned char OpFlag = 0;
7782     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7783                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7784
7785     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7786     // global base reg.
7787     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7788                   !Subtarget->is64Bit();
7789     if (PIC32)
7790       OpFlag = X86II::MO_TLVP_PIC_BASE;
7791     else
7792       OpFlag = X86II::MO_TLVP;
7793     DebugLoc DL = Op.getDebugLoc();
7794     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7795                                                 GA->getValueType(0),
7796                                                 GA->getOffset(), OpFlag);
7797     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7798
7799     // With PIC32, the address is actually $g + Offset.
7800     if (PIC32)
7801       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7802                            DAG.getNode(X86ISD::GlobalBaseReg,
7803                                        DebugLoc(), getPointerTy()),
7804                            Offset);
7805
7806     // Lowering the machine isd will make sure everything is in the right
7807     // location.
7808     SDValue Chain = DAG.getEntryNode();
7809     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7810     SDValue Args[] = { Chain, Offset };
7811     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7812
7813     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7814     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7815     MFI->setAdjustsStack(true);
7816
7817     // And our return value (tls address) is in the standard call return value
7818     // location.
7819     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7820     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7821                               Chain.getValue(1));
7822   }
7823
7824   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7825     // Just use the implicit TLS architecture
7826     // Need to generate someting similar to:
7827     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7828     //                                  ; from TEB
7829     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7830     //   mov     rcx, qword [rdx+rcx*8]
7831     //   mov     eax, .tls$:tlsvar
7832     //   [rax+rcx] contains the address
7833     // Windows 64bit: gs:0x58
7834     // Windows 32bit: fs:__tls_array
7835
7836     // If GV is an alias then use the aliasee for determining
7837     // thread-localness.
7838     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7839       GV = GA->resolveAliasedGlobal(false);
7840     DebugLoc dl = GA->getDebugLoc();
7841     SDValue Chain = DAG.getEntryNode();
7842
7843     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7844     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7845     // use its literal value of 0x2C.
7846     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7847                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7848                                                              256)
7849                                         : Type::getInt32PtrTy(*DAG.getContext(),
7850                                                               257));
7851
7852     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7853       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7854         DAG.getExternalSymbol("_tls_array", getPointerTy()));
7855
7856     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7857                                         MachinePointerInfo(Ptr),
7858                                         false, false, false, 0);
7859
7860     // Load the _tls_index variable
7861     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7862     if (Subtarget->is64Bit())
7863       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7864                            IDX, MachinePointerInfo(), MVT::i32,
7865                            false, false, 0);
7866     else
7867       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7868                         false, false, false, 0);
7869
7870     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7871                                     getPointerTy());
7872     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7873
7874     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7875     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7876                       false, false, false, 0);
7877
7878     // Get the offset of start of .tls section
7879     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7880                                              GA->getValueType(0),
7881                                              GA->getOffset(), X86II::MO_SECREL);
7882     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7883
7884     // The address of the thread local variable is the add of the thread
7885     // pointer with the offset of the variable.
7886     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7887   }
7888
7889   llvm_unreachable("TLS not implemented for this target.");
7890 }
7891
7892 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7893 /// and take a 2 x i32 value to shift plus a shift amount.
7894 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7895   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7896   EVT VT = Op.getValueType();
7897   unsigned VTBits = VT.getSizeInBits();
7898   DebugLoc dl = Op.getDebugLoc();
7899   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7900   SDValue ShOpLo = Op.getOperand(0);
7901   SDValue ShOpHi = Op.getOperand(1);
7902   SDValue ShAmt  = Op.getOperand(2);
7903   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7904                                      DAG.getConstant(VTBits - 1, MVT::i8))
7905                        : DAG.getConstant(0, VT);
7906
7907   SDValue Tmp2, Tmp3;
7908   if (Op.getOpcode() == ISD::SHL_PARTS) {
7909     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7910     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7911   } else {
7912     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7913     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7914   }
7915
7916   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7917                                 DAG.getConstant(VTBits, MVT::i8));
7918   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7919                              AndNode, DAG.getConstant(0, MVT::i8));
7920
7921   SDValue Hi, Lo;
7922   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7923   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7924   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7925
7926   if (Op.getOpcode() == ISD::SHL_PARTS) {
7927     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7928     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7929   } else {
7930     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7931     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7932   }
7933
7934   SDValue Ops[2] = { Lo, Hi };
7935   return DAG.getMergeValues(Ops, 2, dl);
7936 }
7937
7938 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7939                                            SelectionDAG &DAG) const {
7940   EVT SrcVT = Op.getOperand(0).getValueType();
7941
7942   if (SrcVT.isVector())
7943     return SDValue();
7944
7945   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7946          "Unknown SINT_TO_FP to lower!");
7947
7948   // These are really Legal; return the operand so the caller accepts it as
7949   // Legal.
7950   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7951     return Op;
7952   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7953       Subtarget->is64Bit()) {
7954     return Op;
7955   }
7956
7957   DebugLoc dl = Op.getDebugLoc();
7958   unsigned Size = SrcVT.getSizeInBits()/8;
7959   MachineFunction &MF = DAG.getMachineFunction();
7960   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7961   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7962   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7963                                StackSlot,
7964                                MachinePointerInfo::getFixedStack(SSFI),
7965                                false, false, 0);
7966   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7967 }
7968
7969 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7970                                      SDValue StackSlot,
7971                                      SelectionDAG &DAG) const {
7972   // Build the FILD
7973   DebugLoc DL = Op.getDebugLoc();
7974   SDVTList Tys;
7975   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7976   if (useSSE)
7977     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7978   else
7979     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7980
7981   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7982
7983   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7984   MachineMemOperand *MMO;
7985   if (FI) {
7986     int SSFI = FI->getIndex();
7987     MMO =
7988       DAG.getMachineFunction()
7989       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7990                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7991   } else {
7992     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7993     StackSlot = StackSlot.getOperand(1);
7994   }
7995   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7996   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7997                                            X86ISD::FILD, DL,
7998                                            Tys, Ops, array_lengthof(Ops),
7999                                            SrcVT, MMO);
8000
8001   if (useSSE) {
8002     Chain = Result.getValue(1);
8003     SDValue InFlag = Result.getValue(2);
8004
8005     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8006     // shouldn't be necessary except that RFP cannot be live across
8007     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8008     MachineFunction &MF = DAG.getMachineFunction();
8009     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8010     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8011     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8012     Tys = DAG.getVTList(MVT::Other);
8013     SDValue Ops[] = {
8014       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8015     };
8016     MachineMemOperand *MMO =
8017       DAG.getMachineFunction()
8018       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8019                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8020
8021     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8022                                     Ops, array_lengthof(Ops),
8023                                     Op.getValueType(), MMO);
8024     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8025                          MachinePointerInfo::getFixedStack(SSFI),
8026                          false, false, false, 0);
8027   }
8028
8029   return Result;
8030 }
8031
8032 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8033 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8034                                                SelectionDAG &DAG) const {
8035   // This algorithm is not obvious. Here it is what we're trying to output:
8036   /*
8037      movq       %rax,  %xmm0
8038      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8039      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8040      #ifdef __SSE3__
8041        haddpd   %xmm0, %xmm0
8042      #else
8043        pshufd   $0x4e, %xmm0, %xmm1
8044        addpd    %xmm1, %xmm0
8045      #endif
8046   */
8047
8048   DebugLoc dl = Op.getDebugLoc();
8049   LLVMContext *Context = DAG.getContext();
8050
8051   // Build some magic constants.
8052   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8053   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8054   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8055
8056   SmallVector<Constant*,2> CV1;
8057   CV1.push_back(
8058     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8059                                       APInt(64, 0x4330000000000000ULL))));
8060   CV1.push_back(
8061     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8062                                       APInt(64, 0x4530000000000000ULL))));
8063   Constant *C1 = ConstantVector::get(CV1);
8064   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8065
8066   // Load the 64-bit value into an XMM register.
8067   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8068                             Op.getOperand(0));
8069   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8070                               MachinePointerInfo::getConstantPool(),
8071                               false, false, false, 16);
8072   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8073                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8074                               CLod0);
8075
8076   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8077                               MachinePointerInfo::getConstantPool(),
8078                               false, false, false, 16);
8079   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8080   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8081   SDValue Result;
8082
8083   if (Subtarget->hasSSE3()) {
8084     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8085     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8086   } else {
8087     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8088     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8089                                            S2F, 0x4E, DAG);
8090     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8091                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8092                          Sub);
8093   }
8094
8095   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8096                      DAG.getIntPtrConstant(0));
8097 }
8098
8099 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8100 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8101                                                SelectionDAG &DAG) const {
8102   DebugLoc dl = Op.getDebugLoc();
8103   // FP constant to bias correct the final result.
8104   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8105                                    MVT::f64);
8106
8107   // Load the 32-bit value into an XMM register.
8108   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8109                              Op.getOperand(0));
8110
8111   // Zero out the upper parts of the register.
8112   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8113
8114   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8115                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8116                      DAG.getIntPtrConstant(0));
8117
8118   // Or the load with the bias.
8119   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8120                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8121                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8122                                                    MVT::v2f64, Load)),
8123                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8124                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8125                                                    MVT::v2f64, Bias)));
8126   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8127                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8128                    DAG.getIntPtrConstant(0));
8129
8130   // Subtract the bias.
8131   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8132
8133   // Handle final rounding.
8134   EVT DestVT = Op.getValueType();
8135
8136   if (DestVT.bitsLT(MVT::f64))
8137     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8138                        DAG.getIntPtrConstant(0));
8139   if (DestVT.bitsGT(MVT::f64))
8140     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8141
8142   // Handle final rounding.
8143   return Sub;
8144 }
8145
8146 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8147                                                SelectionDAG &DAG) const {
8148   SDValue N0 = Op.getOperand(0);
8149   EVT SVT = N0.getValueType();
8150   DebugLoc dl = Op.getDebugLoc();
8151
8152   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8153           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8154          "Custom UINT_TO_FP is not supported!");
8155
8156   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8157                              SVT.getVectorNumElements());
8158   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8159                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8160 }
8161
8162 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8163                                            SelectionDAG &DAG) const {
8164   SDValue N0 = Op.getOperand(0);
8165   DebugLoc dl = Op.getDebugLoc();
8166
8167   if (Op.getValueType().isVector())
8168     return lowerUINT_TO_FP_vec(Op, DAG);
8169
8170   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8171   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8172   // the optimization here.
8173   if (DAG.SignBitIsZero(N0))
8174     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8175
8176   EVT SrcVT = N0.getValueType();
8177   EVT DstVT = Op.getValueType();
8178   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8179     return LowerUINT_TO_FP_i64(Op, DAG);
8180   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8181     return LowerUINT_TO_FP_i32(Op, DAG);
8182   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8183     return SDValue();
8184
8185   // Make a 64-bit buffer, and use it to build an FILD.
8186   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8187   if (SrcVT == MVT::i32) {
8188     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8189     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8190                                      getPointerTy(), StackSlot, WordOff);
8191     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8192                                   StackSlot, MachinePointerInfo(),
8193                                   false, false, 0);
8194     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8195                                   OffsetSlot, MachinePointerInfo(),
8196                                   false, false, 0);
8197     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8198     return Fild;
8199   }
8200
8201   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8202   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8203                                StackSlot, MachinePointerInfo(),
8204                                false, false, 0);
8205   // For i64 source, we need to add the appropriate power of 2 if the input
8206   // was negative.  This is the same as the optimization in
8207   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8208   // we must be careful to do the computation in x87 extended precision, not
8209   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8210   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8211   MachineMemOperand *MMO =
8212     DAG.getMachineFunction()
8213     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8214                           MachineMemOperand::MOLoad, 8, 8);
8215
8216   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8217   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8218   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8219                                          MVT::i64, MMO);
8220
8221   APInt FF(32, 0x5F800000ULL);
8222
8223   // Check whether the sign bit is set.
8224   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8225                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8226                                  ISD::SETLT);
8227
8228   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8229   SDValue FudgePtr = DAG.getConstantPool(
8230                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8231                                          getPointerTy());
8232
8233   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8234   SDValue Zero = DAG.getIntPtrConstant(0);
8235   SDValue Four = DAG.getIntPtrConstant(4);
8236   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8237                                Zero, Four);
8238   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8239
8240   // Load the value out, extending it from f32 to f80.
8241   // FIXME: Avoid the extend by constructing the right constant pool?
8242   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8243                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8244                                  MVT::f32, false, false, 4);
8245   // Extend everything to 80 bits to force it to be done on x87.
8246   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8247   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8248 }
8249
8250 std::pair<SDValue,SDValue>
8251 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8252                                     bool IsSigned, bool IsReplace) const {
8253   DebugLoc DL = Op.getDebugLoc();
8254
8255   EVT DstTy = Op.getValueType();
8256
8257   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8258     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8259     DstTy = MVT::i64;
8260   }
8261
8262   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8263          DstTy.getSimpleVT() >= MVT::i16 &&
8264          "Unknown FP_TO_INT to lower!");
8265
8266   // These are really Legal.
8267   if (DstTy == MVT::i32 &&
8268       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8269     return std::make_pair(SDValue(), SDValue());
8270   if (Subtarget->is64Bit() &&
8271       DstTy == MVT::i64 &&
8272       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8273     return std::make_pair(SDValue(), SDValue());
8274
8275   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8276   // stack slot, or into the FTOL runtime function.
8277   MachineFunction &MF = DAG.getMachineFunction();
8278   unsigned MemSize = DstTy.getSizeInBits()/8;
8279   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8280   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8281
8282   unsigned Opc;
8283   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8284     Opc = X86ISD::WIN_FTOL;
8285   else
8286     switch (DstTy.getSimpleVT().SimpleTy) {
8287     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8288     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8289     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8290     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8291     }
8292
8293   SDValue Chain = DAG.getEntryNode();
8294   SDValue Value = Op.getOperand(0);
8295   EVT TheVT = Op.getOperand(0).getValueType();
8296   // FIXME This causes a redundant load/store if the SSE-class value is already
8297   // in memory, such as if it is on the callstack.
8298   if (isScalarFPTypeInSSEReg(TheVT)) {
8299     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8300     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8301                          MachinePointerInfo::getFixedStack(SSFI),
8302                          false, false, 0);
8303     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8304     SDValue Ops[] = {
8305       Chain, StackSlot, DAG.getValueType(TheVT)
8306     };
8307
8308     MachineMemOperand *MMO =
8309       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8310                               MachineMemOperand::MOLoad, MemSize, MemSize);
8311     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8312                                     DstTy, MMO);
8313     Chain = Value.getValue(1);
8314     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8315     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8316   }
8317
8318   MachineMemOperand *MMO =
8319     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8320                             MachineMemOperand::MOStore, MemSize, MemSize);
8321
8322   if (Opc != X86ISD::WIN_FTOL) {
8323     // Build the FP_TO_INT*_IN_MEM
8324     SDValue Ops[] = { Chain, Value, StackSlot };
8325     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8326                                            Ops, 3, DstTy, MMO);
8327     return std::make_pair(FIST, StackSlot);
8328   } else {
8329     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8330       DAG.getVTList(MVT::Other, MVT::Glue),
8331       Chain, Value);
8332     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8333       MVT::i32, ftol.getValue(1));
8334     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8335       MVT::i32, eax.getValue(2));
8336     SDValue Ops[] = { eax, edx };
8337     SDValue pair = IsReplace
8338       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8339       : DAG.getMergeValues(Ops, 2, DL);
8340     return std::make_pair(pair, SDValue());
8341   }
8342 }
8343
8344 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8345                               const X86Subtarget *Subtarget) {
8346   MVT VT = Op->getValueType(0).getSimpleVT();
8347   SDValue In = Op->getOperand(0);
8348   MVT InVT = In.getValueType().getSimpleVT();
8349   DebugLoc dl = Op->getDebugLoc();
8350
8351   // Optimize vectors in AVX mode:
8352   //
8353   //   v8i16 -> v8i32
8354   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8355   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8356   //   Concat upper and lower parts.
8357   //
8358   //   v4i32 -> v4i64
8359   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8360   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8361   //   Concat upper and lower parts.
8362   //
8363
8364   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8365       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8366     return SDValue();
8367
8368   if (Subtarget->hasInt256())
8369     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8370
8371   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8372   SDValue Undef = DAG.getUNDEF(InVT);
8373   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8374   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8375   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8376
8377   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8378                              VT.getVectorNumElements()/2);
8379
8380   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8381   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8382
8383   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8384 }
8385
8386 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8387                                            SelectionDAG &DAG) const {
8388   if (Subtarget->hasFp256()) {
8389     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8390     if (Res.getNode())
8391       return Res;
8392   }
8393
8394   return SDValue();
8395 }
8396 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8397                                             SelectionDAG &DAG) const {
8398   DebugLoc DL = Op.getDebugLoc();
8399   MVT VT = Op.getValueType().getSimpleVT();
8400   SDValue In = Op.getOperand(0);
8401   MVT SVT = In.getValueType().getSimpleVT();
8402
8403   if (Subtarget->hasFp256()) {
8404     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8405     if (Res.getNode())
8406       return Res;
8407   }
8408
8409   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8410       VT.getVectorNumElements() != SVT.getVectorNumElements())
8411     return SDValue();
8412
8413   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8414
8415   // AVX2 has better support of integer extending.
8416   if (Subtarget->hasInt256())
8417     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8418
8419   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8420   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8421   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8422                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8423                                                 DAG.getUNDEF(MVT::v8i16),
8424                                                 &Mask[0]));
8425
8426   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8427 }
8428
8429 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8430   DebugLoc DL = Op.getDebugLoc();
8431   MVT VT = Op.getValueType().getSimpleVT();
8432   SDValue In = Op.getOperand(0);
8433   MVT SVT = In.getValueType().getSimpleVT();
8434
8435   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8436     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8437     if (Subtarget->hasInt256()) {
8438       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8439       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8440       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8441                                 ShufMask);
8442       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8443                          DAG.getIntPtrConstant(0));
8444     }
8445
8446     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8447     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8448                                DAG.getIntPtrConstant(0));
8449     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8450                                DAG.getIntPtrConstant(2));
8451
8452     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8453     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8454
8455     // The PSHUFD mask:
8456     static const int ShufMask1[] = {0, 2, 0, 0};
8457     SDValue Undef = DAG.getUNDEF(VT);
8458     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8459     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8460
8461     // The MOVLHPS mask:
8462     static const int ShufMask2[] = {0, 1, 4, 5};
8463     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8464   }
8465
8466   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8467     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8468     if (Subtarget->hasInt256()) {
8469       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8470
8471       SmallVector<SDValue,32> pshufbMask;
8472       for (unsigned i = 0; i < 2; ++i) {
8473         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8474         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8475         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8476         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8477         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8478         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8479         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8480         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8481         for (unsigned j = 0; j < 8; ++j)
8482           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8483       }
8484       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8485                                &pshufbMask[0], 32);
8486       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8487       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8488
8489       static const int ShufMask[] = {0,  2,  -1,  -1};
8490       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8491                                 &ShufMask[0]);
8492       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8493                        DAG.getIntPtrConstant(0));
8494       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8495     }
8496
8497     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8498                                DAG.getIntPtrConstant(0));
8499
8500     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8501                                DAG.getIntPtrConstant(4));
8502
8503     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8504     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8505
8506     // The PSHUFB mask:
8507     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8508                                    -1, -1, -1, -1, -1, -1, -1, -1};
8509
8510     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8511     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8512     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8513
8514     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8515     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8516
8517     // The MOVLHPS Mask:
8518     static const int ShufMask2[] = {0, 1, 4, 5};
8519     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8520     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8521   }
8522
8523   // Handle truncation of V256 to V128 using shuffles.
8524   if (!VT.is128BitVector() || !SVT.is256BitVector())
8525     return SDValue();
8526
8527   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8528          "Invalid op");
8529   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8530
8531   unsigned NumElems = VT.getVectorNumElements();
8532   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8533                              NumElems * 2);
8534
8535   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8536   // Prepare truncation shuffle mask
8537   for (unsigned i = 0; i != NumElems; ++i)
8538     MaskVec[i] = i * 2;
8539   SDValue V = DAG.getVectorShuffle(NVT, DL,
8540                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8541                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8542   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8543                      DAG.getIntPtrConstant(0));
8544 }
8545
8546 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8547                                            SelectionDAG &DAG) const {
8548   MVT VT = Op.getValueType().getSimpleVT();
8549   if (VT.isVector()) {
8550     if (VT == MVT::v8i16)
8551       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8552                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8553                                      MVT::v8i32, Op.getOperand(0)));
8554     return SDValue();
8555   }
8556
8557   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8558     /*IsSigned=*/ true, /*IsReplace=*/ false);
8559   SDValue FIST = Vals.first, StackSlot = Vals.second;
8560   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8561   if (FIST.getNode() == 0) return Op;
8562
8563   if (StackSlot.getNode())
8564     // Load the result.
8565     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8566                        FIST, StackSlot, MachinePointerInfo(),
8567                        false, false, false, 0);
8568
8569   // The node is the result.
8570   return FIST;
8571 }
8572
8573 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8574                                            SelectionDAG &DAG) const {
8575   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8576     /*IsSigned=*/ false, /*IsReplace=*/ false);
8577   SDValue FIST = Vals.first, StackSlot = Vals.second;
8578   assert(FIST.getNode() && "Unexpected failure");
8579
8580   if (StackSlot.getNode())
8581     // Load the result.
8582     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8583                        FIST, StackSlot, MachinePointerInfo(),
8584                        false, false, false, 0);
8585
8586   // The node is the result.
8587   return FIST;
8588 }
8589
8590 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8591   DebugLoc DL = Op.getDebugLoc();
8592   MVT VT = Op.getValueType().getSimpleVT();
8593   SDValue In = Op.getOperand(0);
8594   MVT SVT = In.getValueType().getSimpleVT();
8595
8596   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8597
8598   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8599                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8600                                  In, DAG.getUNDEF(SVT)));
8601 }
8602
8603 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8604   LLVMContext *Context = DAG.getContext();
8605   DebugLoc dl = Op.getDebugLoc();
8606   MVT VT = Op.getValueType().getSimpleVT();
8607   MVT EltVT = VT;
8608   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8609   if (VT.isVector()) {
8610     EltVT = VT.getVectorElementType();
8611     NumElts = VT.getVectorNumElements();
8612   }
8613   Constant *C;
8614   if (EltVT == MVT::f64)
8615     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8616                                           APInt(64, ~(1ULL << 63))));
8617   else
8618     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8619                                           APInt(32, ~(1U << 31))));
8620   C = ConstantVector::getSplat(NumElts, C);
8621   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8622   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8623   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8624                              MachinePointerInfo::getConstantPool(),
8625                              false, false, false, Alignment);
8626   if (VT.isVector()) {
8627     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8628     return DAG.getNode(ISD::BITCAST, dl, VT,
8629                        DAG.getNode(ISD::AND, dl, ANDVT,
8630                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8631                                                Op.getOperand(0)),
8632                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8633   }
8634   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8635 }
8636
8637 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8638   LLVMContext *Context = DAG.getContext();
8639   DebugLoc dl = Op.getDebugLoc();
8640   MVT VT = Op.getValueType().getSimpleVT();
8641   MVT EltVT = VT;
8642   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8643   if (VT.isVector()) {
8644     EltVT = VT.getVectorElementType();
8645     NumElts = VT.getVectorNumElements();
8646   }
8647   Constant *C;
8648   if (EltVT == MVT::f64)
8649     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8650                                           APInt(64, 1ULL << 63)));
8651   else
8652     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8653                                           APInt(32, 1U << 31)));
8654   C = ConstantVector::getSplat(NumElts, C);
8655   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8656   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8657   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8658                              MachinePointerInfo::getConstantPool(),
8659                              false, false, false, Alignment);
8660   if (VT.isVector()) {
8661     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8662     return DAG.getNode(ISD::BITCAST, dl, VT,
8663                        DAG.getNode(ISD::XOR, dl, XORVT,
8664                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8665                                                Op.getOperand(0)),
8666                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8667   }
8668
8669   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8670 }
8671
8672 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8673   LLVMContext *Context = DAG.getContext();
8674   SDValue Op0 = Op.getOperand(0);
8675   SDValue Op1 = Op.getOperand(1);
8676   DebugLoc dl = Op.getDebugLoc();
8677   MVT VT = Op.getValueType().getSimpleVT();
8678   MVT SrcVT = Op1.getValueType().getSimpleVT();
8679
8680   // If second operand is smaller, extend it first.
8681   if (SrcVT.bitsLT(VT)) {
8682     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8683     SrcVT = VT;
8684   }
8685   // And if it is bigger, shrink it first.
8686   if (SrcVT.bitsGT(VT)) {
8687     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8688     SrcVT = VT;
8689   }
8690
8691   // At this point the operands and the result should have the same
8692   // type, and that won't be f80 since that is not custom lowered.
8693
8694   // First get the sign bit of second operand.
8695   SmallVector<Constant*,4> CV;
8696   if (SrcVT == MVT::f64) {
8697     const fltSemantics &Sem = APFloat::IEEEdouble;
8698     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8699     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8700   } else {
8701     const fltSemantics &Sem = APFloat::IEEEsingle;
8702     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8703     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8704     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8705     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8706   }
8707   Constant *C = ConstantVector::get(CV);
8708   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8709   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8710                               MachinePointerInfo::getConstantPool(),
8711                               false, false, false, 16);
8712   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8713
8714   // Shift sign bit right or left if the two operands have different types.
8715   if (SrcVT.bitsGT(VT)) {
8716     // Op0 is MVT::f32, Op1 is MVT::f64.
8717     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8718     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8719                           DAG.getConstant(32, MVT::i32));
8720     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8721     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8722                           DAG.getIntPtrConstant(0));
8723   }
8724
8725   // Clear first operand sign bit.
8726   CV.clear();
8727   if (VT == MVT::f64) {
8728     const fltSemantics &Sem = APFloat::IEEEdouble;
8729     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8730                                                    APInt(64, ~(1ULL << 63)))));
8731     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8732   } else {
8733     const fltSemantics &Sem = APFloat::IEEEsingle;
8734     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8735                                                    APInt(32, ~(1U << 31)))));
8736     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8737     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8738     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8739   }
8740   C = ConstantVector::get(CV);
8741   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8742   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8743                               MachinePointerInfo::getConstantPool(),
8744                               false, false, false, 16);
8745   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8746
8747   // Or the value with the sign bit.
8748   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8749 }
8750
8751 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8752   SDValue N0 = Op.getOperand(0);
8753   DebugLoc dl = Op.getDebugLoc();
8754   MVT VT = Op.getValueType().getSimpleVT();
8755
8756   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8757   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8758                                   DAG.getConstant(1, VT));
8759   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8760 }
8761
8762 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8763 //
8764 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8765                                                   SelectionDAG &DAG) const {
8766   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8767
8768   if (!Subtarget->hasSSE41())
8769     return SDValue();
8770
8771   if (!Op->hasOneUse())
8772     return SDValue();
8773
8774   SDNode *N = Op.getNode();
8775   DebugLoc DL = N->getDebugLoc();
8776
8777   SmallVector<SDValue, 8> Opnds;
8778   DenseMap<SDValue, unsigned> VecInMap;
8779   EVT VT = MVT::Other;
8780
8781   // Recognize a special case where a vector is casted into wide integer to
8782   // test all 0s.
8783   Opnds.push_back(N->getOperand(0));
8784   Opnds.push_back(N->getOperand(1));
8785
8786   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8787     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8788     // BFS traverse all OR'd operands.
8789     if (I->getOpcode() == ISD::OR) {
8790       Opnds.push_back(I->getOperand(0));
8791       Opnds.push_back(I->getOperand(1));
8792       // Re-evaluate the number of nodes to be traversed.
8793       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8794       continue;
8795     }
8796
8797     // Quit if a non-EXTRACT_VECTOR_ELT
8798     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8799       return SDValue();
8800
8801     // Quit if without a constant index.
8802     SDValue Idx = I->getOperand(1);
8803     if (!isa<ConstantSDNode>(Idx))
8804       return SDValue();
8805
8806     SDValue ExtractedFromVec = I->getOperand(0);
8807     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8808     if (M == VecInMap.end()) {
8809       VT = ExtractedFromVec.getValueType();
8810       // Quit if not 128/256-bit vector.
8811       if (!VT.is128BitVector() && !VT.is256BitVector())
8812         return SDValue();
8813       // Quit if not the same type.
8814       if (VecInMap.begin() != VecInMap.end() &&
8815           VT != VecInMap.begin()->first.getValueType())
8816         return SDValue();
8817       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8818     }
8819     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8820   }
8821
8822   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8823          "Not extracted from 128-/256-bit vector.");
8824
8825   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8826   SmallVector<SDValue, 8> VecIns;
8827
8828   for (DenseMap<SDValue, unsigned>::const_iterator
8829         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8830     // Quit if not all elements are used.
8831     if (I->second != FullMask)
8832       return SDValue();
8833     VecIns.push_back(I->first);
8834   }
8835
8836   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8837
8838   // Cast all vectors into TestVT for PTEST.
8839   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8840     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8841
8842   // If more than one full vectors are evaluated, OR them first before PTEST.
8843   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8844     // Each iteration will OR 2 nodes and append the result until there is only
8845     // 1 node left, i.e. the final OR'd value of all vectors.
8846     SDValue LHS = VecIns[Slot];
8847     SDValue RHS = VecIns[Slot + 1];
8848     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8849   }
8850
8851   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8852                      VecIns.back(), VecIns.back());
8853 }
8854
8855 /// Emit nodes that will be selected as "test Op0,Op0", or something
8856 /// equivalent.
8857 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8858                                     SelectionDAG &DAG) const {
8859   DebugLoc dl = Op.getDebugLoc();
8860
8861   // CF and OF aren't always set the way we want. Determine which
8862   // of these we need.
8863   bool NeedCF = false;
8864   bool NeedOF = false;
8865   switch (X86CC) {
8866   default: break;
8867   case X86::COND_A: case X86::COND_AE:
8868   case X86::COND_B: case X86::COND_BE:
8869     NeedCF = true;
8870     break;
8871   case X86::COND_G: case X86::COND_GE:
8872   case X86::COND_L: case X86::COND_LE:
8873   case X86::COND_O: case X86::COND_NO:
8874     NeedOF = true;
8875     break;
8876   }
8877
8878   // See if we can use the EFLAGS value from the operand instead of
8879   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8880   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8881   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8882     // Emit a CMP with 0, which is the TEST pattern.
8883     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8884                        DAG.getConstant(0, Op.getValueType()));
8885
8886   unsigned Opcode = 0;
8887   unsigned NumOperands = 0;
8888
8889   // Truncate operations may prevent the merge of the SETCC instruction
8890   // and the arithmetic intruction before it. Attempt to truncate the operands
8891   // of the arithmetic instruction and use a reduced bit-width instruction.
8892   bool NeedTruncation = false;
8893   SDValue ArithOp = Op;
8894   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8895     SDValue Arith = Op->getOperand(0);
8896     // Both the trunc and the arithmetic op need to have one user each.
8897     if (Arith->hasOneUse())
8898       switch (Arith.getOpcode()) {
8899         default: break;
8900         case ISD::ADD:
8901         case ISD::SUB:
8902         case ISD::AND:
8903         case ISD::OR:
8904         case ISD::XOR: {
8905           NeedTruncation = true;
8906           ArithOp = Arith;
8907         }
8908       }
8909   }
8910
8911   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8912   // which may be the result of a CAST.  We use the variable 'Op', which is the
8913   // non-casted variable when we check for possible users.
8914   switch (ArithOp.getOpcode()) {
8915   case ISD::ADD:
8916     // Due to an isel shortcoming, be conservative if this add is likely to be
8917     // selected as part of a load-modify-store instruction. When the root node
8918     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8919     // uses of other nodes in the match, such as the ADD in this case. This
8920     // leads to the ADD being left around and reselected, with the result being
8921     // two adds in the output.  Alas, even if none our users are stores, that
8922     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8923     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8924     // climbing the DAG back to the root, and it doesn't seem to be worth the
8925     // effort.
8926     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8927          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8928       if (UI->getOpcode() != ISD::CopyToReg &&
8929           UI->getOpcode() != ISD::SETCC &&
8930           UI->getOpcode() != ISD::STORE)
8931         goto default_case;
8932
8933     if (ConstantSDNode *C =
8934         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8935       // An add of one will be selected as an INC.
8936       if (C->getAPIntValue() == 1) {
8937         Opcode = X86ISD::INC;
8938         NumOperands = 1;
8939         break;
8940       }
8941
8942       // An add of negative one (subtract of one) will be selected as a DEC.
8943       if (C->getAPIntValue().isAllOnesValue()) {
8944         Opcode = X86ISD::DEC;
8945         NumOperands = 1;
8946         break;
8947       }
8948     }
8949
8950     // Otherwise use a regular EFLAGS-setting add.
8951     Opcode = X86ISD::ADD;
8952     NumOperands = 2;
8953     break;
8954   case ISD::AND: {
8955     // If the primary and result isn't used, don't bother using X86ISD::AND,
8956     // because a TEST instruction will be better.
8957     bool NonFlagUse = false;
8958     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8959            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8960       SDNode *User = *UI;
8961       unsigned UOpNo = UI.getOperandNo();
8962       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8963         // Look pass truncate.
8964         UOpNo = User->use_begin().getOperandNo();
8965         User = *User->use_begin();
8966       }
8967
8968       if (User->getOpcode() != ISD::BRCOND &&
8969           User->getOpcode() != ISD::SETCC &&
8970           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8971         NonFlagUse = true;
8972         break;
8973       }
8974     }
8975
8976     if (!NonFlagUse)
8977       break;
8978   }
8979     // FALL THROUGH
8980   case ISD::SUB:
8981   case ISD::OR:
8982   case ISD::XOR:
8983     // Due to the ISEL shortcoming noted above, be conservative if this op is
8984     // likely to be selected as part of a load-modify-store instruction.
8985     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8986            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8987       if (UI->getOpcode() == ISD::STORE)
8988         goto default_case;
8989
8990     // Otherwise use a regular EFLAGS-setting instruction.
8991     switch (ArithOp.getOpcode()) {
8992     default: llvm_unreachable("unexpected operator!");
8993     case ISD::SUB: Opcode = X86ISD::SUB; break;
8994     case ISD::XOR: Opcode = X86ISD::XOR; break;
8995     case ISD::AND: Opcode = X86ISD::AND; break;
8996     case ISD::OR: {
8997       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
8998         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
8999         if (EFLAGS.getNode())
9000           return EFLAGS;
9001       }
9002       Opcode = X86ISD::OR;
9003       break;
9004     }
9005     }
9006
9007     NumOperands = 2;
9008     break;
9009   case X86ISD::ADD:
9010   case X86ISD::SUB:
9011   case X86ISD::INC:
9012   case X86ISD::DEC:
9013   case X86ISD::OR:
9014   case X86ISD::XOR:
9015   case X86ISD::AND:
9016     return SDValue(Op.getNode(), 1);
9017   default:
9018   default_case:
9019     break;
9020   }
9021
9022   // If we found that truncation is beneficial, perform the truncation and
9023   // update 'Op'.
9024   if (NeedTruncation) {
9025     EVT VT = Op.getValueType();
9026     SDValue WideVal = Op->getOperand(0);
9027     EVT WideVT = WideVal.getValueType();
9028     unsigned ConvertedOp = 0;
9029     // Use a target machine opcode to prevent further DAGCombine
9030     // optimizations that may separate the arithmetic operations
9031     // from the setcc node.
9032     switch (WideVal.getOpcode()) {
9033       default: break;
9034       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9035       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9036       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9037       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9038       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9039     }
9040
9041     if (ConvertedOp) {
9042       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9043       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9044         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9045         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9046         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9047       }
9048     }
9049   }
9050
9051   if (Opcode == 0)
9052     // Emit a CMP with 0, which is the TEST pattern.
9053     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9054                        DAG.getConstant(0, Op.getValueType()));
9055
9056   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9057   SmallVector<SDValue, 4> Ops;
9058   for (unsigned i = 0; i != NumOperands; ++i)
9059     Ops.push_back(Op.getOperand(i));
9060
9061   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9062   DAG.ReplaceAllUsesWith(Op, New);
9063   return SDValue(New.getNode(), 1);
9064 }
9065
9066 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9067 /// equivalent.
9068 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9069                                    SelectionDAG &DAG) const {
9070   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9071     if (C->getAPIntValue() == 0)
9072       return EmitTest(Op0, X86CC, DAG);
9073
9074   DebugLoc dl = Op0.getDebugLoc();
9075   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9076        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9077     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9078     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9079     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9080                               Op0, Op1);
9081     return SDValue(Sub.getNode(), 1);
9082   }
9083   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9084 }
9085
9086 /// Convert a comparison if required by the subtarget.
9087 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9088                                                  SelectionDAG &DAG) const {
9089   // If the subtarget does not support the FUCOMI instruction, floating-point
9090   // comparisons have to be converted.
9091   if (Subtarget->hasCMov() ||
9092       Cmp.getOpcode() != X86ISD::CMP ||
9093       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9094       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9095     return Cmp;
9096
9097   // The instruction selector will select an FUCOM instruction instead of
9098   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9099   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9100   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9101   DebugLoc dl = Cmp.getDebugLoc();
9102   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9103   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9104   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9105                             DAG.getConstant(8, MVT::i8));
9106   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9107   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9108 }
9109
9110 static bool isAllOnes(SDValue V) {
9111   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9112   return C && C->isAllOnesValue();
9113 }
9114
9115 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9116 /// if it's possible.
9117 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9118                                      DebugLoc dl, SelectionDAG &DAG) const {
9119   SDValue Op0 = And.getOperand(0);
9120   SDValue Op1 = And.getOperand(1);
9121   if (Op0.getOpcode() == ISD::TRUNCATE)
9122     Op0 = Op0.getOperand(0);
9123   if (Op1.getOpcode() == ISD::TRUNCATE)
9124     Op1 = Op1.getOperand(0);
9125
9126   SDValue LHS, RHS;
9127   if (Op1.getOpcode() == ISD::SHL)
9128     std::swap(Op0, Op1);
9129   if (Op0.getOpcode() == ISD::SHL) {
9130     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9131       if (And00C->getZExtValue() == 1) {
9132         // If we looked past a truncate, check that it's only truncating away
9133         // known zeros.
9134         unsigned BitWidth = Op0.getValueSizeInBits();
9135         unsigned AndBitWidth = And.getValueSizeInBits();
9136         if (BitWidth > AndBitWidth) {
9137           APInt Zeros, Ones;
9138           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9139           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9140             return SDValue();
9141         }
9142         LHS = Op1;
9143         RHS = Op0.getOperand(1);
9144       }
9145   } else if (Op1.getOpcode() == ISD::Constant) {
9146     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9147     uint64_t AndRHSVal = AndRHS->getZExtValue();
9148     SDValue AndLHS = Op0;
9149
9150     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9151       LHS = AndLHS.getOperand(0);
9152       RHS = AndLHS.getOperand(1);
9153     }
9154
9155     // Use BT if the immediate can't be encoded in a TEST instruction.
9156     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9157       LHS = AndLHS;
9158       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9159     }
9160   }
9161
9162   if (LHS.getNode()) {
9163     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9164     // the condition code later.
9165     bool Invert = false;
9166     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9167       Invert = true;
9168       LHS = LHS.getOperand(0);
9169     }
9170
9171     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9172     // instruction.  Since the shift amount is in-range-or-undefined, we know
9173     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9174     // the encoding for the i16 version is larger than the i32 version.
9175     // Also promote i16 to i32 for performance / code size reason.
9176     if (LHS.getValueType() == MVT::i8 ||
9177         LHS.getValueType() == MVT::i16)
9178       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9179
9180     // If the operand types disagree, extend the shift amount to match.  Since
9181     // BT ignores high bits (like shifts) we can use anyextend.
9182     if (LHS.getValueType() != RHS.getValueType())
9183       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9184
9185     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9186     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9187     // Flip the condition if the LHS was a not instruction
9188     if (Invert)
9189       Cond = X86::GetOppositeBranchCondition(Cond);
9190     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9191                        DAG.getConstant(Cond, MVT::i8), BT);
9192   }
9193
9194   return SDValue();
9195 }
9196
9197 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9198 // ones, and then concatenate the result back.
9199 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9200   MVT VT = Op.getValueType().getSimpleVT();
9201
9202   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9203          "Unsupported value type for operation");
9204
9205   unsigned NumElems = VT.getVectorNumElements();
9206   DebugLoc dl = Op.getDebugLoc();
9207   SDValue CC = Op.getOperand(2);
9208
9209   // Extract the LHS vectors
9210   SDValue LHS = Op.getOperand(0);
9211   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9212   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9213
9214   // Extract the RHS vectors
9215   SDValue RHS = Op.getOperand(1);
9216   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9217   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9218
9219   // Issue the operation on the smaller types and concatenate the result back
9220   MVT EltVT = VT.getVectorElementType();
9221   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9222   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9223                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9224                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9225 }
9226
9227 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9228                            SelectionDAG &DAG) {
9229   SDValue Cond;
9230   SDValue Op0 = Op.getOperand(0);
9231   SDValue Op1 = Op.getOperand(1);
9232   SDValue CC = Op.getOperand(2);
9233   MVT VT = Op.getValueType().getSimpleVT();
9234   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9235   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9236   DebugLoc dl = Op.getDebugLoc();
9237
9238   if (isFP) {
9239 #ifndef NDEBUG
9240     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9241     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9242 #endif
9243
9244     unsigned SSECC;
9245     bool Swap = false;
9246
9247     // SSE Condition code mapping:
9248     //  0 - EQ
9249     //  1 - LT
9250     //  2 - LE
9251     //  3 - UNORD
9252     //  4 - NEQ
9253     //  5 - NLT
9254     //  6 - NLE
9255     //  7 - ORD
9256     switch (SetCCOpcode) {
9257     default: llvm_unreachable("Unexpected SETCC condition");
9258     case ISD::SETOEQ:
9259     case ISD::SETEQ:  SSECC = 0; break;
9260     case ISD::SETOGT:
9261     case ISD::SETGT: Swap = true; // Fallthrough
9262     case ISD::SETLT:
9263     case ISD::SETOLT: SSECC = 1; break;
9264     case ISD::SETOGE:
9265     case ISD::SETGE: Swap = true; // Fallthrough
9266     case ISD::SETLE:
9267     case ISD::SETOLE: SSECC = 2; break;
9268     case ISD::SETUO:  SSECC = 3; break;
9269     case ISD::SETUNE:
9270     case ISD::SETNE:  SSECC = 4; break;
9271     case ISD::SETULE: Swap = true; // Fallthrough
9272     case ISD::SETUGE: SSECC = 5; break;
9273     case ISD::SETULT: Swap = true; // Fallthrough
9274     case ISD::SETUGT: SSECC = 6; break;
9275     case ISD::SETO:   SSECC = 7; break;
9276     case ISD::SETUEQ:
9277     case ISD::SETONE: SSECC = 8; break;
9278     }
9279     if (Swap)
9280       std::swap(Op0, Op1);
9281
9282     // In the two special cases we can't handle, emit two comparisons.
9283     if (SSECC == 8) {
9284       unsigned CC0, CC1;
9285       unsigned CombineOpc;
9286       if (SetCCOpcode == ISD::SETUEQ) {
9287         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9288       } else {
9289         assert(SetCCOpcode == ISD::SETONE);
9290         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9291       }
9292
9293       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9294                                  DAG.getConstant(CC0, MVT::i8));
9295       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9296                                  DAG.getConstant(CC1, MVT::i8));
9297       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9298     }
9299     // Handle all other FP comparisons here.
9300     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9301                        DAG.getConstant(SSECC, MVT::i8));
9302   }
9303
9304   // Break 256-bit integer vector compare into smaller ones.
9305   if (VT.is256BitVector() && !Subtarget->hasInt256())
9306     return Lower256IntVSETCC(Op, DAG);
9307
9308   // We are handling one of the integer comparisons here.  Since SSE only has
9309   // GT and EQ comparisons for integer, swapping operands and multiple
9310   // operations may be required for some comparisons.
9311   unsigned Opc;
9312   bool Swap = false, Invert = false, FlipSigns = false;
9313
9314   switch (SetCCOpcode) {
9315   default: llvm_unreachable("Unexpected SETCC condition");
9316   case ISD::SETNE:  Invert = true;
9317   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9318   case ISD::SETLT:  Swap = true;
9319   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9320   case ISD::SETGE:  Swap = true;
9321   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9322   case ISD::SETULT: Swap = true;
9323   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9324   case ISD::SETUGE: Swap = true;
9325   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9326   }
9327   if (Swap)
9328     std::swap(Op0, Op1);
9329
9330   // Check that the operation in question is available (most are plain SSE2,
9331   // but PCMPGTQ and PCMPEQQ have different requirements).
9332   if (VT == MVT::v2i64) {
9333     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9334       return SDValue();
9335     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9336       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9337       // pcmpeqd + pshufd + pand.
9338       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9339
9340       // First cast everything to the right type,
9341       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9342       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9343
9344       // Do the compare.
9345       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9346
9347       // Make sure the lower and upper halves are both all-ones.
9348       const int Mask[] = { 1, 0, 3, 2 };
9349       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9350       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9351
9352       if (Invert)
9353         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9354
9355       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9356     }
9357   }
9358
9359   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9360   // bits of the inputs before performing those operations.
9361   if (FlipSigns) {
9362     EVT EltVT = VT.getVectorElementType();
9363     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9364                                       EltVT);
9365     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9366     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9367                                     SignBits.size());
9368     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9369     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9370   }
9371
9372   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9373
9374   // If the logical-not of the result is required, perform that now.
9375   if (Invert)
9376     Result = DAG.getNOT(dl, Result, VT);
9377
9378   return Result;
9379 }
9380
9381 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9382
9383   MVT VT = Op.getValueType().getSimpleVT();
9384
9385   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9386
9387   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9388   SDValue Op0 = Op.getOperand(0);
9389   SDValue Op1 = Op.getOperand(1);
9390   DebugLoc dl = Op.getDebugLoc();
9391   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9392
9393   // Optimize to BT if possible.
9394   // Lower (X & (1 << N)) == 0 to BT(X, N).
9395   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9396   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9397   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9398       Op1.getOpcode() == ISD::Constant &&
9399       cast<ConstantSDNode>(Op1)->isNullValue() &&
9400       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9401     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9402     if (NewSetCC.getNode())
9403       return NewSetCC;
9404   }
9405
9406   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9407   // these.
9408   if (Op1.getOpcode() == ISD::Constant &&
9409       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9410        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9411       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9412
9413     // If the input is a setcc, then reuse the input setcc or use a new one with
9414     // the inverted condition.
9415     if (Op0.getOpcode() == X86ISD::SETCC) {
9416       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9417       bool Invert = (CC == ISD::SETNE) ^
9418         cast<ConstantSDNode>(Op1)->isNullValue();
9419       if (!Invert) return Op0;
9420
9421       CCode = X86::GetOppositeBranchCondition(CCode);
9422       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9423                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9424     }
9425   }
9426
9427   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9428   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9429   if (X86CC == X86::COND_INVALID)
9430     return SDValue();
9431
9432   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9433   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9434   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9435                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9436 }
9437
9438 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9439 static bool isX86LogicalCmp(SDValue Op) {
9440   unsigned Opc = Op.getNode()->getOpcode();
9441   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9442       Opc == X86ISD::SAHF)
9443     return true;
9444   if (Op.getResNo() == 1 &&
9445       (Opc == X86ISD::ADD ||
9446        Opc == X86ISD::SUB ||
9447        Opc == X86ISD::ADC ||
9448        Opc == X86ISD::SBB ||
9449        Opc == X86ISD::SMUL ||
9450        Opc == X86ISD::UMUL ||
9451        Opc == X86ISD::INC ||
9452        Opc == X86ISD::DEC ||
9453        Opc == X86ISD::OR ||
9454        Opc == X86ISD::XOR ||
9455        Opc == X86ISD::AND))
9456     return true;
9457
9458   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9459     return true;
9460
9461   return false;
9462 }
9463
9464 static bool isZero(SDValue V) {
9465   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9466   return C && C->isNullValue();
9467 }
9468
9469 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9470   if (V.getOpcode() != ISD::TRUNCATE)
9471     return false;
9472
9473   SDValue VOp0 = V.getOperand(0);
9474   unsigned InBits = VOp0.getValueSizeInBits();
9475   unsigned Bits = V.getValueSizeInBits();
9476   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9477 }
9478
9479 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9480   bool addTest = true;
9481   SDValue Cond  = Op.getOperand(0);
9482   SDValue Op1 = Op.getOperand(1);
9483   SDValue Op2 = Op.getOperand(2);
9484   DebugLoc DL = Op.getDebugLoc();
9485   SDValue CC;
9486
9487   if (Cond.getOpcode() == ISD::SETCC) {
9488     SDValue NewCond = LowerSETCC(Cond, DAG);
9489     if (NewCond.getNode())
9490       Cond = NewCond;
9491   }
9492
9493   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9494   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9495   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9496   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9497   if (Cond.getOpcode() == X86ISD::SETCC &&
9498       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9499       isZero(Cond.getOperand(1).getOperand(1))) {
9500     SDValue Cmp = Cond.getOperand(1);
9501
9502     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9503
9504     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9505         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9506       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9507
9508       SDValue CmpOp0 = Cmp.getOperand(0);
9509       // Apply further optimizations for special cases
9510       // (select (x != 0), -1, 0) -> neg & sbb
9511       // (select (x == 0), 0, -1) -> neg & sbb
9512       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9513         if (YC->isNullValue() &&
9514             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9515           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9516           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9517                                     DAG.getConstant(0, CmpOp0.getValueType()),
9518                                     CmpOp0);
9519           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9520                                     DAG.getConstant(X86::COND_B, MVT::i8),
9521                                     SDValue(Neg.getNode(), 1));
9522           return Res;
9523         }
9524
9525       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9526                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9527       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9528
9529       SDValue Res =   // Res = 0 or -1.
9530         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9531                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9532
9533       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9534         Res = DAG.getNOT(DL, Res, Res.getValueType());
9535
9536       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9537       if (N2C == 0 || !N2C->isNullValue())
9538         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9539       return Res;
9540     }
9541   }
9542
9543   // Look past (and (setcc_carry (cmp ...)), 1).
9544   if (Cond.getOpcode() == ISD::AND &&
9545       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9546     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9547     if (C && C->getAPIntValue() == 1)
9548       Cond = Cond.getOperand(0);
9549   }
9550
9551   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9552   // setting operand in place of the X86ISD::SETCC.
9553   unsigned CondOpcode = Cond.getOpcode();
9554   if (CondOpcode == X86ISD::SETCC ||
9555       CondOpcode == X86ISD::SETCC_CARRY) {
9556     CC = Cond.getOperand(0);
9557
9558     SDValue Cmp = Cond.getOperand(1);
9559     unsigned Opc = Cmp.getOpcode();
9560     MVT VT = Op.getValueType().getSimpleVT();
9561
9562     bool IllegalFPCMov = false;
9563     if (VT.isFloatingPoint() && !VT.isVector() &&
9564         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9565       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9566
9567     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9568         Opc == X86ISD::BT) { // FIXME
9569       Cond = Cmp;
9570       addTest = false;
9571     }
9572   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9573              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9574              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9575               Cond.getOperand(0).getValueType() != MVT::i8)) {
9576     SDValue LHS = Cond.getOperand(0);
9577     SDValue RHS = Cond.getOperand(1);
9578     unsigned X86Opcode;
9579     unsigned X86Cond;
9580     SDVTList VTs;
9581     switch (CondOpcode) {
9582     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9583     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9584     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9585     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9586     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9587     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9588     default: llvm_unreachable("unexpected overflowing operator");
9589     }
9590     if (CondOpcode == ISD::UMULO)
9591       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9592                           MVT::i32);
9593     else
9594       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9595
9596     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9597
9598     if (CondOpcode == ISD::UMULO)
9599       Cond = X86Op.getValue(2);
9600     else
9601       Cond = X86Op.getValue(1);
9602
9603     CC = DAG.getConstant(X86Cond, MVT::i8);
9604     addTest = false;
9605   }
9606
9607   if (addTest) {
9608     // Look pass the truncate if the high bits are known zero.
9609     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9610         Cond = Cond.getOperand(0);
9611
9612     // We know the result of AND is compared against zero. Try to match
9613     // it to BT.
9614     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9615       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9616       if (NewSetCC.getNode()) {
9617         CC = NewSetCC.getOperand(0);
9618         Cond = NewSetCC.getOperand(1);
9619         addTest = false;
9620       }
9621     }
9622   }
9623
9624   if (addTest) {
9625     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9626     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9627   }
9628
9629   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9630   // a <  b ?  0 : -1 -> RES = setcc_carry
9631   // a >= b ? -1 :  0 -> RES = setcc_carry
9632   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9633   if (Cond.getOpcode() == X86ISD::SUB) {
9634     Cond = ConvertCmpIfNecessary(Cond, DAG);
9635     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9636
9637     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9638         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9639       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9640                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9641       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9642         return DAG.getNOT(DL, Res, Res.getValueType());
9643       return Res;
9644     }
9645   }
9646
9647   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9648   // widen the cmov and push the truncate through. This avoids introducing a new
9649   // branch during isel and doesn't add any extensions.
9650   if (Op.getValueType() == MVT::i8 &&
9651       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9652     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9653     if (T1.getValueType() == T2.getValueType() &&
9654         // Blacklist CopyFromReg to avoid partial register stalls.
9655         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9656       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9657       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9658       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9659     }
9660   }
9661
9662   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9663   // condition is true.
9664   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9665   SDValue Ops[] = { Op2, Op1, CC, Cond };
9666   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9667 }
9668
9669 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9670                                             SelectionDAG &DAG) const {
9671   MVT VT = Op->getValueType(0).getSimpleVT();
9672   SDValue In = Op->getOperand(0);
9673   MVT InVT = In.getValueType().getSimpleVT();
9674   DebugLoc dl = Op->getDebugLoc();
9675
9676   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9677       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9678     return SDValue();
9679
9680   if (Subtarget->hasInt256())
9681     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9682
9683   // Optimize vectors in AVX mode
9684   // Sign extend  v8i16 to v8i32 and
9685   //              v4i32 to v4i64
9686   //
9687   // Divide input vector into two parts
9688   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9689   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9690   // concat the vectors to original VT
9691
9692   unsigned NumElems = InVT.getVectorNumElements();
9693   SDValue Undef = DAG.getUNDEF(InVT);
9694
9695   SmallVector<int,8> ShufMask1(NumElems, -1);
9696   for (unsigned i = 0; i != NumElems/2; ++i)
9697     ShufMask1[i] = i;
9698
9699   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9700
9701   SmallVector<int,8> ShufMask2(NumElems, -1);
9702   for (unsigned i = 0; i != NumElems/2; ++i)
9703     ShufMask2[i] = i + NumElems/2;
9704
9705   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9706
9707   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9708                                 VT.getVectorNumElements()/2);
9709
9710   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9711   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9712
9713   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9714 }
9715
9716 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9717 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9718 // from the AND / OR.
9719 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9720   Opc = Op.getOpcode();
9721   if (Opc != ISD::OR && Opc != ISD::AND)
9722     return false;
9723   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9724           Op.getOperand(0).hasOneUse() &&
9725           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9726           Op.getOperand(1).hasOneUse());
9727 }
9728
9729 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9730 // 1 and that the SETCC node has a single use.
9731 static bool isXor1OfSetCC(SDValue Op) {
9732   if (Op.getOpcode() != ISD::XOR)
9733     return false;
9734   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9735   if (N1C && N1C->getAPIntValue() == 1) {
9736     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9737       Op.getOperand(0).hasOneUse();
9738   }
9739   return false;
9740 }
9741
9742 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9743   bool addTest = true;
9744   SDValue Chain = Op.getOperand(0);
9745   SDValue Cond  = Op.getOperand(1);
9746   SDValue Dest  = Op.getOperand(2);
9747   DebugLoc dl = Op.getDebugLoc();
9748   SDValue CC;
9749   bool Inverted = false;
9750
9751   if (Cond.getOpcode() == ISD::SETCC) {
9752     // Check for setcc([su]{add,sub,mul}o == 0).
9753     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9754         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9755         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9756         Cond.getOperand(0).getResNo() == 1 &&
9757         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9758          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9759          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9760          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9761          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9762          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9763       Inverted = true;
9764       Cond = Cond.getOperand(0);
9765     } else {
9766       SDValue NewCond = LowerSETCC(Cond, DAG);
9767       if (NewCond.getNode())
9768         Cond = NewCond;
9769     }
9770   }
9771 #if 0
9772   // FIXME: LowerXALUO doesn't handle these!!
9773   else if (Cond.getOpcode() == X86ISD::ADD  ||
9774            Cond.getOpcode() == X86ISD::SUB  ||
9775            Cond.getOpcode() == X86ISD::SMUL ||
9776            Cond.getOpcode() == X86ISD::UMUL)
9777     Cond = LowerXALUO(Cond, DAG);
9778 #endif
9779
9780   // Look pass (and (setcc_carry (cmp ...)), 1).
9781   if (Cond.getOpcode() == ISD::AND &&
9782       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9783     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9784     if (C && C->getAPIntValue() == 1)
9785       Cond = Cond.getOperand(0);
9786   }
9787
9788   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9789   // setting operand in place of the X86ISD::SETCC.
9790   unsigned CondOpcode = Cond.getOpcode();
9791   if (CondOpcode == X86ISD::SETCC ||
9792       CondOpcode == X86ISD::SETCC_CARRY) {
9793     CC = Cond.getOperand(0);
9794
9795     SDValue Cmp = Cond.getOperand(1);
9796     unsigned Opc = Cmp.getOpcode();
9797     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9798     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9799       Cond = Cmp;
9800       addTest = false;
9801     } else {
9802       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9803       default: break;
9804       case X86::COND_O:
9805       case X86::COND_B:
9806         // These can only come from an arithmetic instruction with overflow,
9807         // e.g. SADDO, UADDO.
9808         Cond = Cond.getNode()->getOperand(1);
9809         addTest = false;
9810         break;
9811       }
9812     }
9813   }
9814   CondOpcode = Cond.getOpcode();
9815   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9816       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9817       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9818        Cond.getOperand(0).getValueType() != MVT::i8)) {
9819     SDValue LHS = Cond.getOperand(0);
9820     SDValue RHS = Cond.getOperand(1);
9821     unsigned X86Opcode;
9822     unsigned X86Cond;
9823     SDVTList VTs;
9824     switch (CondOpcode) {
9825     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9826     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9827     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9828     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9829     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9830     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9831     default: llvm_unreachable("unexpected overflowing operator");
9832     }
9833     if (Inverted)
9834       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9835     if (CondOpcode == ISD::UMULO)
9836       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9837                           MVT::i32);
9838     else
9839       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9840
9841     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9842
9843     if (CondOpcode == ISD::UMULO)
9844       Cond = X86Op.getValue(2);
9845     else
9846       Cond = X86Op.getValue(1);
9847
9848     CC = DAG.getConstant(X86Cond, MVT::i8);
9849     addTest = false;
9850   } else {
9851     unsigned CondOpc;
9852     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9853       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9854       if (CondOpc == ISD::OR) {
9855         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9856         // two branches instead of an explicit OR instruction with a
9857         // separate test.
9858         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9859             isX86LogicalCmp(Cmp)) {
9860           CC = Cond.getOperand(0).getOperand(0);
9861           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9862                               Chain, Dest, CC, Cmp);
9863           CC = Cond.getOperand(1).getOperand(0);
9864           Cond = Cmp;
9865           addTest = false;
9866         }
9867       } else { // ISD::AND
9868         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9869         // two branches instead of an explicit AND instruction with a
9870         // separate test. However, we only do this if this block doesn't
9871         // have a fall-through edge, because this requires an explicit
9872         // jmp when the condition is false.
9873         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9874             isX86LogicalCmp(Cmp) &&
9875             Op.getNode()->hasOneUse()) {
9876           X86::CondCode CCode =
9877             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9878           CCode = X86::GetOppositeBranchCondition(CCode);
9879           CC = DAG.getConstant(CCode, MVT::i8);
9880           SDNode *User = *Op.getNode()->use_begin();
9881           // Look for an unconditional branch following this conditional branch.
9882           // We need this because we need to reverse the successors in order
9883           // to implement FCMP_OEQ.
9884           if (User->getOpcode() == ISD::BR) {
9885             SDValue FalseBB = User->getOperand(1);
9886             SDNode *NewBR =
9887               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9888             assert(NewBR == User);
9889             (void)NewBR;
9890             Dest = FalseBB;
9891
9892             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9893                                 Chain, Dest, CC, Cmp);
9894             X86::CondCode CCode =
9895               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9896             CCode = X86::GetOppositeBranchCondition(CCode);
9897             CC = DAG.getConstant(CCode, MVT::i8);
9898             Cond = Cmp;
9899             addTest = false;
9900           }
9901         }
9902       }
9903     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9904       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9905       // It should be transformed during dag combiner except when the condition
9906       // is set by a arithmetics with overflow node.
9907       X86::CondCode CCode =
9908         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9909       CCode = X86::GetOppositeBranchCondition(CCode);
9910       CC = DAG.getConstant(CCode, MVT::i8);
9911       Cond = Cond.getOperand(0).getOperand(1);
9912       addTest = false;
9913     } else if (Cond.getOpcode() == ISD::SETCC &&
9914                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9915       // For FCMP_OEQ, we can emit
9916       // two branches instead of an explicit AND instruction with a
9917       // separate test. However, we only do this if this block doesn't
9918       // have a fall-through edge, because this requires an explicit
9919       // jmp when the condition is false.
9920       if (Op.getNode()->hasOneUse()) {
9921         SDNode *User = *Op.getNode()->use_begin();
9922         // Look for an unconditional branch following this conditional branch.
9923         // We need this because we need to reverse the successors in order
9924         // to implement FCMP_OEQ.
9925         if (User->getOpcode() == ISD::BR) {
9926           SDValue FalseBB = User->getOperand(1);
9927           SDNode *NewBR =
9928             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9929           assert(NewBR == User);
9930           (void)NewBR;
9931           Dest = FalseBB;
9932
9933           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9934                                     Cond.getOperand(0), Cond.getOperand(1));
9935           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9936           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9937           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9938                               Chain, Dest, CC, Cmp);
9939           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9940           Cond = Cmp;
9941           addTest = false;
9942         }
9943       }
9944     } else if (Cond.getOpcode() == ISD::SETCC &&
9945                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9946       // For FCMP_UNE, we can emit
9947       // two branches instead of an explicit AND instruction with a
9948       // separate test. However, we only do this if this block doesn't
9949       // have a fall-through edge, because this requires an explicit
9950       // jmp when the condition is false.
9951       if (Op.getNode()->hasOneUse()) {
9952         SDNode *User = *Op.getNode()->use_begin();
9953         // Look for an unconditional branch following this conditional branch.
9954         // We need this because we need to reverse the successors in order
9955         // to implement FCMP_UNE.
9956         if (User->getOpcode() == ISD::BR) {
9957           SDValue FalseBB = User->getOperand(1);
9958           SDNode *NewBR =
9959             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9960           assert(NewBR == User);
9961           (void)NewBR;
9962
9963           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9964                                     Cond.getOperand(0), Cond.getOperand(1));
9965           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9966           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9967           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9968                               Chain, Dest, CC, Cmp);
9969           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9970           Cond = Cmp;
9971           addTest = false;
9972           Dest = FalseBB;
9973         }
9974       }
9975     }
9976   }
9977
9978   if (addTest) {
9979     // Look pass the truncate if the high bits are known zero.
9980     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9981         Cond = Cond.getOperand(0);
9982
9983     // We know the result of AND is compared against zero. Try to match
9984     // it to BT.
9985     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9986       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9987       if (NewSetCC.getNode()) {
9988         CC = NewSetCC.getOperand(0);
9989         Cond = NewSetCC.getOperand(1);
9990         addTest = false;
9991       }
9992     }
9993   }
9994
9995   if (addTest) {
9996     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9997     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9998   }
9999   Cond = ConvertCmpIfNecessary(Cond, DAG);
10000   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10001                      Chain, Dest, CC, Cond);
10002 }
10003
10004 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10005 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10006 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10007 // that the guard pages used by the OS virtual memory manager are allocated in
10008 // correct sequence.
10009 SDValue
10010 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10011                                            SelectionDAG &DAG) const {
10012   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10013           getTargetMachine().Options.EnableSegmentedStacks) &&
10014          "This should be used only on Windows targets or when segmented stacks "
10015          "are being used");
10016   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10017   DebugLoc dl = Op.getDebugLoc();
10018
10019   // Get the inputs.
10020   SDValue Chain = Op.getOperand(0);
10021   SDValue Size  = Op.getOperand(1);
10022   // FIXME: Ensure alignment here
10023
10024   bool Is64Bit = Subtarget->is64Bit();
10025   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10026
10027   if (getTargetMachine().Options.EnableSegmentedStacks) {
10028     MachineFunction &MF = DAG.getMachineFunction();
10029     MachineRegisterInfo &MRI = MF.getRegInfo();
10030
10031     if (Is64Bit) {
10032       // The 64 bit implementation of segmented stacks needs to clobber both r10
10033       // r11. This makes it impossible to use it along with nested parameters.
10034       const Function *F = MF.getFunction();
10035
10036       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10037            I != E; ++I)
10038         if (I->hasNestAttr())
10039           report_fatal_error("Cannot use segmented stacks with functions that "
10040                              "have nested arguments.");
10041     }
10042
10043     const TargetRegisterClass *AddrRegClass =
10044       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10045     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10046     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10047     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10048                                 DAG.getRegister(Vreg, SPTy));
10049     SDValue Ops1[2] = { Value, Chain };
10050     return DAG.getMergeValues(Ops1, 2, dl);
10051   } else {
10052     SDValue Flag;
10053     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10054
10055     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10056     Flag = Chain.getValue(1);
10057     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10058
10059     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10060     Flag = Chain.getValue(1);
10061
10062     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10063                                SPTy).getValue(1);
10064
10065     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10066     return DAG.getMergeValues(Ops1, 2, dl);
10067   }
10068 }
10069
10070 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10071   MachineFunction &MF = DAG.getMachineFunction();
10072   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10073
10074   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10075   DebugLoc DL = Op.getDebugLoc();
10076
10077   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10078     // vastart just stores the address of the VarArgsFrameIndex slot into the
10079     // memory location argument.
10080     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10081                                    getPointerTy());
10082     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10083                         MachinePointerInfo(SV), false, false, 0);
10084   }
10085
10086   // __va_list_tag:
10087   //   gp_offset         (0 - 6 * 8)
10088   //   fp_offset         (48 - 48 + 8 * 16)
10089   //   overflow_arg_area (point to parameters coming in memory).
10090   //   reg_save_area
10091   SmallVector<SDValue, 8> MemOps;
10092   SDValue FIN = Op.getOperand(1);
10093   // Store gp_offset
10094   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10095                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10096                                                MVT::i32),
10097                                FIN, MachinePointerInfo(SV), false, false, 0);
10098   MemOps.push_back(Store);
10099
10100   // Store fp_offset
10101   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10102                     FIN, DAG.getIntPtrConstant(4));
10103   Store = DAG.getStore(Op.getOperand(0), DL,
10104                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10105                                        MVT::i32),
10106                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10107   MemOps.push_back(Store);
10108
10109   // Store ptr to overflow_arg_area
10110   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10111                     FIN, DAG.getIntPtrConstant(4));
10112   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10113                                     getPointerTy());
10114   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10115                        MachinePointerInfo(SV, 8),
10116                        false, false, 0);
10117   MemOps.push_back(Store);
10118
10119   // Store ptr to reg_save_area.
10120   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10121                     FIN, DAG.getIntPtrConstant(8));
10122   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10123                                     getPointerTy());
10124   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10125                        MachinePointerInfo(SV, 16), false, false, 0);
10126   MemOps.push_back(Store);
10127   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10128                      &MemOps[0], MemOps.size());
10129 }
10130
10131 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10132   assert(Subtarget->is64Bit() &&
10133          "LowerVAARG only handles 64-bit va_arg!");
10134   assert((Subtarget->isTargetLinux() ||
10135           Subtarget->isTargetDarwin()) &&
10136           "Unhandled target in LowerVAARG");
10137   assert(Op.getNode()->getNumOperands() == 4);
10138   SDValue Chain = Op.getOperand(0);
10139   SDValue SrcPtr = Op.getOperand(1);
10140   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10141   unsigned Align = Op.getConstantOperandVal(3);
10142   DebugLoc dl = Op.getDebugLoc();
10143
10144   EVT ArgVT = Op.getNode()->getValueType(0);
10145   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10146   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10147   uint8_t ArgMode;
10148
10149   // Decide which area this value should be read from.
10150   // TODO: Implement the AMD64 ABI in its entirety. This simple
10151   // selection mechanism works only for the basic types.
10152   if (ArgVT == MVT::f80) {
10153     llvm_unreachable("va_arg for f80 not yet implemented");
10154   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10155     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10156   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10157     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10158   } else {
10159     llvm_unreachable("Unhandled argument type in LowerVAARG");
10160   }
10161
10162   if (ArgMode == 2) {
10163     // Sanity Check: Make sure using fp_offset makes sense.
10164     assert(!getTargetMachine().Options.UseSoftFloat &&
10165            !(DAG.getMachineFunction()
10166                 .getFunction()->getAttributes()
10167                 .hasAttribute(AttributeSet::FunctionIndex,
10168                               Attribute::NoImplicitFloat)) &&
10169            Subtarget->hasSSE1());
10170   }
10171
10172   // Insert VAARG_64 node into the DAG
10173   // VAARG_64 returns two values: Variable Argument Address, Chain
10174   SmallVector<SDValue, 11> InstOps;
10175   InstOps.push_back(Chain);
10176   InstOps.push_back(SrcPtr);
10177   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10178   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10179   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10180   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10181   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10182                                           VTs, &InstOps[0], InstOps.size(),
10183                                           MVT::i64,
10184                                           MachinePointerInfo(SV),
10185                                           /*Align=*/0,
10186                                           /*Volatile=*/false,
10187                                           /*ReadMem=*/true,
10188                                           /*WriteMem=*/true);
10189   Chain = VAARG.getValue(1);
10190
10191   // Load the next argument and return it
10192   return DAG.getLoad(ArgVT, dl,
10193                      Chain,
10194                      VAARG,
10195                      MachinePointerInfo(),
10196                      false, false, false, 0);
10197 }
10198
10199 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10200                            SelectionDAG &DAG) {
10201   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10202   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10203   SDValue Chain = Op.getOperand(0);
10204   SDValue DstPtr = Op.getOperand(1);
10205   SDValue SrcPtr = Op.getOperand(2);
10206   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10207   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10208   DebugLoc DL = Op.getDebugLoc();
10209
10210   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10211                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10212                        false,
10213                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10214 }
10215
10216 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10217 // may or may not be a constant. Takes immediate version of shift as input.
10218 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10219                                    SDValue SrcOp, SDValue ShAmt,
10220                                    SelectionDAG &DAG) {
10221   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10222
10223   if (isa<ConstantSDNode>(ShAmt)) {
10224     // Constant may be a TargetConstant. Use a regular constant.
10225     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10226     switch (Opc) {
10227       default: llvm_unreachable("Unknown target vector shift node");
10228       case X86ISD::VSHLI:
10229       case X86ISD::VSRLI:
10230       case X86ISD::VSRAI:
10231         return DAG.getNode(Opc, dl, VT, SrcOp,
10232                            DAG.getConstant(ShiftAmt, MVT::i32));
10233     }
10234   }
10235
10236   // Change opcode to non-immediate version
10237   switch (Opc) {
10238     default: llvm_unreachable("Unknown target vector shift node");
10239     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10240     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10241     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10242   }
10243
10244   // Need to build a vector containing shift amount
10245   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10246   SDValue ShOps[4];
10247   ShOps[0] = ShAmt;
10248   ShOps[1] = DAG.getConstant(0, MVT::i32);
10249   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10250   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10251
10252   // The return type has to be a 128-bit type with the same element
10253   // type as the input type.
10254   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10255   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10256
10257   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10258   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10259 }
10260
10261 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10262   DebugLoc dl = Op.getDebugLoc();
10263   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10264   switch (IntNo) {
10265   default: return SDValue();    // Don't custom lower most intrinsics.
10266   // Comparison intrinsics.
10267   case Intrinsic::x86_sse_comieq_ss:
10268   case Intrinsic::x86_sse_comilt_ss:
10269   case Intrinsic::x86_sse_comile_ss:
10270   case Intrinsic::x86_sse_comigt_ss:
10271   case Intrinsic::x86_sse_comige_ss:
10272   case Intrinsic::x86_sse_comineq_ss:
10273   case Intrinsic::x86_sse_ucomieq_ss:
10274   case Intrinsic::x86_sse_ucomilt_ss:
10275   case Intrinsic::x86_sse_ucomile_ss:
10276   case Intrinsic::x86_sse_ucomigt_ss:
10277   case Intrinsic::x86_sse_ucomige_ss:
10278   case Intrinsic::x86_sse_ucomineq_ss:
10279   case Intrinsic::x86_sse2_comieq_sd:
10280   case Intrinsic::x86_sse2_comilt_sd:
10281   case Intrinsic::x86_sse2_comile_sd:
10282   case Intrinsic::x86_sse2_comigt_sd:
10283   case Intrinsic::x86_sse2_comige_sd:
10284   case Intrinsic::x86_sse2_comineq_sd:
10285   case Intrinsic::x86_sse2_ucomieq_sd:
10286   case Intrinsic::x86_sse2_ucomilt_sd:
10287   case Intrinsic::x86_sse2_ucomile_sd:
10288   case Intrinsic::x86_sse2_ucomigt_sd:
10289   case Intrinsic::x86_sse2_ucomige_sd:
10290   case Intrinsic::x86_sse2_ucomineq_sd: {
10291     unsigned Opc;
10292     ISD::CondCode CC;
10293     switch (IntNo) {
10294     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10295     case Intrinsic::x86_sse_comieq_ss:
10296     case Intrinsic::x86_sse2_comieq_sd:
10297       Opc = X86ISD::COMI;
10298       CC = ISD::SETEQ;
10299       break;
10300     case Intrinsic::x86_sse_comilt_ss:
10301     case Intrinsic::x86_sse2_comilt_sd:
10302       Opc = X86ISD::COMI;
10303       CC = ISD::SETLT;
10304       break;
10305     case Intrinsic::x86_sse_comile_ss:
10306     case Intrinsic::x86_sse2_comile_sd:
10307       Opc = X86ISD::COMI;
10308       CC = ISD::SETLE;
10309       break;
10310     case Intrinsic::x86_sse_comigt_ss:
10311     case Intrinsic::x86_sse2_comigt_sd:
10312       Opc = X86ISD::COMI;
10313       CC = ISD::SETGT;
10314       break;
10315     case Intrinsic::x86_sse_comige_ss:
10316     case Intrinsic::x86_sse2_comige_sd:
10317       Opc = X86ISD::COMI;
10318       CC = ISD::SETGE;
10319       break;
10320     case Intrinsic::x86_sse_comineq_ss:
10321     case Intrinsic::x86_sse2_comineq_sd:
10322       Opc = X86ISD::COMI;
10323       CC = ISD::SETNE;
10324       break;
10325     case Intrinsic::x86_sse_ucomieq_ss:
10326     case Intrinsic::x86_sse2_ucomieq_sd:
10327       Opc = X86ISD::UCOMI;
10328       CC = ISD::SETEQ;
10329       break;
10330     case Intrinsic::x86_sse_ucomilt_ss:
10331     case Intrinsic::x86_sse2_ucomilt_sd:
10332       Opc = X86ISD::UCOMI;
10333       CC = ISD::SETLT;
10334       break;
10335     case Intrinsic::x86_sse_ucomile_ss:
10336     case Intrinsic::x86_sse2_ucomile_sd:
10337       Opc = X86ISD::UCOMI;
10338       CC = ISD::SETLE;
10339       break;
10340     case Intrinsic::x86_sse_ucomigt_ss:
10341     case Intrinsic::x86_sse2_ucomigt_sd:
10342       Opc = X86ISD::UCOMI;
10343       CC = ISD::SETGT;
10344       break;
10345     case Intrinsic::x86_sse_ucomige_ss:
10346     case Intrinsic::x86_sse2_ucomige_sd:
10347       Opc = X86ISD::UCOMI;
10348       CC = ISD::SETGE;
10349       break;
10350     case Intrinsic::x86_sse_ucomineq_ss:
10351     case Intrinsic::x86_sse2_ucomineq_sd:
10352       Opc = X86ISD::UCOMI;
10353       CC = ISD::SETNE;
10354       break;
10355     }
10356
10357     SDValue LHS = Op.getOperand(1);
10358     SDValue RHS = Op.getOperand(2);
10359     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10360     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10361     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10362     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10363                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10364     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10365   }
10366
10367   // Arithmetic intrinsics.
10368   case Intrinsic::x86_sse2_pmulu_dq:
10369   case Intrinsic::x86_avx2_pmulu_dq:
10370     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10371                        Op.getOperand(1), Op.getOperand(2));
10372
10373   // SSE2/AVX2 sub with unsigned saturation intrinsics
10374   case Intrinsic::x86_sse2_psubus_b:
10375   case Intrinsic::x86_sse2_psubus_w:
10376   case Intrinsic::x86_avx2_psubus_b:
10377   case Intrinsic::x86_avx2_psubus_w:
10378     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10379                        Op.getOperand(1), Op.getOperand(2));
10380
10381   // SSE3/AVX horizontal add/sub intrinsics
10382   case Intrinsic::x86_sse3_hadd_ps:
10383   case Intrinsic::x86_sse3_hadd_pd:
10384   case Intrinsic::x86_avx_hadd_ps_256:
10385   case Intrinsic::x86_avx_hadd_pd_256:
10386   case Intrinsic::x86_sse3_hsub_ps:
10387   case Intrinsic::x86_sse3_hsub_pd:
10388   case Intrinsic::x86_avx_hsub_ps_256:
10389   case Intrinsic::x86_avx_hsub_pd_256:
10390   case Intrinsic::x86_ssse3_phadd_w_128:
10391   case Intrinsic::x86_ssse3_phadd_d_128:
10392   case Intrinsic::x86_avx2_phadd_w:
10393   case Intrinsic::x86_avx2_phadd_d:
10394   case Intrinsic::x86_ssse3_phsub_w_128:
10395   case Intrinsic::x86_ssse3_phsub_d_128:
10396   case Intrinsic::x86_avx2_phsub_w:
10397   case Intrinsic::x86_avx2_phsub_d: {
10398     unsigned Opcode;
10399     switch (IntNo) {
10400     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10401     case Intrinsic::x86_sse3_hadd_ps:
10402     case Intrinsic::x86_sse3_hadd_pd:
10403     case Intrinsic::x86_avx_hadd_ps_256:
10404     case Intrinsic::x86_avx_hadd_pd_256:
10405       Opcode = X86ISD::FHADD;
10406       break;
10407     case Intrinsic::x86_sse3_hsub_ps:
10408     case Intrinsic::x86_sse3_hsub_pd:
10409     case Intrinsic::x86_avx_hsub_ps_256:
10410     case Intrinsic::x86_avx_hsub_pd_256:
10411       Opcode = X86ISD::FHSUB;
10412       break;
10413     case Intrinsic::x86_ssse3_phadd_w_128:
10414     case Intrinsic::x86_ssse3_phadd_d_128:
10415     case Intrinsic::x86_avx2_phadd_w:
10416     case Intrinsic::x86_avx2_phadd_d:
10417       Opcode = X86ISD::HADD;
10418       break;
10419     case Intrinsic::x86_ssse3_phsub_w_128:
10420     case Intrinsic::x86_ssse3_phsub_d_128:
10421     case Intrinsic::x86_avx2_phsub_w:
10422     case Intrinsic::x86_avx2_phsub_d:
10423       Opcode = X86ISD::HSUB;
10424       break;
10425     }
10426     return DAG.getNode(Opcode, dl, Op.getValueType(),
10427                        Op.getOperand(1), Op.getOperand(2));
10428   }
10429
10430   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10431   case Intrinsic::x86_sse2_pmaxu_b:
10432   case Intrinsic::x86_sse41_pmaxuw:
10433   case Intrinsic::x86_sse41_pmaxud:
10434   case Intrinsic::x86_avx2_pmaxu_b:
10435   case Intrinsic::x86_avx2_pmaxu_w:
10436   case Intrinsic::x86_avx2_pmaxu_d:
10437   case Intrinsic::x86_sse2_pminu_b:
10438   case Intrinsic::x86_sse41_pminuw:
10439   case Intrinsic::x86_sse41_pminud:
10440   case Intrinsic::x86_avx2_pminu_b:
10441   case Intrinsic::x86_avx2_pminu_w:
10442   case Intrinsic::x86_avx2_pminu_d:
10443   case Intrinsic::x86_sse41_pmaxsb:
10444   case Intrinsic::x86_sse2_pmaxs_w:
10445   case Intrinsic::x86_sse41_pmaxsd:
10446   case Intrinsic::x86_avx2_pmaxs_b:
10447   case Intrinsic::x86_avx2_pmaxs_w:
10448   case Intrinsic::x86_avx2_pmaxs_d:
10449   case Intrinsic::x86_sse41_pminsb:
10450   case Intrinsic::x86_sse2_pmins_w:
10451   case Intrinsic::x86_sse41_pminsd:
10452   case Intrinsic::x86_avx2_pmins_b:
10453   case Intrinsic::x86_avx2_pmins_w:
10454   case Intrinsic::x86_avx2_pmins_d: {
10455     unsigned Opcode;
10456     switch (IntNo) {
10457     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10458     case Intrinsic::x86_sse2_pmaxu_b:
10459     case Intrinsic::x86_sse41_pmaxuw:
10460     case Intrinsic::x86_sse41_pmaxud:
10461     case Intrinsic::x86_avx2_pmaxu_b:
10462     case Intrinsic::x86_avx2_pmaxu_w:
10463     case Intrinsic::x86_avx2_pmaxu_d:
10464       Opcode = X86ISD::UMAX;
10465       break;
10466     case Intrinsic::x86_sse2_pminu_b:
10467     case Intrinsic::x86_sse41_pminuw:
10468     case Intrinsic::x86_sse41_pminud:
10469     case Intrinsic::x86_avx2_pminu_b:
10470     case Intrinsic::x86_avx2_pminu_w:
10471     case Intrinsic::x86_avx2_pminu_d:
10472       Opcode = X86ISD::UMIN;
10473       break;
10474     case Intrinsic::x86_sse41_pmaxsb:
10475     case Intrinsic::x86_sse2_pmaxs_w:
10476     case Intrinsic::x86_sse41_pmaxsd:
10477     case Intrinsic::x86_avx2_pmaxs_b:
10478     case Intrinsic::x86_avx2_pmaxs_w:
10479     case Intrinsic::x86_avx2_pmaxs_d:
10480       Opcode = X86ISD::SMAX;
10481       break;
10482     case Intrinsic::x86_sse41_pminsb:
10483     case Intrinsic::x86_sse2_pmins_w:
10484     case Intrinsic::x86_sse41_pminsd:
10485     case Intrinsic::x86_avx2_pmins_b:
10486     case Intrinsic::x86_avx2_pmins_w:
10487     case Intrinsic::x86_avx2_pmins_d:
10488       Opcode = X86ISD::SMIN;
10489       break;
10490     }
10491     return DAG.getNode(Opcode, dl, Op.getValueType(),
10492                        Op.getOperand(1), Op.getOperand(2));
10493   }
10494
10495   // SSE/SSE2/AVX floating point max/min intrinsics.
10496   case Intrinsic::x86_sse_max_ps:
10497   case Intrinsic::x86_sse2_max_pd:
10498   case Intrinsic::x86_avx_max_ps_256:
10499   case Intrinsic::x86_avx_max_pd_256:
10500   case Intrinsic::x86_sse_min_ps:
10501   case Intrinsic::x86_sse2_min_pd:
10502   case Intrinsic::x86_avx_min_ps_256:
10503   case Intrinsic::x86_avx_min_pd_256: {
10504     unsigned Opcode;
10505     switch (IntNo) {
10506     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10507     case Intrinsic::x86_sse_max_ps:
10508     case Intrinsic::x86_sse2_max_pd:
10509     case Intrinsic::x86_avx_max_ps_256:
10510     case Intrinsic::x86_avx_max_pd_256:
10511       Opcode = X86ISD::FMAX;
10512       break;
10513     case Intrinsic::x86_sse_min_ps:
10514     case Intrinsic::x86_sse2_min_pd:
10515     case Intrinsic::x86_avx_min_ps_256:
10516     case Intrinsic::x86_avx_min_pd_256:
10517       Opcode = X86ISD::FMIN;
10518       break;
10519     }
10520     return DAG.getNode(Opcode, dl, Op.getValueType(),
10521                        Op.getOperand(1), Op.getOperand(2));
10522   }
10523
10524   // AVX2 variable shift intrinsics
10525   case Intrinsic::x86_avx2_psllv_d:
10526   case Intrinsic::x86_avx2_psllv_q:
10527   case Intrinsic::x86_avx2_psllv_d_256:
10528   case Intrinsic::x86_avx2_psllv_q_256:
10529   case Intrinsic::x86_avx2_psrlv_d:
10530   case Intrinsic::x86_avx2_psrlv_q:
10531   case Intrinsic::x86_avx2_psrlv_d_256:
10532   case Intrinsic::x86_avx2_psrlv_q_256:
10533   case Intrinsic::x86_avx2_psrav_d:
10534   case Intrinsic::x86_avx2_psrav_d_256: {
10535     unsigned Opcode;
10536     switch (IntNo) {
10537     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10538     case Intrinsic::x86_avx2_psllv_d:
10539     case Intrinsic::x86_avx2_psllv_q:
10540     case Intrinsic::x86_avx2_psllv_d_256:
10541     case Intrinsic::x86_avx2_psllv_q_256:
10542       Opcode = ISD::SHL;
10543       break;
10544     case Intrinsic::x86_avx2_psrlv_d:
10545     case Intrinsic::x86_avx2_psrlv_q:
10546     case Intrinsic::x86_avx2_psrlv_d_256:
10547     case Intrinsic::x86_avx2_psrlv_q_256:
10548       Opcode = ISD::SRL;
10549       break;
10550     case Intrinsic::x86_avx2_psrav_d:
10551     case Intrinsic::x86_avx2_psrav_d_256:
10552       Opcode = ISD::SRA;
10553       break;
10554     }
10555     return DAG.getNode(Opcode, dl, Op.getValueType(),
10556                        Op.getOperand(1), Op.getOperand(2));
10557   }
10558
10559   case Intrinsic::x86_ssse3_pshuf_b_128:
10560   case Intrinsic::x86_avx2_pshuf_b:
10561     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10562                        Op.getOperand(1), Op.getOperand(2));
10563
10564   case Intrinsic::x86_ssse3_psign_b_128:
10565   case Intrinsic::x86_ssse3_psign_w_128:
10566   case Intrinsic::x86_ssse3_psign_d_128:
10567   case Intrinsic::x86_avx2_psign_b:
10568   case Intrinsic::x86_avx2_psign_w:
10569   case Intrinsic::x86_avx2_psign_d:
10570     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10571                        Op.getOperand(1), Op.getOperand(2));
10572
10573   case Intrinsic::x86_sse41_insertps:
10574     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10575                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10576
10577   case Intrinsic::x86_avx_vperm2f128_ps_256:
10578   case Intrinsic::x86_avx_vperm2f128_pd_256:
10579   case Intrinsic::x86_avx_vperm2f128_si_256:
10580   case Intrinsic::x86_avx2_vperm2i128:
10581     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10582                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10583
10584   case Intrinsic::x86_avx2_permd:
10585   case Intrinsic::x86_avx2_permps:
10586     // Operands intentionally swapped. Mask is last operand to intrinsic,
10587     // but second operand for node/intruction.
10588     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10589                        Op.getOperand(2), Op.getOperand(1));
10590
10591   case Intrinsic::x86_sse_sqrt_ps:
10592   case Intrinsic::x86_sse2_sqrt_pd:
10593   case Intrinsic::x86_avx_sqrt_ps_256:
10594   case Intrinsic::x86_avx_sqrt_pd_256:
10595     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10596
10597   // ptest and testp intrinsics. The intrinsic these come from are designed to
10598   // return an integer value, not just an instruction so lower it to the ptest
10599   // or testp pattern and a setcc for the result.
10600   case Intrinsic::x86_sse41_ptestz:
10601   case Intrinsic::x86_sse41_ptestc:
10602   case Intrinsic::x86_sse41_ptestnzc:
10603   case Intrinsic::x86_avx_ptestz_256:
10604   case Intrinsic::x86_avx_ptestc_256:
10605   case Intrinsic::x86_avx_ptestnzc_256:
10606   case Intrinsic::x86_avx_vtestz_ps:
10607   case Intrinsic::x86_avx_vtestc_ps:
10608   case Intrinsic::x86_avx_vtestnzc_ps:
10609   case Intrinsic::x86_avx_vtestz_pd:
10610   case Intrinsic::x86_avx_vtestc_pd:
10611   case Intrinsic::x86_avx_vtestnzc_pd:
10612   case Intrinsic::x86_avx_vtestz_ps_256:
10613   case Intrinsic::x86_avx_vtestc_ps_256:
10614   case Intrinsic::x86_avx_vtestnzc_ps_256:
10615   case Intrinsic::x86_avx_vtestz_pd_256:
10616   case Intrinsic::x86_avx_vtestc_pd_256:
10617   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10618     bool IsTestPacked = false;
10619     unsigned X86CC;
10620     switch (IntNo) {
10621     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10622     case Intrinsic::x86_avx_vtestz_ps:
10623     case Intrinsic::x86_avx_vtestz_pd:
10624     case Intrinsic::x86_avx_vtestz_ps_256:
10625     case Intrinsic::x86_avx_vtestz_pd_256:
10626       IsTestPacked = true; // Fallthrough
10627     case Intrinsic::x86_sse41_ptestz:
10628     case Intrinsic::x86_avx_ptestz_256:
10629       // ZF = 1
10630       X86CC = X86::COND_E;
10631       break;
10632     case Intrinsic::x86_avx_vtestc_ps:
10633     case Intrinsic::x86_avx_vtestc_pd:
10634     case Intrinsic::x86_avx_vtestc_ps_256:
10635     case Intrinsic::x86_avx_vtestc_pd_256:
10636       IsTestPacked = true; // Fallthrough
10637     case Intrinsic::x86_sse41_ptestc:
10638     case Intrinsic::x86_avx_ptestc_256:
10639       // CF = 1
10640       X86CC = X86::COND_B;
10641       break;
10642     case Intrinsic::x86_avx_vtestnzc_ps:
10643     case Intrinsic::x86_avx_vtestnzc_pd:
10644     case Intrinsic::x86_avx_vtestnzc_ps_256:
10645     case Intrinsic::x86_avx_vtestnzc_pd_256:
10646       IsTestPacked = true; // Fallthrough
10647     case Intrinsic::x86_sse41_ptestnzc:
10648     case Intrinsic::x86_avx_ptestnzc_256:
10649       // ZF and CF = 0
10650       X86CC = X86::COND_A;
10651       break;
10652     }
10653
10654     SDValue LHS = Op.getOperand(1);
10655     SDValue RHS = Op.getOperand(2);
10656     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10657     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10658     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10659     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10660     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10661   }
10662
10663   // SSE/AVX shift intrinsics
10664   case Intrinsic::x86_sse2_psll_w:
10665   case Intrinsic::x86_sse2_psll_d:
10666   case Intrinsic::x86_sse2_psll_q:
10667   case Intrinsic::x86_avx2_psll_w:
10668   case Intrinsic::x86_avx2_psll_d:
10669   case Intrinsic::x86_avx2_psll_q:
10670   case Intrinsic::x86_sse2_psrl_w:
10671   case Intrinsic::x86_sse2_psrl_d:
10672   case Intrinsic::x86_sse2_psrl_q:
10673   case Intrinsic::x86_avx2_psrl_w:
10674   case Intrinsic::x86_avx2_psrl_d:
10675   case Intrinsic::x86_avx2_psrl_q:
10676   case Intrinsic::x86_sse2_psra_w:
10677   case Intrinsic::x86_sse2_psra_d:
10678   case Intrinsic::x86_avx2_psra_w:
10679   case Intrinsic::x86_avx2_psra_d: {
10680     unsigned Opcode;
10681     switch (IntNo) {
10682     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10683     case Intrinsic::x86_sse2_psll_w:
10684     case Intrinsic::x86_sse2_psll_d:
10685     case Intrinsic::x86_sse2_psll_q:
10686     case Intrinsic::x86_avx2_psll_w:
10687     case Intrinsic::x86_avx2_psll_d:
10688     case Intrinsic::x86_avx2_psll_q:
10689       Opcode = X86ISD::VSHL;
10690       break;
10691     case Intrinsic::x86_sse2_psrl_w:
10692     case Intrinsic::x86_sse2_psrl_d:
10693     case Intrinsic::x86_sse2_psrl_q:
10694     case Intrinsic::x86_avx2_psrl_w:
10695     case Intrinsic::x86_avx2_psrl_d:
10696     case Intrinsic::x86_avx2_psrl_q:
10697       Opcode = X86ISD::VSRL;
10698       break;
10699     case Intrinsic::x86_sse2_psra_w:
10700     case Intrinsic::x86_sse2_psra_d:
10701     case Intrinsic::x86_avx2_psra_w:
10702     case Intrinsic::x86_avx2_psra_d:
10703       Opcode = X86ISD::VSRA;
10704       break;
10705     }
10706     return DAG.getNode(Opcode, dl, Op.getValueType(),
10707                        Op.getOperand(1), Op.getOperand(2));
10708   }
10709
10710   // SSE/AVX immediate shift intrinsics
10711   case Intrinsic::x86_sse2_pslli_w:
10712   case Intrinsic::x86_sse2_pslli_d:
10713   case Intrinsic::x86_sse2_pslli_q:
10714   case Intrinsic::x86_avx2_pslli_w:
10715   case Intrinsic::x86_avx2_pslli_d:
10716   case Intrinsic::x86_avx2_pslli_q:
10717   case Intrinsic::x86_sse2_psrli_w:
10718   case Intrinsic::x86_sse2_psrli_d:
10719   case Intrinsic::x86_sse2_psrli_q:
10720   case Intrinsic::x86_avx2_psrli_w:
10721   case Intrinsic::x86_avx2_psrli_d:
10722   case Intrinsic::x86_avx2_psrli_q:
10723   case Intrinsic::x86_sse2_psrai_w:
10724   case Intrinsic::x86_sse2_psrai_d:
10725   case Intrinsic::x86_avx2_psrai_w:
10726   case Intrinsic::x86_avx2_psrai_d: {
10727     unsigned Opcode;
10728     switch (IntNo) {
10729     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10730     case Intrinsic::x86_sse2_pslli_w:
10731     case Intrinsic::x86_sse2_pslli_d:
10732     case Intrinsic::x86_sse2_pslli_q:
10733     case Intrinsic::x86_avx2_pslli_w:
10734     case Intrinsic::x86_avx2_pslli_d:
10735     case Intrinsic::x86_avx2_pslli_q:
10736       Opcode = X86ISD::VSHLI;
10737       break;
10738     case Intrinsic::x86_sse2_psrli_w:
10739     case Intrinsic::x86_sse2_psrli_d:
10740     case Intrinsic::x86_sse2_psrli_q:
10741     case Intrinsic::x86_avx2_psrli_w:
10742     case Intrinsic::x86_avx2_psrli_d:
10743     case Intrinsic::x86_avx2_psrli_q:
10744       Opcode = X86ISD::VSRLI;
10745       break;
10746     case Intrinsic::x86_sse2_psrai_w:
10747     case Intrinsic::x86_sse2_psrai_d:
10748     case Intrinsic::x86_avx2_psrai_w:
10749     case Intrinsic::x86_avx2_psrai_d:
10750       Opcode = X86ISD::VSRAI;
10751       break;
10752     }
10753     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10754                                Op.getOperand(1), Op.getOperand(2), DAG);
10755   }
10756
10757   case Intrinsic::x86_sse42_pcmpistria128:
10758   case Intrinsic::x86_sse42_pcmpestria128:
10759   case Intrinsic::x86_sse42_pcmpistric128:
10760   case Intrinsic::x86_sse42_pcmpestric128:
10761   case Intrinsic::x86_sse42_pcmpistrio128:
10762   case Intrinsic::x86_sse42_pcmpestrio128:
10763   case Intrinsic::x86_sse42_pcmpistris128:
10764   case Intrinsic::x86_sse42_pcmpestris128:
10765   case Intrinsic::x86_sse42_pcmpistriz128:
10766   case Intrinsic::x86_sse42_pcmpestriz128: {
10767     unsigned Opcode;
10768     unsigned X86CC;
10769     switch (IntNo) {
10770     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10771     case Intrinsic::x86_sse42_pcmpistria128:
10772       Opcode = X86ISD::PCMPISTRI;
10773       X86CC = X86::COND_A;
10774       break;
10775     case Intrinsic::x86_sse42_pcmpestria128:
10776       Opcode = X86ISD::PCMPESTRI;
10777       X86CC = X86::COND_A;
10778       break;
10779     case Intrinsic::x86_sse42_pcmpistric128:
10780       Opcode = X86ISD::PCMPISTRI;
10781       X86CC = X86::COND_B;
10782       break;
10783     case Intrinsic::x86_sse42_pcmpestric128:
10784       Opcode = X86ISD::PCMPESTRI;
10785       X86CC = X86::COND_B;
10786       break;
10787     case Intrinsic::x86_sse42_pcmpistrio128:
10788       Opcode = X86ISD::PCMPISTRI;
10789       X86CC = X86::COND_O;
10790       break;
10791     case Intrinsic::x86_sse42_pcmpestrio128:
10792       Opcode = X86ISD::PCMPESTRI;
10793       X86CC = X86::COND_O;
10794       break;
10795     case Intrinsic::x86_sse42_pcmpistris128:
10796       Opcode = X86ISD::PCMPISTRI;
10797       X86CC = X86::COND_S;
10798       break;
10799     case Intrinsic::x86_sse42_pcmpestris128:
10800       Opcode = X86ISD::PCMPESTRI;
10801       X86CC = X86::COND_S;
10802       break;
10803     case Intrinsic::x86_sse42_pcmpistriz128:
10804       Opcode = X86ISD::PCMPISTRI;
10805       X86CC = X86::COND_E;
10806       break;
10807     case Intrinsic::x86_sse42_pcmpestriz128:
10808       Opcode = X86ISD::PCMPESTRI;
10809       X86CC = X86::COND_E;
10810       break;
10811     }
10812     SmallVector<SDValue, 5> NewOps;
10813     NewOps.append(Op->op_begin()+1, Op->op_end());
10814     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10815     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10816     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10817                                 DAG.getConstant(X86CC, MVT::i8),
10818                                 SDValue(PCMP.getNode(), 1));
10819     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10820   }
10821
10822   case Intrinsic::x86_sse42_pcmpistri128:
10823   case Intrinsic::x86_sse42_pcmpestri128: {
10824     unsigned Opcode;
10825     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10826       Opcode = X86ISD::PCMPISTRI;
10827     else
10828       Opcode = X86ISD::PCMPESTRI;
10829
10830     SmallVector<SDValue, 5> NewOps;
10831     NewOps.append(Op->op_begin()+1, Op->op_end());
10832     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10833     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10834   }
10835   case Intrinsic::x86_fma_vfmadd_ps:
10836   case Intrinsic::x86_fma_vfmadd_pd:
10837   case Intrinsic::x86_fma_vfmsub_ps:
10838   case Intrinsic::x86_fma_vfmsub_pd:
10839   case Intrinsic::x86_fma_vfnmadd_ps:
10840   case Intrinsic::x86_fma_vfnmadd_pd:
10841   case Intrinsic::x86_fma_vfnmsub_ps:
10842   case Intrinsic::x86_fma_vfnmsub_pd:
10843   case Intrinsic::x86_fma_vfmaddsub_ps:
10844   case Intrinsic::x86_fma_vfmaddsub_pd:
10845   case Intrinsic::x86_fma_vfmsubadd_ps:
10846   case Intrinsic::x86_fma_vfmsubadd_pd:
10847   case Intrinsic::x86_fma_vfmadd_ps_256:
10848   case Intrinsic::x86_fma_vfmadd_pd_256:
10849   case Intrinsic::x86_fma_vfmsub_ps_256:
10850   case Intrinsic::x86_fma_vfmsub_pd_256:
10851   case Intrinsic::x86_fma_vfnmadd_ps_256:
10852   case Intrinsic::x86_fma_vfnmadd_pd_256:
10853   case Intrinsic::x86_fma_vfnmsub_ps_256:
10854   case Intrinsic::x86_fma_vfnmsub_pd_256:
10855   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10856   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10857   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10858   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10859     unsigned Opc;
10860     switch (IntNo) {
10861     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10862     case Intrinsic::x86_fma_vfmadd_ps:
10863     case Intrinsic::x86_fma_vfmadd_pd:
10864     case Intrinsic::x86_fma_vfmadd_ps_256:
10865     case Intrinsic::x86_fma_vfmadd_pd_256:
10866       Opc = X86ISD::FMADD;
10867       break;
10868     case Intrinsic::x86_fma_vfmsub_ps:
10869     case Intrinsic::x86_fma_vfmsub_pd:
10870     case Intrinsic::x86_fma_vfmsub_ps_256:
10871     case Intrinsic::x86_fma_vfmsub_pd_256:
10872       Opc = X86ISD::FMSUB;
10873       break;
10874     case Intrinsic::x86_fma_vfnmadd_ps:
10875     case Intrinsic::x86_fma_vfnmadd_pd:
10876     case Intrinsic::x86_fma_vfnmadd_ps_256:
10877     case Intrinsic::x86_fma_vfnmadd_pd_256:
10878       Opc = X86ISD::FNMADD;
10879       break;
10880     case Intrinsic::x86_fma_vfnmsub_ps:
10881     case Intrinsic::x86_fma_vfnmsub_pd:
10882     case Intrinsic::x86_fma_vfnmsub_ps_256:
10883     case Intrinsic::x86_fma_vfnmsub_pd_256:
10884       Opc = X86ISD::FNMSUB;
10885       break;
10886     case Intrinsic::x86_fma_vfmaddsub_ps:
10887     case Intrinsic::x86_fma_vfmaddsub_pd:
10888     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10889     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10890       Opc = X86ISD::FMADDSUB;
10891       break;
10892     case Intrinsic::x86_fma_vfmsubadd_ps:
10893     case Intrinsic::x86_fma_vfmsubadd_pd:
10894     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10895     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10896       Opc = X86ISD::FMSUBADD;
10897       break;
10898     }
10899
10900     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10901                        Op.getOperand(2), Op.getOperand(3));
10902   }
10903   }
10904 }
10905
10906 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10907   DebugLoc dl = Op.getDebugLoc();
10908   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10909   switch (IntNo) {
10910   default: return SDValue();    // Don't custom lower most intrinsics.
10911
10912   // RDRAND intrinsics.
10913   case Intrinsic::x86_rdrand_16:
10914   case Intrinsic::x86_rdrand_32:
10915   case Intrinsic::x86_rdrand_64: {
10916     // Emit the node with the right value type.
10917     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10918     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10919
10920     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10921     // return the value from Rand, which is always 0, casted to i32.
10922     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10923                       DAG.getConstant(1, Op->getValueType(1)),
10924                       DAG.getConstant(X86::COND_B, MVT::i32),
10925                       SDValue(Result.getNode(), 1) };
10926     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10927                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10928                                   Ops, 4);
10929
10930     // Return { result, isValid, chain }.
10931     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10932                        SDValue(Result.getNode(), 2));
10933   }
10934   }
10935 }
10936
10937 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10938                                            SelectionDAG &DAG) const {
10939   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10940   MFI->setReturnAddressIsTaken(true);
10941
10942   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10943   DebugLoc dl = Op.getDebugLoc();
10944   EVT PtrVT = getPointerTy();
10945
10946   if (Depth > 0) {
10947     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10948     SDValue Offset =
10949       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10950     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10951                        DAG.getNode(ISD::ADD, dl, PtrVT,
10952                                    FrameAddr, Offset),
10953                        MachinePointerInfo(), false, false, false, 0);
10954   }
10955
10956   // Just load the return address.
10957   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10958   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10959                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10960 }
10961
10962 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10963   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10964   MFI->setFrameAddressIsTaken(true);
10965
10966   EVT VT = Op.getValueType();
10967   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10968   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10969   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10970   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10971   while (Depth--)
10972     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10973                             MachinePointerInfo(),
10974                             false, false, false, 0);
10975   return FrameAddr;
10976 }
10977
10978 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10979                                                      SelectionDAG &DAG) const {
10980   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10981 }
10982
10983 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10984   SDValue Chain     = Op.getOperand(0);
10985   SDValue Offset    = Op.getOperand(1);
10986   SDValue Handler   = Op.getOperand(2);
10987   DebugLoc dl       = Op.getDebugLoc();
10988
10989   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10990                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10991                                      getPointerTy());
10992   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10993
10994   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
10995                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
10996   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
10997   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
10998                        false, false, 0);
10999   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11000
11001   return DAG.getNode(X86ISD::EH_RETURN, dl,
11002                      MVT::Other,
11003                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11004 }
11005
11006 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11007                                                SelectionDAG &DAG) const {
11008   DebugLoc DL = Op.getDebugLoc();
11009   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11010                      DAG.getVTList(MVT::i32, MVT::Other),
11011                      Op.getOperand(0), Op.getOperand(1));
11012 }
11013
11014 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11015                                                 SelectionDAG &DAG) const {
11016   DebugLoc DL = Op.getDebugLoc();
11017   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11018                      Op.getOperand(0), Op.getOperand(1));
11019 }
11020
11021 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11022   return Op.getOperand(0);
11023 }
11024
11025 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11026                                                 SelectionDAG &DAG) const {
11027   SDValue Root = Op.getOperand(0);
11028   SDValue Trmp = Op.getOperand(1); // trampoline
11029   SDValue FPtr = Op.getOperand(2); // nested function
11030   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11031   DebugLoc dl  = Op.getDebugLoc();
11032
11033   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11034   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11035
11036   if (Subtarget->is64Bit()) {
11037     SDValue OutChains[6];
11038
11039     // Large code-model.
11040     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11041     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11042
11043     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11044     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11045
11046     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11047
11048     // Load the pointer to the nested function into R11.
11049     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11050     SDValue Addr = Trmp;
11051     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11052                                 Addr, MachinePointerInfo(TrmpAddr),
11053                                 false, false, 0);
11054
11055     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11056                        DAG.getConstant(2, MVT::i64));
11057     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11058                                 MachinePointerInfo(TrmpAddr, 2),
11059                                 false, false, 2);
11060
11061     // Load the 'nest' parameter value into R10.
11062     // R10 is specified in X86CallingConv.td
11063     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11064     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11065                        DAG.getConstant(10, MVT::i64));
11066     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11067                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11068                                 false, false, 0);
11069
11070     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11071                        DAG.getConstant(12, MVT::i64));
11072     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11073                                 MachinePointerInfo(TrmpAddr, 12),
11074                                 false, false, 2);
11075
11076     // Jump to the nested function.
11077     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11078     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11079                        DAG.getConstant(20, MVT::i64));
11080     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11081                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11082                                 false, false, 0);
11083
11084     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11085     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11086                        DAG.getConstant(22, MVT::i64));
11087     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11088                                 MachinePointerInfo(TrmpAddr, 22),
11089                                 false, false, 0);
11090
11091     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11092   } else {
11093     const Function *Func =
11094       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11095     CallingConv::ID CC = Func->getCallingConv();
11096     unsigned NestReg;
11097
11098     switch (CC) {
11099     default:
11100       llvm_unreachable("Unsupported calling convention");
11101     case CallingConv::C:
11102     case CallingConv::X86_StdCall: {
11103       // Pass 'nest' parameter in ECX.
11104       // Must be kept in sync with X86CallingConv.td
11105       NestReg = X86::ECX;
11106
11107       // Check that ECX wasn't needed by an 'inreg' parameter.
11108       FunctionType *FTy = Func->getFunctionType();
11109       const AttributeSet &Attrs = Func->getAttributes();
11110
11111       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11112         unsigned InRegCount = 0;
11113         unsigned Idx = 1;
11114
11115         for (FunctionType::param_iterator I = FTy->param_begin(),
11116              E = FTy->param_end(); I != E; ++I, ++Idx)
11117           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11118             // FIXME: should only count parameters that are lowered to integers.
11119             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11120
11121         if (InRegCount > 2) {
11122           report_fatal_error("Nest register in use - reduce number of inreg"
11123                              " parameters!");
11124         }
11125       }
11126       break;
11127     }
11128     case CallingConv::X86_FastCall:
11129     case CallingConv::X86_ThisCall:
11130     case CallingConv::Fast:
11131       // Pass 'nest' parameter in EAX.
11132       // Must be kept in sync with X86CallingConv.td
11133       NestReg = X86::EAX;
11134       break;
11135     }
11136
11137     SDValue OutChains[4];
11138     SDValue Addr, Disp;
11139
11140     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11141                        DAG.getConstant(10, MVT::i32));
11142     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11143
11144     // This is storing the opcode for MOV32ri.
11145     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11146     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11147     OutChains[0] = DAG.getStore(Root, dl,
11148                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11149                                 Trmp, MachinePointerInfo(TrmpAddr),
11150                                 false, false, 0);
11151
11152     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11153                        DAG.getConstant(1, MVT::i32));
11154     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11155                                 MachinePointerInfo(TrmpAddr, 1),
11156                                 false, false, 1);
11157
11158     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11159     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11160                        DAG.getConstant(5, MVT::i32));
11161     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11162                                 MachinePointerInfo(TrmpAddr, 5),
11163                                 false, false, 1);
11164
11165     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11166                        DAG.getConstant(6, MVT::i32));
11167     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11168                                 MachinePointerInfo(TrmpAddr, 6),
11169                                 false, false, 1);
11170
11171     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11172   }
11173 }
11174
11175 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11176                                             SelectionDAG &DAG) const {
11177   /*
11178    The rounding mode is in bits 11:10 of FPSR, and has the following
11179    settings:
11180      00 Round to nearest
11181      01 Round to -inf
11182      10 Round to +inf
11183      11 Round to 0
11184
11185   FLT_ROUNDS, on the other hand, expects the following:
11186     -1 Undefined
11187      0 Round to 0
11188      1 Round to nearest
11189      2 Round to +inf
11190      3 Round to -inf
11191
11192   To perform the conversion, we do:
11193     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11194   */
11195
11196   MachineFunction &MF = DAG.getMachineFunction();
11197   const TargetMachine &TM = MF.getTarget();
11198   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11199   unsigned StackAlignment = TFI.getStackAlignment();
11200   EVT VT = Op.getValueType();
11201   DebugLoc DL = Op.getDebugLoc();
11202
11203   // Save FP Control Word to stack slot
11204   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11205   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11206
11207   MachineMemOperand *MMO =
11208    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11209                            MachineMemOperand::MOStore, 2, 2);
11210
11211   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11212   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11213                                           DAG.getVTList(MVT::Other),
11214                                           Ops, 2, MVT::i16, MMO);
11215
11216   // Load FP Control Word from stack slot
11217   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11218                             MachinePointerInfo(), false, false, false, 0);
11219
11220   // Transform as necessary
11221   SDValue CWD1 =
11222     DAG.getNode(ISD::SRL, DL, MVT::i16,
11223                 DAG.getNode(ISD::AND, DL, MVT::i16,
11224                             CWD, DAG.getConstant(0x800, MVT::i16)),
11225                 DAG.getConstant(11, MVT::i8));
11226   SDValue CWD2 =
11227     DAG.getNode(ISD::SRL, DL, MVT::i16,
11228                 DAG.getNode(ISD::AND, DL, MVT::i16,
11229                             CWD, DAG.getConstant(0x400, MVT::i16)),
11230                 DAG.getConstant(9, MVT::i8));
11231
11232   SDValue RetVal =
11233     DAG.getNode(ISD::AND, DL, MVT::i16,
11234                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11235                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11236                             DAG.getConstant(1, MVT::i16)),
11237                 DAG.getConstant(3, MVT::i16));
11238
11239   return DAG.getNode((VT.getSizeInBits() < 16 ?
11240                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11241 }
11242
11243 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11244   EVT VT = Op.getValueType();
11245   EVT OpVT = VT;
11246   unsigned NumBits = VT.getSizeInBits();
11247   DebugLoc dl = Op.getDebugLoc();
11248
11249   Op = Op.getOperand(0);
11250   if (VT == MVT::i8) {
11251     // Zero extend to i32 since there is not an i8 bsr.
11252     OpVT = MVT::i32;
11253     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11254   }
11255
11256   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11257   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11258   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11259
11260   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11261   SDValue Ops[] = {
11262     Op,
11263     DAG.getConstant(NumBits+NumBits-1, OpVT),
11264     DAG.getConstant(X86::COND_E, MVT::i8),
11265     Op.getValue(1)
11266   };
11267   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11268
11269   // Finally xor with NumBits-1.
11270   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11271
11272   if (VT == MVT::i8)
11273     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11274   return Op;
11275 }
11276
11277 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11278   EVT VT = Op.getValueType();
11279   EVT OpVT = VT;
11280   unsigned NumBits = VT.getSizeInBits();
11281   DebugLoc dl = Op.getDebugLoc();
11282
11283   Op = Op.getOperand(0);
11284   if (VT == MVT::i8) {
11285     // Zero extend to i32 since there is not an i8 bsr.
11286     OpVT = MVT::i32;
11287     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11288   }
11289
11290   // Issue a bsr (scan bits in reverse).
11291   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11292   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11293
11294   // And xor with NumBits-1.
11295   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11296
11297   if (VT == MVT::i8)
11298     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11299   return Op;
11300 }
11301
11302 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11303   EVT VT = Op.getValueType();
11304   unsigned NumBits = VT.getSizeInBits();
11305   DebugLoc dl = Op.getDebugLoc();
11306   Op = Op.getOperand(0);
11307
11308   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11309   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11310   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11311
11312   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11313   SDValue Ops[] = {
11314     Op,
11315     DAG.getConstant(NumBits, VT),
11316     DAG.getConstant(X86::COND_E, MVT::i8),
11317     Op.getValue(1)
11318   };
11319   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11320 }
11321
11322 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11323 // ones, and then concatenate the result back.
11324 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11325   EVT VT = Op.getValueType();
11326
11327   assert(VT.is256BitVector() && VT.isInteger() &&
11328          "Unsupported value type for operation");
11329
11330   unsigned NumElems = VT.getVectorNumElements();
11331   DebugLoc dl = Op.getDebugLoc();
11332
11333   // Extract the LHS vectors
11334   SDValue LHS = Op.getOperand(0);
11335   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11336   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11337
11338   // Extract the RHS vectors
11339   SDValue RHS = Op.getOperand(1);
11340   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11341   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11342
11343   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11344   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11345
11346   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11347                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11348                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11349 }
11350
11351 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11352   assert(Op.getValueType().is256BitVector() &&
11353          Op.getValueType().isInteger() &&
11354          "Only handle AVX 256-bit vector integer operation");
11355   return Lower256IntArith(Op, DAG);
11356 }
11357
11358 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11359   assert(Op.getValueType().is256BitVector() &&
11360          Op.getValueType().isInteger() &&
11361          "Only handle AVX 256-bit vector integer operation");
11362   return Lower256IntArith(Op, DAG);
11363 }
11364
11365 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11366                         SelectionDAG &DAG) {
11367   DebugLoc dl = Op.getDebugLoc();
11368   EVT VT = Op.getValueType();
11369
11370   // Decompose 256-bit ops into smaller 128-bit ops.
11371   if (VT.is256BitVector() && !Subtarget->hasInt256())
11372     return Lower256IntArith(Op, DAG);
11373
11374   SDValue A = Op.getOperand(0);
11375   SDValue B = Op.getOperand(1);
11376
11377   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11378   if (VT == MVT::v4i32) {
11379     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11380            "Should not custom lower when pmuldq is available!");
11381
11382     // Extract the odd parts.
11383     const int UnpackMask[] = { 1, -1, 3, -1 };
11384     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11385     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11386
11387     // Multiply the even parts.
11388     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11389     // Now multiply odd parts.
11390     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11391
11392     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11393     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11394
11395     // Merge the two vectors back together with a shuffle. This expands into 2
11396     // shuffles.
11397     const int ShufMask[] = { 0, 4, 2, 6 };
11398     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11399   }
11400
11401   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11402          "Only know how to lower V2I64/V4I64 multiply");
11403
11404   //  Ahi = psrlqi(a, 32);
11405   //  Bhi = psrlqi(b, 32);
11406   //
11407   //  AloBlo = pmuludq(a, b);
11408   //  AloBhi = pmuludq(a, Bhi);
11409   //  AhiBlo = pmuludq(Ahi, b);
11410
11411   //  AloBhi = psllqi(AloBhi, 32);
11412   //  AhiBlo = psllqi(AhiBlo, 32);
11413   //  return AloBlo + AloBhi + AhiBlo;
11414
11415   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11416
11417   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11418   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11419
11420   // Bit cast to 32-bit vectors for MULUDQ
11421   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11422   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11423   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11424   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11425   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11426
11427   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11428   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11429   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11430
11431   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11432   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11433
11434   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11435   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11436 }
11437
11438 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11439   EVT VT = Op.getValueType();
11440   EVT EltTy = VT.getVectorElementType();
11441   unsigned NumElts = VT.getVectorNumElements();
11442   SDValue N0 = Op.getOperand(0);
11443   DebugLoc dl = Op.getDebugLoc();
11444
11445   // Lower sdiv X, pow2-const.
11446   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11447   if (!C)
11448     return SDValue();
11449
11450   APInt SplatValue, SplatUndef;
11451   unsigned MinSplatBits;
11452   bool HasAnyUndefs;
11453   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11454     return SDValue();
11455
11456   if ((SplatValue != 0) &&
11457       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11458     unsigned lg2 = SplatValue.countTrailingZeros();
11459     // Splat the sign bit.
11460     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11461     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11462     // Add (N0 < 0) ? abs2 - 1 : 0;
11463     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11464     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11465     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11466     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11467     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11468
11469     // If we're dividing by a positive value, we're done.  Otherwise, we must
11470     // negate the result.
11471     if (SplatValue.isNonNegative())
11472       return SRA;
11473
11474     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11475     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11476     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11477   }
11478   return SDValue();
11479 }
11480
11481 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11482                                          const X86Subtarget *Subtarget) {
11483   EVT VT = Op.getValueType();
11484   DebugLoc dl = Op.getDebugLoc();
11485   SDValue R = Op.getOperand(0);
11486   SDValue Amt = Op.getOperand(1);
11487
11488   // Optimize shl/srl/sra with constant shift amount.
11489   if (isSplatVector(Amt.getNode())) {
11490     SDValue SclrAmt = Amt->getOperand(0);
11491     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11492       uint64_t ShiftAmt = C->getZExtValue();
11493
11494       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11495           (Subtarget->hasInt256() &&
11496            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11497         if (Op.getOpcode() == ISD::SHL)
11498           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11499                              DAG.getConstant(ShiftAmt, MVT::i32));
11500         if (Op.getOpcode() == ISD::SRL)
11501           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11502                              DAG.getConstant(ShiftAmt, MVT::i32));
11503         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11504           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11505                              DAG.getConstant(ShiftAmt, MVT::i32));
11506       }
11507
11508       if (VT == MVT::v16i8) {
11509         if (Op.getOpcode() == ISD::SHL) {
11510           // Make a large shift.
11511           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11512                                     DAG.getConstant(ShiftAmt, MVT::i32));
11513           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11514           // Zero out the rightmost bits.
11515           SmallVector<SDValue, 16> V(16,
11516                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11517                                                      MVT::i8));
11518           return DAG.getNode(ISD::AND, dl, VT, SHL,
11519                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11520         }
11521         if (Op.getOpcode() == ISD::SRL) {
11522           // Make a large shift.
11523           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11524                                     DAG.getConstant(ShiftAmt, MVT::i32));
11525           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11526           // Zero out the leftmost bits.
11527           SmallVector<SDValue, 16> V(16,
11528                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11529                                                      MVT::i8));
11530           return DAG.getNode(ISD::AND, dl, VT, SRL,
11531                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11532         }
11533         if (Op.getOpcode() == ISD::SRA) {
11534           if (ShiftAmt == 7) {
11535             // R s>> 7  ===  R s< 0
11536             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11537             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11538           }
11539
11540           // R s>> a === ((R u>> a) ^ m) - m
11541           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11542           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11543                                                          MVT::i8));
11544           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11545           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11546           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11547           return Res;
11548         }
11549         llvm_unreachable("Unknown shift opcode.");
11550       }
11551
11552       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11553         if (Op.getOpcode() == ISD::SHL) {
11554           // Make a large shift.
11555           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11556                                     DAG.getConstant(ShiftAmt, MVT::i32));
11557           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11558           // Zero out the rightmost bits.
11559           SmallVector<SDValue, 32> V(32,
11560                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11561                                                      MVT::i8));
11562           return DAG.getNode(ISD::AND, dl, VT, SHL,
11563                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11564         }
11565         if (Op.getOpcode() == ISD::SRL) {
11566           // Make a large shift.
11567           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11568                                     DAG.getConstant(ShiftAmt, MVT::i32));
11569           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11570           // Zero out the leftmost bits.
11571           SmallVector<SDValue, 32> V(32,
11572                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11573                                                      MVT::i8));
11574           return DAG.getNode(ISD::AND, dl, VT, SRL,
11575                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11576         }
11577         if (Op.getOpcode() == ISD::SRA) {
11578           if (ShiftAmt == 7) {
11579             // R s>> 7  ===  R s< 0
11580             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11581             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11582           }
11583
11584           // R s>> a === ((R u>> a) ^ m) - m
11585           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11586           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11587                                                          MVT::i8));
11588           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11589           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11590           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11591           return Res;
11592         }
11593         llvm_unreachable("Unknown shift opcode.");
11594       }
11595     }
11596   }
11597
11598   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11599   if (!Subtarget->is64Bit() &&
11600       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11601       Amt.getOpcode() == ISD::BITCAST &&
11602       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11603     Amt = Amt.getOperand(0);
11604     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11605                      VT.getVectorNumElements();
11606     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11607     uint64_t ShiftAmt = 0;
11608     for (unsigned i = 0; i != Ratio; ++i) {
11609       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11610       if (C == 0)
11611         return SDValue();
11612       // 6 == Log2(64)
11613       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11614     }
11615     // Check remaining shift amounts.
11616     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11617       uint64_t ShAmt = 0;
11618       for (unsigned j = 0; j != Ratio; ++j) {
11619         ConstantSDNode *C =
11620           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11621         if (C == 0)
11622           return SDValue();
11623         // 6 == Log2(64)
11624         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11625       }
11626       if (ShAmt != ShiftAmt)
11627         return SDValue();
11628     }
11629     switch (Op.getOpcode()) {
11630     default:
11631       llvm_unreachable("Unknown shift opcode!");
11632     case ISD::SHL:
11633       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11634                          DAG.getConstant(ShiftAmt, MVT::i32));
11635     case ISD::SRL:
11636       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11637                          DAG.getConstant(ShiftAmt, MVT::i32));
11638     case ISD::SRA:
11639       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11640                          DAG.getConstant(ShiftAmt, MVT::i32));
11641     }
11642   }
11643
11644   return SDValue();
11645 }
11646
11647 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11648                                         const X86Subtarget* Subtarget) {
11649   EVT VT = Op.getValueType();
11650   DebugLoc dl = Op.getDebugLoc();
11651   SDValue R = Op.getOperand(0);
11652   SDValue Amt = Op.getOperand(1);
11653
11654   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11655       VT == MVT::v4i32 || VT == MVT::v8i16 ||
11656       (Subtarget->hasInt256() &&
11657        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11658         VT == MVT::v8i32 || VT == MVT::v16i16))) {
11659     SDValue BaseShAmt;
11660     EVT EltVT = VT.getVectorElementType();
11661
11662     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11663       unsigned NumElts = VT.getVectorNumElements();
11664       unsigned i, j;
11665       for (i = 0; i != NumElts; ++i) {
11666         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11667           continue;
11668         break;
11669       }
11670       for (j = i; j != NumElts; ++j) {
11671         SDValue Arg = Amt.getOperand(j);
11672         if (Arg.getOpcode() == ISD::UNDEF) continue;
11673         if (Arg != Amt.getOperand(i))
11674           break;
11675       }
11676       if (i != NumElts && j == NumElts)
11677         BaseShAmt = Amt.getOperand(i);
11678     } else {
11679       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11680         Amt = Amt.getOperand(0);
11681       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11682                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11683         SDValue InVec = Amt.getOperand(0);
11684         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11685           unsigned NumElts = InVec.getValueType().getVectorNumElements();
11686           unsigned i = 0;
11687           for (; i != NumElts; ++i) {
11688             SDValue Arg = InVec.getOperand(i);
11689             if (Arg.getOpcode() == ISD::UNDEF) continue;
11690             BaseShAmt = Arg;
11691             break;
11692           }
11693         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11694            if (ConstantSDNode *C =
11695                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11696              unsigned SplatIdx =
11697                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11698              if (C->getZExtValue() == SplatIdx)
11699                BaseShAmt = InVec.getOperand(1);
11700            }
11701         }
11702         if (BaseShAmt.getNode() == 0)
11703           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11704                                   DAG.getIntPtrConstant(0));
11705       }
11706     }
11707
11708     if (BaseShAmt.getNode()) {
11709       if (EltVT.bitsGT(MVT::i32))
11710         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11711       else if (EltVT.bitsLT(MVT::i32))
11712         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11713
11714       switch (Op.getOpcode()) {
11715       default:
11716         llvm_unreachable("Unknown shift opcode!");
11717       case ISD::SHL:
11718         switch (VT.getSimpleVT().SimpleTy) {
11719         default: return SDValue();
11720         case MVT::v2i64:
11721         case MVT::v4i32:
11722         case MVT::v8i16:
11723         case MVT::v4i64:
11724         case MVT::v8i32:
11725         case MVT::v16i16:
11726           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11727         }
11728       case ISD::SRA:
11729         switch (VT.getSimpleVT().SimpleTy) {
11730         default: return SDValue();
11731         case MVT::v4i32:
11732         case MVT::v8i16:
11733         case MVT::v8i32:
11734         case MVT::v16i16:
11735           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11736         }
11737       case ISD::SRL:
11738         switch (VT.getSimpleVT().SimpleTy) {
11739         default: return SDValue();
11740         case MVT::v2i64:
11741         case MVT::v4i32:
11742         case MVT::v8i16:
11743         case MVT::v4i64:
11744         case MVT::v8i32:
11745         case MVT::v16i16:
11746           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11747         }
11748       }
11749     }
11750   }
11751
11752   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11753   if (!Subtarget->is64Bit() &&
11754       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11755       Amt.getOpcode() == ISD::BITCAST &&
11756       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11757     Amt = Amt.getOperand(0);
11758     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11759                      VT.getVectorNumElements();
11760     std::vector<SDValue> Vals(Ratio);
11761     for (unsigned i = 0; i != Ratio; ++i)
11762       Vals[i] = Amt.getOperand(i);
11763     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11764       for (unsigned j = 0; j != Ratio; ++j)
11765         if (Vals[j] != Amt.getOperand(i + j))
11766           return SDValue();
11767     }
11768     switch (Op.getOpcode()) {
11769     default:
11770       llvm_unreachable("Unknown shift opcode!");
11771     case ISD::SHL:
11772       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11773     case ISD::SRL:
11774       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11775     case ISD::SRA:
11776       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11777     }
11778   }
11779
11780   return SDValue();
11781 }
11782
11783 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11784
11785   EVT VT = Op.getValueType();
11786   DebugLoc dl = Op.getDebugLoc();
11787   SDValue R = Op.getOperand(0);
11788   SDValue Amt = Op.getOperand(1);
11789   SDValue V;
11790
11791   if (!Subtarget->hasSSE2())
11792     return SDValue();
11793
11794   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11795   if (V.getNode())
11796     return V;
11797
11798   V = LowerScalarVariableShift(Op, DAG, Subtarget);
11799   if (V.getNode())
11800       return V;
11801
11802   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11803   if (Subtarget->hasInt256()) {
11804     if (Op.getOpcode() == ISD::SRL &&
11805         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11806          VT == MVT::v4i64 || VT == MVT::v8i32))
11807       return Op;
11808     if (Op.getOpcode() == ISD::SHL &&
11809         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11810          VT == MVT::v4i64 || VT == MVT::v8i32))
11811       return Op;
11812     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11813       return Op;
11814   }
11815
11816   // Lower SHL with variable shift amount.
11817   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11818     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11819
11820     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11821     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11822     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11823     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11824   }
11825   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11826     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11827
11828     // a = a << 5;
11829     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11830     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11831
11832     // Turn 'a' into a mask suitable for VSELECT
11833     SDValue VSelM = DAG.getConstant(0x80, VT);
11834     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11835     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11836
11837     SDValue CM1 = DAG.getConstant(0x0f, VT);
11838     SDValue CM2 = DAG.getConstant(0x3f, VT);
11839
11840     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11841     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11842     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11843                             DAG.getConstant(4, MVT::i32), DAG);
11844     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11845     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11846
11847     // a += a
11848     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11849     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11850     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11851
11852     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11853     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11854     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11855                             DAG.getConstant(2, MVT::i32), DAG);
11856     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11857     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11858
11859     // a += a
11860     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11861     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11862     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11863
11864     // return VSELECT(r, r+r, a);
11865     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11866                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11867     return R;
11868   }
11869
11870   // Decompose 256-bit shifts into smaller 128-bit shifts.
11871   if (VT.is256BitVector()) {
11872     unsigned NumElems = VT.getVectorNumElements();
11873     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11874     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11875
11876     // Extract the two vectors
11877     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11878     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11879
11880     // Recreate the shift amount vectors
11881     SDValue Amt1, Amt2;
11882     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11883       // Constant shift amount
11884       SmallVector<SDValue, 4> Amt1Csts;
11885       SmallVector<SDValue, 4> Amt2Csts;
11886       for (unsigned i = 0; i != NumElems/2; ++i)
11887         Amt1Csts.push_back(Amt->getOperand(i));
11888       for (unsigned i = NumElems/2; i != NumElems; ++i)
11889         Amt2Csts.push_back(Amt->getOperand(i));
11890
11891       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11892                                  &Amt1Csts[0], NumElems/2);
11893       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11894                                  &Amt2Csts[0], NumElems/2);
11895     } else {
11896       // Variable shift amount
11897       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11898       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11899     }
11900
11901     // Issue new vector shifts for the smaller types
11902     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11903     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11904
11905     // Concatenate the result back
11906     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11907   }
11908
11909   return SDValue();
11910 }
11911
11912 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11913   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11914   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11915   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11916   // has only one use.
11917   SDNode *N = Op.getNode();
11918   SDValue LHS = N->getOperand(0);
11919   SDValue RHS = N->getOperand(1);
11920   unsigned BaseOp = 0;
11921   unsigned Cond = 0;
11922   DebugLoc DL = Op.getDebugLoc();
11923   switch (Op.getOpcode()) {
11924   default: llvm_unreachable("Unknown ovf instruction!");
11925   case ISD::SADDO:
11926     // A subtract of one will be selected as a INC. Note that INC doesn't
11927     // set CF, so we can't do this for UADDO.
11928     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11929       if (C->isOne()) {
11930         BaseOp = X86ISD::INC;
11931         Cond = X86::COND_O;
11932         break;
11933       }
11934     BaseOp = X86ISD::ADD;
11935     Cond = X86::COND_O;
11936     break;
11937   case ISD::UADDO:
11938     BaseOp = X86ISD::ADD;
11939     Cond = X86::COND_B;
11940     break;
11941   case ISD::SSUBO:
11942     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11943     // set CF, so we can't do this for USUBO.
11944     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11945       if (C->isOne()) {
11946         BaseOp = X86ISD::DEC;
11947         Cond = X86::COND_O;
11948         break;
11949       }
11950     BaseOp = X86ISD::SUB;
11951     Cond = X86::COND_O;
11952     break;
11953   case ISD::USUBO:
11954     BaseOp = X86ISD::SUB;
11955     Cond = X86::COND_B;
11956     break;
11957   case ISD::SMULO:
11958     BaseOp = X86ISD::SMUL;
11959     Cond = X86::COND_O;
11960     break;
11961   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11962     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11963                                  MVT::i32);
11964     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11965
11966     SDValue SetCC =
11967       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11968                   DAG.getConstant(X86::COND_O, MVT::i32),
11969                   SDValue(Sum.getNode(), 2));
11970
11971     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11972   }
11973   }
11974
11975   // Also sets EFLAGS.
11976   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11977   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11978
11979   SDValue SetCC =
11980     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11981                 DAG.getConstant(Cond, MVT::i32),
11982                 SDValue(Sum.getNode(), 1));
11983
11984   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11985 }
11986
11987 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11988                                                   SelectionDAG &DAG) const {
11989   DebugLoc dl = Op.getDebugLoc();
11990   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11991   EVT VT = Op.getValueType();
11992
11993   if (!Subtarget->hasSSE2() || !VT.isVector())
11994     return SDValue();
11995
11996   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11997                       ExtraVT.getScalarType().getSizeInBits();
11998   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11999
12000   switch (VT.getSimpleVT().SimpleTy) {
12001     default: return SDValue();
12002     case MVT::v8i32:
12003     case MVT::v16i16:
12004       if (!Subtarget->hasFp256())
12005         return SDValue();
12006       if (!Subtarget->hasInt256()) {
12007         // needs to be split
12008         unsigned NumElems = VT.getVectorNumElements();
12009
12010         // Extract the LHS vectors
12011         SDValue LHS = Op.getOperand(0);
12012         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12013         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12014
12015         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12016         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12017
12018         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12019         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12020         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12021                                    ExtraNumElems/2);
12022         SDValue Extra = DAG.getValueType(ExtraVT);
12023
12024         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12025         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12026
12027         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12028       }
12029       // fall through
12030     case MVT::v4i32:
12031     case MVT::v8i16: {
12032       // (sext (vzext x)) -> (vsext x)
12033       SDValue Op0 = Op.getOperand(0);
12034       SDValue Op00 = Op0.getOperand(0);
12035       SDValue Tmp1;
12036       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12037       if (Op0.getOpcode() == ISD::BITCAST &&
12038           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12039         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12040       if (Tmp1.getNode()) {
12041         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12042         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12043                "This optimization is invalid without a VZEXT.");
12044         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12045       }
12046
12047       // If the above didn't work, then just use Shift-Left + Shift-Right.
12048       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12049       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12050     }
12051   }
12052 }
12053
12054 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
12055                               SelectionDAG &DAG) {
12056   DebugLoc dl = Op.getDebugLoc();
12057
12058   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
12059   // There isn't any reason to disable it if the target processor supports it.
12060   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
12061     SDValue Chain = Op.getOperand(0);
12062     SDValue Zero = DAG.getConstant(0, MVT::i32);
12063     SDValue Ops[] = {
12064       DAG.getRegister(X86::ESP, MVT::i32), // Base
12065       DAG.getTargetConstant(1, MVT::i8),   // Scale
12066       DAG.getRegister(0, MVT::i32),        // Index
12067       DAG.getTargetConstant(0, MVT::i32),  // Disp
12068       DAG.getRegister(0, MVT::i32),        // Segment.
12069       Zero,
12070       Chain
12071     };
12072     SDNode *Res =
12073       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12074                           array_lengthof(Ops));
12075     return SDValue(Res, 0);
12076   }
12077
12078   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
12079   if (!isDev)
12080     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12081
12082   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12083   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12084   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
12085   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
12086
12087   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
12088   if (!Op1 && !Op2 && !Op3 && Op4)
12089     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
12090
12091   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
12092   if (Op1 && !Op2 && !Op3 && !Op4)
12093     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
12094
12095   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
12096   //           (MFENCE)>;
12097   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12098 }
12099
12100 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12101                                  SelectionDAG &DAG) {
12102   DebugLoc dl = Op.getDebugLoc();
12103   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12104     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12105   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12106     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12107
12108   // The only fence that needs an instruction is a sequentially-consistent
12109   // cross-thread fence.
12110   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12111     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12112     // no-sse2). There isn't any reason to disable it if the target processor
12113     // supports it.
12114     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12115       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12116
12117     SDValue Chain = Op.getOperand(0);
12118     SDValue Zero = DAG.getConstant(0, MVT::i32);
12119     SDValue Ops[] = {
12120       DAG.getRegister(X86::ESP, MVT::i32), // Base
12121       DAG.getTargetConstant(1, MVT::i8),   // Scale
12122       DAG.getRegister(0, MVT::i32),        // Index
12123       DAG.getTargetConstant(0, MVT::i32),  // Disp
12124       DAG.getRegister(0, MVT::i32),        // Segment.
12125       Zero,
12126       Chain
12127     };
12128     SDNode *Res =
12129       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12130                          array_lengthof(Ops));
12131     return SDValue(Res, 0);
12132   }
12133
12134   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12135   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12136 }
12137
12138 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12139                              SelectionDAG &DAG) {
12140   EVT T = Op.getValueType();
12141   DebugLoc DL = Op.getDebugLoc();
12142   unsigned Reg = 0;
12143   unsigned size = 0;
12144   switch(T.getSimpleVT().SimpleTy) {
12145   default: llvm_unreachable("Invalid value type!");
12146   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12147   case MVT::i16: Reg = X86::AX;  size = 2; break;
12148   case MVT::i32: Reg = X86::EAX; size = 4; break;
12149   case MVT::i64:
12150     assert(Subtarget->is64Bit() && "Node not type legal!");
12151     Reg = X86::RAX; size = 8;
12152     break;
12153   }
12154   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12155                                     Op.getOperand(2), SDValue());
12156   SDValue Ops[] = { cpIn.getValue(0),
12157                     Op.getOperand(1),
12158                     Op.getOperand(3),
12159                     DAG.getTargetConstant(size, MVT::i8),
12160                     cpIn.getValue(1) };
12161   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12162   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12163   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12164                                            Ops, 5, T, MMO);
12165   SDValue cpOut =
12166     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12167   return cpOut;
12168 }
12169
12170 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12171                                      SelectionDAG &DAG) {
12172   assert(Subtarget->is64Bit() && "Result not type legalized?");
12173   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12174   SDValue TheChain = Op.getOperand(0);
12175   DebugLoc dl = Op.getDebugLoc();
12176   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12177   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12178   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12179                                    rax.getValue(2));
12180   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12181                             DAG.getConstant(32, MVT::i8));
12182   SDValue Ops[] = {
12183     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12184     rdx.getValue(1)
12185   };
12186   return DAG.getMergeValues(Ops, 2, dl);
12187 }
12188
12189 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12190   EVT SrcVT = Op.getOperand(0).getValueType();
12191   EVT DstVT = Op.getValueType();
12192   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12193          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12194   assert((DstVT == MVT::i64 ||
12195           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12196          "Unexpected custom BITCAST");
12197   // i64 <=> MMX conversions are Legal.
12198   if (SrcVT==MVT::i64 && DstVT.isVector())
12199     return Op;
12200   if (DstVT==MVT::i64 && SrcVT.isVector())
12201     return Op;
12202   // MMX <=> MMX conversions are Legal.
12203   if (SrcVT.isVector() && DstVT.isVector())
12204     return Op;
12205   // All other conversions need to be expanded.
12206   return SDValue();
12207 }
12208
12209 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12210   SDNode *Node = Op.getNode();
12211   DebugLoc dl = Node->getDebugLoc();
12212   EVT T = Node->getValueType(0);
12213   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12214                               DAG.getConstant(0, T), Node->getOperand(2));
12215   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12216                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12217                        Node->getOperand(0),
12218                        Node->getOperand(1), negOp,
12219                        cast<AtomicSDNode>(Node)->getSrcValue(),
12220                        cast<AtomicSDNode>(Node)->getAlignment(),
12221                        cast<AtomicSDNode>(Node)->getOrdering(),
12222                        cast<AtomicSDNode>(Node)->getSynchScope());
12223 }
12224
12225 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12226   SDNode *Node = Op.getNode();
12227   DebugLoc dl = Node->getDebugLoc();
12228   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12229
12230   // Convert seq_cst store -> xchg
12231   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12232   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12233   //        (The only way to get a 16-byte store is cmpxchg16b)
12234   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12235   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12236       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12237     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12238                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12239                                  Node->getOperand(0),
12240                                  Node->getOperand(1), Node->getOperand(2),
12241                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12242                                  cast<AtomicSDNode>(Node)->getOrdering(),
12243                                  cast<AtomicSDNode>(Node)->getSynchScope());
12244     return Swap.getValue(1);
12245   }
12246   // Other atomic stores have a simple pattern.
12247   return Op;
12248 }
12249
12250 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12251   EVT VT = Op.getNode()->getValueType(0);
12252
12253   // Let legalize expand this if it isn't a legal type yet.
12254   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12255     return SDValue();
12256
12257   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12258
12259   unsigned Opc;
12260   bool ExtraOp = false;
12261   switch (Op.getOpcode()) {
12262   default: llvm_unreachable("Invalid code");
12263   case ISD::ADDC: Opc = X86ISD::ADD; break;
12264   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12265   case ISD::SUBC: Opc = X86ISD::SUB; break;
12266   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12267   }
12268
12269   if (!ExtraOp)
12270     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12271                        Op.getOperand(1));
12272   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12273                      Op.getOperand(1), Op.getOperand(2));
12274 }
12275
12276 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12277   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12278
12279   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12280   // which returns the values in two XMM registers.
12281   DebugLoc dl = Op.getDebugLoc();
12282   SDValue Arg = Op.getOperand(0);
12283   EVT ArgVT = Arg.getValueType();
12284   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12285
12286   ArgListTy Args;
12287   ArgListEntry Entry;
12288
12289   Entry.Node = Arg;
12290   Entry.Ty = ArgTy;
12291   Entry.isSExt = false;
12292   Entry.isZExt = false;
12293   Args.push_back(Entry);
12294
12295   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12296   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12297   // the results are returned via SRet in memory.
12298   const char *LibcallName = (ArgVT == MVT::f64)
12299     ? "__sincos_stret" : "__sincosf_stret";
12300   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12301
12302   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
12303   TargetLowering::
12304     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12305                          false, false, false, false, 0,
12306                          CallingConv::C, /*isTaillCall=*/false,
12307                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12308                          Callee, Args, DAG, dl);
12309   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12310   return CallResult.first;
12311 }
12312
12313 /// LowerOperation - Provide custom lowering hooks for some operations.
12314 ///
12315 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12316   switch (Op.getOpcode()) {
12317   default: llvm_unreachable("Should not custom lower this!");
12318   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12319   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12320   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12321   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12322   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12323   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12324   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12325   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12326   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12327   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12328   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12329   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12330   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12331   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12332   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12333   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12334   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12335   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12336   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12337   case ISD::SHL_PARTS:
12338   case ISD::SRA_PARTS:
12339   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12340   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12341   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12342   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12343   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12344   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12345   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12346   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12347   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12348   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12349   case ISD::FABS:               return LowerFABS(Op, DAG);
12350   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12351   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12352   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12353   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12354   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12355   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12356   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12357   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12358   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12359   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12360   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12361   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12362   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12363   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12364   case ISD::FRAME_TO_ARGS_OFFSET:
12365                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12366   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12367   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12368   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12369   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12370   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12371   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12372   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12373   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12374   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12375   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12376   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12377   case ISD::SRA:
12378   case ISD::SRL:
12379   case ISD::SHL:                return LowerShift(Op, DAG);
12380   case ISD::SADDO:
12381   case ISD::UADDO:
12382   case ISD::SSUBO:
12383   case ISD::USUBO:
12384   case ISD::SMULO:
12385   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12386   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12387   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12388   case ISD::ADDC:
12389   case ISD::ADDE:
12390   case ISD::SUBC:
12391   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12392   case ISD::ADD:                return LowerADD(Op, DAG);
12393   case ISD::SUB:                return LowerSUB(Op, DAG);
12394   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12395   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12396   }
12397 }
12398
12399 static void ReplaceATOMIC_LOAD(SDNode *Node,
12400                                   SmallVectorImpl<SDValue> &Results,
12401                                   SelectionDAG &DAG) {
12402   DebugLoc dl = Node->getDebugLoc();
12403   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12404
12405   // Convert wide load -> cmpxchg8b/cmpxchg16b
12406   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12407   //        (The only way to get a 16-byte load is cmpxchg16b)
12408   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12409   SDValue Zero = DAG.getConstant(0, VT);
12410   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12411                                Node->getOperand(0),
12412                                Node->getOperand(1), Zero, Zero,
12413                                cast<AtomicSDNode>(Node)->getMemOperand(),
12414                                cast<AtomicSDNode>(Node)->getOrdering(),
12415                                cast<AtomicSDNode>(Node)->getSynchScope());
12416   Results.push_back(Swap.getValue(0));
12417   Results.push_back(Swap.getValue(1));
12418 }
12419
12420 static void
12421 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12422                         SelectionDAG &DAG, unsigned NewOp) {
12423   DebugLoc dl = Node->getDebugLoc();
12424   assert (Node->getValueType(0) == MVT::i64 &&
12425           "Only know how to expand i64 atomics");
12426
12427   SDValue Chain = Node->getOperand(0);
12428   SDValue In1 = Node->getOperand(1);
12429   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12430                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12431   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12432                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12433   SDValue Ops[] = { Chain, In1, In2L, In2H };
12434   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12435   SDValue Result =
12436     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12437                             cast<MemSDNode>(Node)->getMemOperand());
12438   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12439   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12440   Results.push_back(Result.getValue(2));
12441 }
12442
12443 /// ReplaceNodeResults - Replace a node with an illegal result type
12444 /// with a new node built out of custom code.
12445 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12446                                            SmallVectorImpl<SDValue>&Results,
12447                                            SelectionDAG &DAG) const {
12448   DebugLoc dl = N->getDebugLoc();
12449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12450   switch (N->getOpcode()) {
12451   default:
12452     llvm_unreachable("Do not know how to custom type legalize this operation!");
12453   case ISD::SIGN_EXTEND_INREG:
12454   case ISD::ADDC:
12455   case ISD::ADDE:
12456   case ISD::SUBC:
12457   case ISD::SUBE:
12458     // We don't want to expand or promote these.
12459     return;
12460   case ISD::FP_TO_SINT:
12461   case ISD::FP_TO_UINT: {
12462     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12463
12464     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12465       return;
12466
12467     std::pair<SDValue,SDValue> Vals =
12468         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12469     SDValue FIST = Vals.first, StackSlot = Vals.second;
12470     if (FIST.getNode() != 0) {
12471       EVT VT = N->getValueType(0);
12472       // Return a load from the stack slot.
12473       if (StackSlot.getNode() != 0)
12474         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12475                                       MachinePointerInfo(),
12476                                       false, false, false, 0));
12477       else
12478         Results.push_back(FIST);
12479     }
12480     return;
12481   }
12482   case ISD::UINT_TO_FP: {
12483     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12484     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12485         N->getValueType(0) != MVT::v2f32)
12486       return;
12487     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12488                                  N->getOperand(0));
12489     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12490                                      MVT::f64);
12491     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12492     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12493                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12494     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12495     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12496     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12497     return;
12498   }
12499   case ISD::FP_ROUND: {
12500     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12501         return;
12502     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12503     Results.push_back(V);
12504     return;
12505   }
12506   case ISD::READCYCLECOUNTER: {
12507     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12508     SDValue TheChain = N->getOperand(0);
12509     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12510     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12511                                      rd.getValue(1));
12512     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12513                                      eax.getValue(2));
12514     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12515     SDValue Ops[] = { eax, edx };
12516     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12517     Results.push_back(edx.getValue(1));
12518     return;
12519   }
12520   case ISD::ATOMIC_CMP_SWAP: {
12521     EVT T = N->getValueType(0);
12522     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12523     bool Regs64bit = T == MVT::i128;
12524     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12525     SDValue cpInL, cpInH;
12526     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12527                         DAG.getConstant(0, HalfT));
12528     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12529                         DAG.getConstant(1, HalfT));
12530     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12531                              Regs64bit ? X86::RAX : X86::EAX,
12532                              cpInL, SDValue());
12533     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12534                              Regs64bit ? X86::RDX : X86::EDX,
12535                              cpInH, cpInL.getValue(1));
12536     SDValue swapInL, swapInH;
12537     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12538                           DAG.getConstant(0, HalfT));
12539     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12540                           DAG.getConstant(1, HalfT));
12541     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12542                                Regs64bit ? X86::RBX : X86::EBX,
12543                                swapInL, cpInH.getValue(1));
12544     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12545                                Regs64bit ? X86::RCX : X86::ECX,
12546                                swapInH, swapInL.getValue(1));
12547     SDValue Ops[] = { swapInH.getValue(0),
12548                       N->getOperand(1),
12549                       swapInH.getValue(1) };
12550     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12551     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12552     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12553                                   X86ISD::LCMPXCHG8_DAG;
12554     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12555                                              Ops, 3, T, MMO);
12556     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12557                                         Regs64bit ? X86::RAX : X86::EAX,
12558                                         HalfT, Result.getValue(1));
12559     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12560                                         Regs64bit ? X86::RDX : X86::EDX,
12561                                         HalfT, cpOutL.getValue(2));
12562     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12563     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12564     Results.push_back(cpOutH.getValue(1));
12565     return;
12566   }
12567   case ISD::ATOMIC_LOAD_ADD:
12568   case ISD::ATOMIC_LOAD_AND:
12569   case ISD::ATOMIC_LOAD_NAND:
12570   case ISD::ATOMIC_LOAD_OR:
12571   case ISD::ATOMIC_LOAD_SUB:
12572   case ISD::ATOMIC_LOAD_XOR:
12573   case ISD::ATOMIC_LOAD_MAX:
12574   case ISD::ATOMIC_LOAD_MIN:
12575   case ISD::ATOMIC_LOAD_UMAX:
12576   case ISD::ATOMIC_LOAD_UMIN:
12577   case ISD::ATOMIC_SWAP: {
12578     unsigned Opc;
12579     switch (N->getOpcode()) {
12580     default: llvm_unreachable("Unexpected opcode");
12581     case ISD::ATOMIC_LOAD_ADD:
12582       Opc = X86ISD::ATOMADD64_DAG;
12583       break;
12584     case ISD::ATOMIC_LOAD_AND:
12585       Opc = X86ISD::ATOMAND64_DAG;
12586       break;
12587     case ISD::ATOMIC_LOAD_NAND:
12588       Opc = X86ISD::ATOMNAND64_DAG;
12589       break;
12590     case ISD::ATOMIC_LOAD_OR:
12591       Opc = X86ISD::ATOMOR64_DAG;
12592       break;
12593     case ISD::ATOMIC_LOAD_SUB:
12594       Opc = X86ISD::ATOMSUB64_DAG;
12595       break;
12596     case ISD::ATOMIC_LOAD_XOR:
12597       Opc = X86ISD::ATOMXOR64_DAG;
12598       break;
12599     case ISD::ATOMIC_LOAD_MAX:
12600       Opc = X86ISD::ATOMMAX64_DAG;
12601       break;
12602     case ISD::ATOMIC_LOAD_MIN:
12603       Opc = X86ISD::ATOMMIN64_DAG;
12604       break;
12605     case ISD::ATOMIC_LOAD_UMAX:
12606       Opc = X86ISD::ATOMUMAX64_DAG;
12607       break;
12608     case ISD::ATOMIC_LOAD_UMIN:
12609       Opc = X86ISD::ATOMUMIN64_DAG;
12610       break;
12611     case ISD::ATOMIC_SWAP:
12612       Opc = X86ISD::ATOMSWAP64_DAG;
12613       break;
12614     }
12615     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12616     return;
12617   }
12618   case ISD::ATOMIC_LOAD:
12619     ReplaceATOMIC_LOAD(N, Results, DAG);
12620   }
12621 }
12622
12623 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12624   switch (Opcode) {
12625   default: return NULL;
12626   case X86ISD::BSF:                return "X86ISD::BSF";
12627   case X86ISD::BSR:                return "X86ISD::BSR";
12628   case X86ISD::SHLD:               return "X86ISD::SHLD";
12629   case X86ISD::SHRD:               return "X86ISD::SHRD";
12630   case X86ISD::FAND:               return "X86ISD::FAND";
12631   case X86ISD::FOR:                return "X86ISD::FOR";
12632   case X86ISD::FXOR:               return "X86ISD::FXOR";
12633   case X86ISD::FSRL:               return "X86ISD::FSRL";
12634   case X86ISD::FILD:               return "X86ISD::FILD";
12635   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12636   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12637   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12638   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12639   case X86ISD::FLD:                return "X86ISD::FLD";
12640   case X86ISD::FST:                return "X86ISD::FST";
12641   case X86ISD::CALL:               return "X86ISD::CALL";
12642   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12643   case X86ISD::BT:                 return "X86ISD::BT";
12644   case X86ISD::CMP:                return "X86ISD::CMP";
12645   case X86ISD::COMI:               return "X86ISD::COMI";
12646   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12647   case X86ISD::SETCC:              return "X86ISD::SETCC";
12648   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12649   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12650   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12651   case X86ISD::CMOV:               return "X86ISD::CMOV";
12652   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12653   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12654   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12655   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12656   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12657   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12658   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12659   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12660   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12661   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12662   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12663   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12664   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12665   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12666   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12667   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12668   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12669   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12670   case X86ISD::HADD:               return "X86ISD::HADD";
12671   case X86ISD::HSUB:               return "X86ISD::HSUB";
12672   case X86ISD::FHADD:              return "X86ISD::FHADD";
12673   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12674   case X86ISD::UMAX:               return "X86ISD::UMAX";
12675   case X86ISD::UMIN:               return "X86ISD::UMIN";
12676   case X86ISD::SMAX:               return "X86ISD::SMAX";
12677   case X86ISD::SMIN:               return "X86ISD::SMIN";
12678   case X86ISD::FMAX:               return "X86ISD::FMAX";
12679   case X86ISD::FMIN:               return "X86ISD::FMIN";
12680   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12681   case X86ISD::FMINC:              return "X86ISD::FMINC";
12682   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12683   case X86ISD::FRCP:               return "X86ISD::FRCP";
12684   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12685   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12686   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12687   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12688   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12689   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12690   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12691   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12692   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12693   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12694   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12695   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12696   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12697   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12698   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12699   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12700   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12701   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12702   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12703   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12704   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12705   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12706   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12707   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12708   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12709   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12710   case X86ISD::VSHL:               return "X86ISD::VSHL";
12711   case X86ISD::VSRL:               return "X86ISD::VSRL";
12712   case X86ISD::VSRA:               return "X86ISD::VSRA";
12713   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12714   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12715   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12716   case X86ISD::CMPP:               return "X86ISD::CMPP";
12717   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12718   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12719   case X86ISD::ADD:                return "X86ISD::ADD";
12720   case X86ISD::SUB:                return "X86ISD::SUB";
12721   case X86ISD::ADC:                return "X86ISD::ADC";
12722   case X86ISD::SBB:                return "X86ISD::SBB";
12723   case X86ISD::SMUL:               return "X86ISD::SMUL";
12724   case X86ISD::UMUL:               return "X86ISD::UMUL";
12725   case X86ISD::INC:                return "X86ISD::INC";
12726   case X86ISD::DEC:                return "X86ISD::DEC";
12727   case X86ISD::OR:                 return "X86ISD::OR";
12728   case X86ISD::XOR:                return "X86ISD::XOR";
12729   case X86ISD::AND:                return "X86ISD::AND";
12730   case X86ISD::BLSI:               return "X86ISD::BLSI";
12731   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12732   case X86ISD::BLSR:               return "X86ISD::BLSR";
12733   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12734   case X86ISD::PTEST:              return "X86ISD::PTEST";
12735   case X86ISD::TESTP:              return "X86ISD::TESTP";
12736   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12737   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12738   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12739   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12740   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12741   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12742   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12743   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12744   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12745   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12746   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12747   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12748   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12749   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12750   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12751   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12752   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12753   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12754   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12755   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12756   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12757   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12758   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12759   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12760   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12761   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12762   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12763   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12764   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12765   case X86ISD::SAHF:               return "X86ISD::SAHF";
12766   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12767   case X86ISD::FMADD:              return "X86ISD::FMADD";
12768   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12769   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12770   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12771   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12772   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12773   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12774   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12775   }
12776 }
12777
12778 // isLegalAddressingMode - Return true if the addressing mode represented
12779 // by AM is legal for this target, for a load/store of the specified type.
12780 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12781                                               Type *Ty) const {
12782   // X86 supports extremely general addressing modes.
12783   CodeModel::Model M = getTargetMachine().getCodeModel();
12784   Reloc::Model R = getTargetMachine().getRelocationModel();
12785
12786   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12787   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12788     return false;
12789
12790   if (AM.BaseGV) {
12791     unsigned GVFlags =
12792       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12793
12794     // If a reference to this global requires an extra load, we can't fold it.
12795     if (isGlobalStubReference(GVFlags))
12796       return false;
12797
12798     // If BaseGV requires a register for the PIC base, we cannot also have a
12799     // BaseReg specified.
12800     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12801       return false;
12802
12803     // If lower 4G is not available, then we must use rip-relative addressing.
12804     if ((M != CodeModel::Small || R != Reloc::Static) &&
12805         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12806       return false;
12807   }
12808
12809   switch (AM.Scale) {
12810   case 0:
12811   case 1:
12812   case 2:
12813   case 4:
12814   case 8:
12815     // These scales always work.
12816     break;
12817   case 3:
12818   case 5:
12819   case 9:
12820     // These scales are formed with basereg+scalereg.  Only accept if there is
12821     // no basereg yet.
12822     if (AM.HasBaseReg)
12823       return false;
12824     break;
12825   default:  // Other stuff never works.
12826     return false;
12827   }
12828
12829   return true;
12830 }
12831
12832 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12833   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12834     return false;
12835   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12836   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12837   return NumBits1 > NumBits2;
12838 }
12839
12840 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12841   return isInt<32>(Imm);
12842 }
12843
12844 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12845   // Can also use sub to handle negated immediates.
12846   return isInt<32>(Imm);
12847 }
12848
12849 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12850   if (!VT1.isInteger() || !VT2.isInteger())
12851     return false;
12852   unsigned NumBits1 = VT1.getSizeInBits();
12853   unsigned NumBits2 = VT2.getSizeInBits();
12854   return NumBits1 > NumBits2;
12855 }
12856
12857 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12858   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12859   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12860 }
12861
12862 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12863   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12864   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12865 }
12866
12867 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12868   EVT VT1 = Val.getValueType();
12869   if (isZExtFree(VT1, VT2))
12870     return true;
12871
12872   if (Val.getOpcode() != ISD::LOAD)
12873     return false;
12874
12875   if (!VT1.isSimple() || !VT1.isInteger() ||
12876       !VT2.isSimple() || !VT2.isInteger())
12877     return false;
12878
12879   switch (VT1.getSimpleVT().SimpleTy) {
12880   default: break;
12881   case MVT::i8:
12882   case MVT::i16:
12883   case MVT::i32:
12884     // X86 has 8, 16, and 32-bit zero-extending loads.
12885     return true;
12886   }
12887
12888   return false;
12889 }
12890
12891 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12892   // i16 instructions are longer (0x66 prefix) and potentially slower.
12893   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12894 }
12895
12896 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12897 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12898 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12899 /// are assumed to be legal.
12900 bool
12901 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12902                                       EVT VT) const {
12903   // Very little shuffling can be done for 64-bit vectors right now.
12904   if (VT.getSizeInBits() == 64)
12905     return false;
12906
12907   // FIXME: pshufb, blends, shifts.
12908   return (VT.getVectorNumElements() == 2 ||
12909           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12910           isMOVLMask(M, VT) ||
12911           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12912           isPSHUFDMask(M, VT) ||
12913           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12914           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12915           isPALIGNRMask(M, VT, Subtarget) ||
12916           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12917           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12918           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12919           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12920 }
12921
12922 bool
12923 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12924                                           EVT VT) const {
12925   unsigned NumElts = VT.getVectorNumElements();
12926   // FIXME: This collection of masks seems suspect.
12927   if (NumElts == 2)
12928     return true;
12929   if (NumElts == 4 && VT.is128BitVector()) {
12930     return (isMOVLMask(Mask, VT)  ||
12931             isCommutedMOVLMask(Mask, VT, true) ||
12932             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12933             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12934   }
12935   return false;
12936 }
12937
12938 //===----------------------------------------------------------------------===//
12939 //                           X86 Scheduler Hooks
12940 //===----------------------------------------------------------------------===//
12941
12942 /// Utility function to emit xbegin specifying the start of an RTM region.
12943 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12944                                      const TargetInstrInfo *TII) {
12945   DebugLoc DL = MI->getDebugLoc();
12946
12947   const BasicBlock *BB = MBB->getBasicBlock();
12948   MachineFunction::iterator I = MBB;
12949   ++I;
12950
12951   // For the v = xbegin(), we generate
12952   //
12953   // thisMBB:
12954   //  xbegin sinkMBB
12955   //
12956   // mainMBB:
12957   //  eax = -1
12958   //
12959   // sinkMBB:
12960   //  v = eax
12961
12962   MachineBasicBlock *thisMBB = MBB;
12963   MachineFunction *MF = MBB->getParent();
12964   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12965   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12966   MF->insert(I, mainMBB);
12967   MF->insert(I, sinkMBB);
12968
12969   // Transfer the remainder of BB and its successor edges to sinkMBB.
12970   sinkMBB->splice(sinkMBB->begin(), MBB,
12971                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12972   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12973
12974   // thisMBB:
12975   //  xbegin sinkMBB
12976   //  # fallthrough to mainMBB
12977   //  # abortion to sinkMBB
12978   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12979   thisMBB->addSuccessor(mainMBB);
12980   thisMBB->addSuccessor(sinkMBB);
12981
12982   // mainMBB:
12983   //  EAX = -1
12984   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12985   mainMBB->addSuccessor(sinkMBB);
12986
12987   // sinkMBB:
12988   // EAX is live into the sinkMBB
12989   sinkMBB->addLiveIn(X86::EAX);
12990   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12991           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12992     .addReg(X86::EAX);
12993
12994   MI->eraseFromParent();
12995   return sinkMBB;
12996 }
12997
12998 // Get CMPXCHG opcode for the specified data type.
12999 static unsigned getCmpXChgOpcode(EVT VT) {
13000   switch (VT.getSimpleVT().SimpleTy) {
13001   case MVT::i8:  return X86::LCMPXCHG8;
13002   case MVT::i16: return X86::LCMPXCHG16;
13003   case MVT::i32: return X86::LCMPXCHG32;
13004   case MVT::i64: return X86::LCMPXCHG64;
13005   default:
13006     break;
13007   }
13008   llvm_unreachable("Invalid operand size!");
13009 }
13010
13011 // Get LOAD opcode for the specified data type.
13012 static unsigned getLoadOpcode(EVT VT) {
13013   switch (VT.getSimpleVT().SimpleTy) {
13014   case MVT::i8:  return X86::MOV8rm;
13015   case MVT::i16: return X86::MOV16rm;
13016   case MVT::i32: return X86::MOV32rm;
13017   case MVT::i64: return X86::MOV64rm;
13018   default:
13019     break;
13020   }
13021   llvm_unreachable("Invalid operand size!");
13022 }
13023
13024 // Get opcode of the non-atomic one from the specified atomic instruction.
13025 static unsigned getNonAtomicOpcode(unsigned Opc) {
13026   switch (Opc) {
13027   case X86::ATOMAND8:  return X86::AND8rr;
13028   case X86::ATOMAND16: return X86::AND16rr;
13029   case X86::ATOMAND32: return X86::AND32rr;
13030   case X86::ATOMAND64: return X86::AND64rr;
13031   case X86::ATOMOR8:   return X86::OR8rr;
13032   case X86::ATOMOR16:  return X86::OR16rr;
13033   case X86::ATOMOR32:  return X86::OR32rr;
13034   case X86::ATOMOR64:  return X86::OR64rr;
13035   case X86::ATOMXOR8:  return X86::XOR8rr;
13036   case X86::ATOMXOR16: return X86::XOR16rr;
13037   case X86::ATOMXOR32: return X86::XOR32rr;
13038   case X86::ATOMXOR64: return X86::XOR64rr;
13039   }
13040   llvm_unreachable("Unhandled atomic-load-op opcode!");
13041 }
13042
13043 // Get opcode of the non-atomic one from the specified atomic instruction with
13044 // extra opcode.
13045 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13046                                                unsigned &ExtraOpc) {
13047   switch (Opc) {
13048   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13049   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13050   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13051   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13052   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13053   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13054   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13055   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13056   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13057   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13058   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13059   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13060   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13061   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13062   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13063   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13064   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13065   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13066   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13067   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13068   }
13069   llvm_unreachable("Unhandled atomic-load-op opcode!");
13070 }
13071
13072 // Get opcode of the non-atomic one from the specified atomic instruction for
13073 // 64-bit data type on 32-bit target.
13074 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13075   switch (Opc) {
13076   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13077   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13078   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13079   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13080   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13081   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13082   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13083   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13084   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13085   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13086   }
13087   llvm_unreachable("Unhandled atomic-load-op opcode!");
13088 }
13089
13090 // Get opcode of the non-atomic one from the specified atomic instruction for
13091 // 64-bit data type on 32-bit target with extra opcode.
13092 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13093                                                    unsigned &HiOpc,
13094                                                    unsigned &ExtraOpc) {
13095   switch (Opc) {
13096   case X86::ATOMNAND6432:
13097     ExtraOpc = X86::NOT32r;
13098     HiOpc = X86::AND32rr;
13099     return X86::AND32rr;
13100   }
13101   llvm_unreachable("Unhandled atomic-load-op opcode!");
13102 }
13103
13104 // Get pseudo CMOV opcode from the specified data type.
13105 static unsigned getPseudoCMOVOpc(EVT VT) {
13106   switch (VT.getSimpleVT().SimpleTy) {
13107   case MVT::i8:  return X86::CMOV_GR8;
13108   case MVT::i16: return X86::CMOV_GR16;
13109   case MVT::i32: return X86::CMOV_GR32;
13110   default:
13111     break;
13112   }
13113   llvm_unreachable("Unknown CMOV opcode!");
13114 }
13115
13116 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13117 // They will be translated into a spin-loop or compare-exchange loop from
13118 //
13119 //    ...
13120 //    dst = atomic-fetch-op MI.addr, MI.val
13121 //    ...
13122 //
13123 // to
13124 //
13125 //    ...
13126 //    t1 = LOAD MI.addr
13127 // loop:
13128 //    t4 = phi(t1, t3 / loop)
13129 //    t2 = OP MI.val, t4
13130 //    EAX = t4
13131 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13132 //    t3 = EAX
13133 //    JNE loop
13134 // sink:
13135 //    dst = t3
13136 //    ...
13137 MachineBasicBlock *
13138 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13139                                        MachineBasicBlock *MBB) const {
13140   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13141   DebugLoc DL = MI->getDebugLoc();
13142
13143   MachineFunction *MF = MBB->getParent();
13144   MachineRegisterInfo &MRI = MF->getRegInfo();
13145
13146   const BasicBlock *BB = MBB->getBasicBlock();
13147   MachineFunction::iterator I = MBB;
13148   ++I;
13149
13150   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13151          "Unexpected number of operands");
13152
13153   assert(MI->hasOneMemOperand() &&
13154          "Expected atomic-load-op to have one memoperand");
13155
13156   // Memory Reference
13157   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13158   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13159
13160   unsigned DstReg, SrcReg;
13161   unsigned MemOpndSlot;
13162
13163   unsigned CurOp = 0;
13164
13165   DstReg = MI->getOperand(CurOp++).getReg();
13166   MemOpndSlot = CurOp;
13167   CurOp += X86::AddrNumOperands;
13168   SrcReg = MI->getOperand(CurOp++).getReg();
13169
13170   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13171   MVT::SimpleValueType VT = *RC->vt_begin();
13172   unsigned t1 = MRI.createVirtualRegister(RC);
13173   unsigned t2 = MRI.createVirtualRegister(RC);
13174   unsigned t3 = MRI.createVirtualRegister(RC);
13175   unsigned t4 = MRI.createVirtualRegister(RC);
13176   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13177
13178   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13179   unsigned LOADOpc = getLoadOpcode(VT);
13180
13181   // For the atomic load-arith operator, we generate
13182   //
13183   //  thisMBB:
13184   //    t1 = LOAD [MI.addr]
13185   //  mainMBB:
13186   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13187   //    t1 = OP MI.val, EAX
13188   //    EAX = t4
13189   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13190   //    t3 = EAX
13191   //    JNE mainMBB
13192   //  sinkMBB:
13193   //    dst = t3
13194
13195   MachineBasicBlock *thisMBB = MBB;
13196   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13197   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13198   MF->insert(I, mainMBB);
13199   MF->insert(I, sinkMBB);
13200
13201   MachineInstrBuilder MIB;
13202
13203   // Transfer the remainder of BB and its successor edges to sinkMBB.
13204   sinkMBB->splice(sinkMBB->begin(), MBB,
13205                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13206   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13207
13208   // thisMBB:
13209   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13210   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13211     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13212     if (NewMO.isReg())
13213       NewMO.setIsKill(false);
13214     MIB.addOperand(NewMO);
13215   }
13216   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13217     unsigned flags = (*MMOI)->getFlags();
13218     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13219     MachineMemOperand *MMO =
13220       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13221                                (*MMOI)->getSize(),
13222                                (*MMOI)->getBaseAlignment(),
13223                                (*MMOI)->getTBAAInfo(),
13224                                (*MMOI)->getRanges());
13225     MIB.addMemOperand(MMO);
13226   }
13227
13228   thisMBB->addSuccessor(mainMBB);
13229
13230   // mainMBB:
13231   MachineBasicBlock *origMainMBB = mainMBB;
13232
13233   // Add a PHI.
13234   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13235                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13236
13237   unsigned Opc = MI->getOpcode();
13238   switch (Opc) {
13239   default:
13240     llvm_unreachable("Unhandled atomic-load-op opcode!");
13241   case X86::ATOMAND8:
13242   case X86::ATOMAND16:
13243   case X86::ATOMAND32:
13244   case X86::ATOMAND64:
13245   case X86::ATOMOR8:
13246   case X86::ATOMOR16:
13247   case X86::ATOMOR32:
13248   case X86::ATOMOR64:
13249   case X86::ATOMXOR8:
13250   case X86::ATOMXOR16:
13251   case X86::ATOMXOR32:
13252   case X86::ATOMXOR64: {
13253     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13254     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13255       .addReg(t4);
13256     break;
13257   }
13258   case X86::ATOMNAND8:
13259   case X86::ATOMNAND16:
13260   case X86::ATOMNAND32:
13261   case X86::ATOMNAND64: {
13262     unsigned Tmp = MRI.createVirtualRegister(RC);
13263     unsigned NOTOpc;
13264     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13265     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13266       .addReg(t4);
13267     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13268     break;
13269   }
13270   case X86::ATOMMAX8:
13271   case X86::ATOMMAX16:
13272   case X86::ATOMMAX32:
13273   case X86::ATOMMAX64:
13274   case X86::ATOMMIN8:
13275   case X86::ATOMMIN16:
13276   case X86::ATOMMIN32:
13277   case X86::ATOMMIN64:
13278   case X86::ATOMUMAX8:
13279   case X86::ATOMUMAX16:
13280   case X86::ATOMUMAX32:
13281   case X86::ATOMUMAX64:
13282   case X86::ATOMUMIN8:
13283   case X86::ATOMUMIN16:
13284   case X86::ATOMUMIN32:
13285   case X86::ATOMUMIN64: {
13286     unsigned CMPOpc;
13287     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13288
13289     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13290       .addReg(SrcReg)
13291       .addReg(t4);
13292
13293     if (Subtarget->hasCMov()) {
13294       if (VT != MVT::i8) {
13295         // Native support
13296         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13297           .addReg(SrcReg)
13298           .addReg(t4);
13299       } else {
13300         // Promote i8 to i32 to use CMOV32
13301         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13302         const TargetRegisterClass *RC32 =
13303           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13304         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13305         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13306         unsigned Tmp = MRI.createVirtualRegister(RC32);
13307
13308         unsigned Undef = MRI.createVirtualRegister(RC32);
13309         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13310
13311         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13312           .addReg(Undef)
13313           .addReg(SrcReg)
13314           .addImm(X86::sub_8bit);
13315         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13316           .addReg(Undef)
13317           .addReg(t4)
13318           .addImm(X86::sub_8bit);
13319
13320         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13321           .addReg(SrcReg32)
13322           .addReg(AccReg32);
13323
13324         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13325           .addReg(Tmp, 0, X86::sub_8bit);
13326       }
13327     } else {
13328       // Use pseudo select and lower them.
13329       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13330              "Invalid atomic-load-op transformation!");
13331       unsigned SelOpc = getPseudoCMOVOpc(VT);
13332       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13333       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13334       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13335               .addReg(SrcReg).addReg(t4)
13336               .addImm(CC);
13337       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13338       // Replace the original PHI node as mainMBB is changed after CMOV
13339       // lowering.
13340       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13341         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13342       Phi->eraseFromParent();
13343     }
13344     break;
13345   }
13346   }
13347
13348   // Copy PhyReg back from virtual register.
13349   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13350     .addReg(t4);
13351
13352   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13353   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13354     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13355     if (NewMO.isReg())
13356       NewMO.setIsKill(false);
13357     MIB.addOperand(NewMO);
13358   }
13359   MIB.addReg(t2);
13360   MIB.setMemRefs(MMOBegin, MMOEnd);
13361
13362   // Copy PhyReg back to virtual register.
13363   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13364     .addReg(PhyReg);
13365
13366   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13367
13368   mainMBB->addSuccessor(origMainMBB);
13369   mainMBB->addSuccessor(sinkMBB);
13370
13371   // sinkMBB:
13372   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13373           TII->get(TargetOpcode::COPY), DstReg)
13374     .addReg(t3);
13375
13376   MI->eraseFromParent();
13377   return sinkMBB;
13378 }
13379
13380 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13381 // instructions. They will be translated into a spin-loop or compare-exchange
13382 // loop from
13383 //
13384 //    ...
13385 //    dst = atomic-fetch-op MI.addr, MI.val
13386 //    ...
13387 //
13388 // to
13389 //
13390 //    ...
13391 //    t1L = LOAD [MI.addr + 0]
13392 //    t1H = LOAD [MI.addr + 4]
13393 // loop:
13394 //    t4L = phi(t1L, t3L / loop)
13395 //    t4H = phi(t1H, t3H / loop)
13396 //    t2L = OP MI.val.lo, t4L
13397 //    t2H = OP MI.val.hi, t4H
13398 //    EAX = t4L
13399 //    EDX = t4H
13400 //    EBX = t2L
13401 //    ECX = t2H
13402 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13403 //    t3L = EAX
13404 //    t3H = EDX
13405 //    JNE loop
13406 // sink:
13407 //    dstL = t3L
13408 //    dstH = t3H
13409 //    ...
13410 MachineBasicBlock *
13411 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13412                                            MachineBasicBlock *MBB) const {
13413   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13414   DebugLoc DL = MI->getDebugLoc();
13415
13416   MachineFunction *MF = MBB->getParent();
13417   MachineRegisterInfo &MRI = MF->getRegInfo();
13418
13419   const BasicBlock *BB = MBB->getBasicBlock();
13420   MachineFunction::iterator I = MBB;
13421   ++I;
13422
13423   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13424          "Unexpected number of operands");
13425
13426   assert(MI->hasOneMemOperand() &&
13427          "Expected atomic-load-op32 to have one memoperand");
13428
13429   // Memory Reference
13430   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13431   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13432
13433   unsigned DstLoReg, DstHiReg;
13434   unsigned SrcLoReg, SrcHiReg;
13435   unsigned MemOpndSlot;
13436
13437   unsigned CurOp = 0;
13438
13439   DstLoReg = MI->getOperand(CurOp++).getReg();
13440   DstHiReg = MI->getOperand(CurOp++).getReg();
13441   MemOpndSlot = CurOp;
13442   CurOp += X86::AddrNumOperands;
13443   SrcLoReg = MI->getOperand(CurOp++).getReg();
13444   SrcHiReg = MI->getOperand(CurOp++).getReg();
13445
13446   const TargetRegisterClass *RC = &X86::GR32RegClass;
13447   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13448
13449   unsigned t1L = MRI.createVirtualRegister(RC);
13450   unsigned t1H = MRI.createVirtualRegister(RC);
13451   unsigned t2L = MRI.createVirtualRegister(RC);
13452   unsigned t2H = MRI.createVirtualRegister(RC);
13453   unsigned t3L = MRI.createVirtualRegister(RC);
13454   unsigned t3H = MRI.createVirtualRegister(RC);
13455   unsigned t4L = MRI.createVirtualRegister(RC);
13456   unsigned t4H = MRI.createVirtualRegister(RC);
13457
13458   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13459   unsigned LOADOpc = X86::MOV32rm;
13460
13461   // For the atomic load-arith operator, we generate
13462   //
13463   //  thisMBB:
13464   //    t1L = LOAD [MI.addr + 0]
13465   //    t1H = LOAD [MI.addr + 4]
13466   //  mainMBB:
13467   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13468   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13469   //    t2L = OP MI.val.lo, t4L
13470   //    t2H = OP MI.val.hi, t4H
13471   //    EBX = t2L
13472   //    ECX = t2H
13473   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13474   //    t3L = EAX
13475   //    t3H = EDX
13476   //    JNE loop
13477   //  sinkMBB:
13478   //    dstL = t3L
13479   //    dstH = t3H
13480
13481   MachineBasicBlock *thisMBB = MBB;
13482   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13483   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13484   MF->insert(I, mainMBB);
13485   MF->insert(I, sinkMBB);
13486
13487   MachineInstrBuilder MIB;
13488
13489   // Transfer the remainder of BB and its successor edges to sinkMBB.
13490   sinkMBB->splice(sinkMBB->begin(), MBB,
13491                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13492   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13493
13494   // thisMBB:
13495   // Lo
13496   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13497   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13498     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13499     if (NewMO.isReg())
13500       NewMO.setIsKill(false);
13501     MIB.addOperand(NewMO);
13502   }
13503   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13504     unsigned flags = (*MMOI)->getFlags();
13505     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13506     MachineMemOperand *MMO =
13507       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13508                                (*MMOI)->getSize(),
13509                                (*MMOI)->getBaseAlignment(),
13510                                (*MMOI)->getTBAAInfo(),
13511                                (*MMOI)->getRanges());
13512     MIB.addMemOperand(MMO);
13513   };
13514   MachineInstr *LowMI = MIB;
13515
13516   // Hi
13517   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13518   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13519     if (i == X86::AddrDisp) {
13520       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13521     } else {
13522       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13523       if (NewMO.isReg())
13524         NewMO.setIsKill(false);
13525       MIB.addOperand(NewMO);
13526     }
13527   }
13528   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13529
13530   thisMBB->addSuccessor(mainMBB);
13531
13532   // mainMBB:
13533   MachineBasicBlock *origMainMBB = mainMBB;
13534
13535   // Add PHIs.
13536   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13537                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13538   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13539                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13540
13541   unsigned Opc = MI->getOpcode();
13542   switch (Opc) {
13543   default:
13544     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13545   case X86::ATOMAND6432:
13546   case X86::ATOMOR6432:
13547   case X86::ATOMXOR6432:
13548   case X86::ATOMADD6432:
13549   case X86::ATOMSUB6432: {
13550     unsigned HiOpc;
13551     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13552     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13553       .addReg(SrcLoReg);
13554     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13555       .addReg(SrcHiReg);
13556     break;
13557   }
13558   case X86::ATOMNAND6432: {
13559     unsigned HiOpc, NOTOpc;
13560     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13561     unsigned TmpL = MRI.createVirtualRegister(RC);
13562     unsigned TmpH = MRI.createVirtualRegister(RC);
13563     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13564       .addReg(t4L);
13565     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13566       .addReg(t4H);
13567     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13568     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13569     break;
13570   }
13571   case X86::ATOMMAX6432:
13572   case X86::ATOMMIN6432:
13573   case X86::ATOMUMAX6432:
13574   case X86::ATOMUMIN6432: {
13575     unsigned HiOpc;
13576     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13577     unsigned cL = MRI.createVirtualRegister(RC8);
13578     unsigned cH = MRI.createVirtualRegister(RC8);
13579     unsigned cL32 = MRI.createVirtualRegister(RC);
13580     unsigned cH32 = MRI.createVirtualRegister(RC);
13581     unsigned cc = MRI.createVirtualRegister(RC);
13582     // cl := cmp src_lo, lo
13583     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13584       .addReg(SrcLoReg).addReg(t4L);
13585     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13586     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13587     // ch := cmp src_hi, hi
13588     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13589       .addReg(SrcHiReg).addReg(t4H);
13590     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13591     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13592     // cc := if (src_hi == hi) ? cl : ch;
13593     if (Subtarget->hasCMov()) {
13594       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13595         .addReg(cH32).addReg(cL32);
13596     } else {
13597       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13598               .addReg(cH32).addReg(cL32)
13599               .addImm(X86::COND_E);
13600       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13601     }
13602     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13603     if (Subtarget->hasCMov()) {
13604       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13605         .addReg(SrcLoReg).addReg(t4L);
13606       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13607         .addReg(SrcHiReg).addReg(t4H);
13608     } else {
13609       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13610               .addReg(SrcLoReg).addReg(t4L)
13611               .addImm(X86::COND_NE);
13612       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13613       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13614       // 2nd CMOV lowering.
13615       mainMBB->addLiveIn(X86::EFLAGS);
13616       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13617               .addReg(SrcHiReg).addReg(t4H)
13618               .addImm(X86::COND_NE);
13619       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13620       // Replace the original PHI node as mainMBB is changed after CMOV
13621       // lowering.
13622       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13623         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13624       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13625         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13626       PhiL->eraseFromParent();
13627       PhiH->eraseFromParent();
13628     }
13629     break;
13630   }
13631   case X86::ATOMSWAP6432: {
13632     unsigned HiOpc;
13633     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13634     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13635     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13636     break;
13637   }
13638   }
13639
13640   // Copy EDX:EAX back from HiReg:LoReg
13641   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13642   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13643   // Copy ECX:EBX from t1H:t1L
13644   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13645   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13646
13647   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13648   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13649     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13650     if (NewMO.isReg())
13651       NewMO.setIsKill(false);
13652     MIB.addOperand(NewMO);
13653   }
13654   MIB.setMemRefs(MMOBegin, MMOEnd);
13655
13656   // Copy EDX:EAX back to t3H:t3L
13657   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13658   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13659
13660   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13661
13662   mainMBB->addSuccessor(origMainMBB);
13663   mainMBB->addSuccessor(sinkMBB);
13664
13665   // sinkMBB:
13666   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13667           TII->get(TargetOpcode::COPY), DstLoReg)
13668     .addReg(t3L);
13669   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13670           TII->get(TargetOpcode::COPY), DstHiReg)
13671     .addReg(t3H);
13672
13673   MI->eraseFromParent();
13674   return sinkMBB;
13675 }
13676
13677 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13678 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13679 // in the .td file.
13680 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13681                                        const TargetInstrInfo *TII) {
13682   unsigned Opc;
13683   switch (MI->getOpcode()) {
13684   default: llvm_unreachable("illegal opcode!");
13685   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13686   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13687   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13688   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13689   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13690   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13691   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13692   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13693   }
13694
13695   DebugLoc dl = MI->getDebugLoc();
13696   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13697
13698   unsigned NumArgs = MI->getNumOperands();
13699   for (unsigned i = 1; i < NumArgs; ++i) {
13700     MachineOperand &Op = MI->getOperand(i);
13701     if (!(Op.isReg() && Op.isImplicit()))
13702       MIB.addOperand(Op);
13703   }
13704   if (MI->hasOneMemOperand())
13705     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13706
13707   BuildMI(*BB, MI, dl,
13708     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13709     .addReg(X86::XMM0);
13710
13711   MI->eraseFromParent();
13712   return BB;
13713 }
13714
13715 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13716 // defs in an instruction pattern
13717 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13718                                        const TargetInstrInfo *TII) {
13719   unsigned Opc;
13720   switch (MI->getOpcode()) {
13721   default: llvm_unreachable("illegal opcode!");
13722   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13723   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13724   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13725   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13726   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13727   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13728   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13729   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13730   }
13731
13732   DebugLoc dl = MI->getDebugLoc();
13733   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13734
13735   unsigned NumArgs = MI->getNumOperands(); // remove the results
13736   for (unsigned i = 1; i < NumArgs; ++i) {
13737     MachineOperand &Op = MI->getOperand(i);
13738     if (!(Op.isReg() && Op.isImplicit()))
13739       MIB.addOperand(Op);
13740   }
13741   if (MI->hasOneMemOperand())
13742     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13743
13744   BuildMI(*BB, MI, dl,
13745     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13746     .addReg(X86::ECX);
13747
13748   MI->eraseFromParent();
13749   return BB;
13750 }
13751
13752 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13753                                        const TargetInstrInfo *TII,
13754                                        const X86Subtarget* Subtarget) {
13755   DebugLoc dl = MI->getDebugLoc();
13756
13757   // Address into RAX/EAX, other two args into ECX, EDX.
13758   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13759   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13760   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13761   for (int i = 0; i < X86::AddrNumOperands; ++i)
13762     MIB.addOperand(MI->getOperand(i));
13763
13764   unsigned ValOps = X86::AddrNumOperands;
13765   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13766     .addReg(MI->getOperand(ValOps).getReg());
13767   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13768     .addReg(MI->getOperand(ValOps+1).getReg());
13769
13770   // The instruction doesn't actually take any operands though.
13771   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13772
13773   MI->eraseFromParent(); // The pseudo is gone now.
13774   return BB;
13775 }
13776
13777 MachineBasicBlock *
13778 X86TargetLowering::EmitVAARG64WithCustomInserter(
13779                    MachineInstr *MI,
13780                    MachineBasicBlock *MBB) const {
13781   // Emit va_arg instruction on X86-64.
13782
13783   // Operands to this pseudo-instruction:
13784   // 0  ) Output        : destination address (reg)
13785   // 1-5) Input         : va_list address (addr, i64mem)
13786   // 6  ) ArgSize       : Size (in bytes) of vararg type
13787   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13788   // 8  ) Align         : Alignment of type
13789   // 9  ) EFLAGS (implicit-def)
13790
13791   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13792   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13793
13794   unsigned DestReg = MI->getOperand(0).getReg();
13795   MachineOperand &Base = MI->getOperand(1);
13796   MachineOperand &Scale = MI->getOperand(2);
13797   MachineOperand &Index = MI->getOperand(3);
13798   MachineOperand &Disp = MI->getOperand(4);
13799   MachineOperand &Segment = MI->getOperand(5);
13800   unsigned ArgSize = MI->getOperand(6).getImm();
13801   unsigned ArgMode = MI->getOperand(7).getImm();
13802   unsigned Align = MI->getOperand(8).getImm();
13803
13804   // Memory Reference
13805   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13806   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13807   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13808
13809   // Machine Information
13810   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13811   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13812   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13813   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13814   DebugLoc DL = MI->getDebugLoc();
13815
13816   // struct va_list {
13817   //   i32   gp_offset
13818   //   i32   fp_offset
13819   //   i64   overflow_area (address)
13820   //   i64   reg_save_area (address)
13821   // }
13822   // sizeof(va_list) = 24
13823   // alignment(va_list) = 8
13824
13825   unsigned TotalNumIntRegs = 6;
13826   unsigned TotalNumXMMRegs = 8;
13827   bool UseGPOffset = (ArgMode == 1);
13828   bool UseFPOffset = (ArgMode == 2);
13829   unsigned MaxOffset = TotalNumIntRegs * 8 +
13830                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13831
13832   /* Align ArgSize to a multiple of 8 */
13833   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13834   bool NeedsAlign = (Align > 8);
13835
13836   MachineBasicBlock *thisMBB = MBB;
13837   MachineBasicBlock *overflowMBB;
13838   MachineBasicBlock *offsetMBB;
13839   MachineBasicBlock *endMBB;
13840
13841   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13842   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13843   unsigned OffsetReg = 0;
13844
13845   if (!UseGPOffset && !UseFPOffset) {
13846     // If we only pull from the overflow region, we don't create a branch.
13847     // We don't need to alter control flow.
13848     OffsetDestReg = 0; // unused
13849     OverflowDestReg = DestReg;
13850
13851     offsetMBB = NULL;
13852     overflowMBB = thisMBB;
13853     endMBB = thisMBB;
13854   } else {
13855     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13856     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13857     // If not, pull from overflow_area. (branch to overflowMBB)
13858     //
13859     //       thisMBB
13860     //         |     .
13861     //         |        .
13862     //     offsetMBB   overflowMBB
13863     //         |        .
13864     //         |     .
13865     //        endMBB
13866
13867     // Registers for the PHI in endMBB
13868     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13869     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13870
13871     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13872     MachineFunction *MF = MBB->getParent();
13873     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13874     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13875     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13876
13877     MachineFunction::iterator MBBIter = MBB;
13878     ++MBBIter;
13879
13880     // Insert the new basic blocks
13881     MF->insert(MBBIter, offsetMBB);
13882     MF->insert(MBBIter, overflowMBB);
13883     MF->insert(MBBIter, endMBB);
13884
13885     // Transfer the remainder of MBB and its successor edges to endMBB.
13886     endMBB->splice(endMBB->begin(), thisMBB,
13887                     llvm::next(MachineBasicBlock::iterator(MI)),
13888                     thisMBB->end());
13889     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13890
13891     // Make offsetMBB and overflowMBB successors of thisMBB
13892     thisMBB->addSuccessor(offsetMBB);
13893     thisMBB->addSuccessor(overflowMBB);
13894
13895     // endMBB is a successor of both offsetMBB and overflowMBB
13896     offsetMBB->addSuccessor(endMBB);
13897     overflowMBB->addSuccessor(endMBB);
13898
13899     // Load the offset value into a register
13900     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13901     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13902       .addOperand(Base)
13903       .addOperand(Scale)
13904       .addOperand(Index)
13905       .addDisp(Disp, UseFPOffset ? 4 : 0)
13906       .addOperand(Segment)
13907       .setMemRefs(MMOBegin, MMOEnd);
13908
13909     // Check if there is enough room left to pull this argument.
13910     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13911       .addReg(OffsetReg)
13912       .addImm(MaxOffset + 8 - ArgSizeA8);
13913
13914     // Branch to "overflowMBB" if offset >= max
13915     // Fall through to "offsetMBB" otherwise
13916     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13917       .addMBB(overflowMBB);
13918   }
13919
13920   // In offsetMBB, emit code to use the reg_save_area.
13921   if (offsetMBB) {
13922     assert(OffsetReg != 0);
13923
13924     // Read the reg_save_area address.
13925     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13926     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13927       .addOperand(Base)
13928       .addOperand(Scale)
13929       .addOperand(Index)
13930       .addDisp(Disp, 16)
13931       .addOperand(Segment)
13932       .setMemRefs(MMOBegin, MMOEnd);
13933
13934     // Zero-extend the offset
13935     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13936       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13937         .addImm(0)
13938         .addReg(OffsetReg)
13939         .addImm(X86::sub_32bit);
13940
13941     // Add the offset to the reg_save_area to get the final address.
13942     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13943       .addReg(OffsetReg64)
13944       .addReg(RegSaveReg);
13945
13946     // Compute the offset for the next argument
13947     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13948     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13949       .addReg(OffsetReg)
13950       .addImm(UseFPOffset ? 16 : 8);
13951
13952     // Store it back into the va_list.
13953     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13954       .addOperand(Base)
13955       .addOperand(Scale)
13956       .addOperand(Index)
13957       .addDisp(Disp, UseFPOffset ? 4 : 0)
13958       .addOperand(Segment)
13959       .addReg(NextOffsetReg)
13960       .setMemRefs(MMOBegin, MMOEnd);
13961
13962     // Jump to endMBB
13963     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13964       .addMBB(endMBB);
13965   }
13966
13967   //
13968   // Emit code to use overflow area
13969   //
13970
13971   // Load the overflow_area address into a register.
13972   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13973   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13974     .addOperand(Base)
13975     .addOperand(Scale)
13976     .addOperand(Index)
13977     .addDisp(Disp, 8)
13978     .addOperand(Segment)
13979     .setMemRefs(MMOBegin, MMOEnd);
13980
13981   // If we need to align it, do so. Otherwise, just copy the address
13982   // to OverflowDestReg.
13983   if (NeedsAlign) {
13984     // Align the overflow address
13985     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13986     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13987
13988     // aligned_addr = (addr + (align-1)) & ~(align-1)
13989     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13990       .addReg(OverflowAddrReg)
13991       .addImm(Align-1);
13992
13993     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13994       .addReg(TmpReg)
13995       .addImm(~(uint64_t)(Align-1));
13996   } else {
13997     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13998       .addReg(OverflowAddrReg);
13999   }
14000
14001   // Compute the next overflow address after this argument.
14002   // (the overflow address should be kept 8-byte aligned)
14003   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14004   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14005     .addReg(OverflowDestReg)
14006     .addImm(ArgSizeA8);
14007
14008   // Store the new overflow address.
14009   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14010     .addOperand(Base)
14011     .addOperand(Scale)
14012     .addOperand(Index)
14013     .addDisp(Disp, 8)
14014     .addOperand(Segment)
14015     .addReg(NextAddrReg)
14016     .setMemRefs(MMOBegin, MMOEnd);
14017
14018   // If we branched, emit the PHI to the front of endMBB.
14019   if (offsetMBB) {
14020     BuildMI(*endMBB, endMBB->begin(), DL,
14021             TII->get(X86::PHI), DestReg)
14022       .addReg(OffsetDestReg).addMBB(offsetMBB)
14023       .addReg(OverflowDestReg).addMBB(overflowMBB);
14024   }
14025
14026   // Erase the pseudo instruction
14027   MI->eraseFromParent();
14028
14029   return endMBB;
14030 }
14031
14032 MachineBasicBlock *
14033 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14034                                                  MachineInstr *MI,
14035                                                  MachineBasicBlock *MBB) const {
14036   // Emit code to save XMM registers to the stack. The ABI says that the
14037   // number of registers to save is given in %al, so it's theoretically
14038   // possible to do an indirect jump trick to avoid saving all of them,
14039   // however this code takes a simpler approach and just executes all
14040   // of the stores if %al is non-zero. It's less code, and it's probably
14041   // easier on the hardware branch predictor, and stores aren't all that
14042   // expensive anyway.
14043
14044   // Create the new basic blocks. One block contains all the XMM stores,
14045   // and one block is the final destination regardless of whether any
14046   // stores were performed.
14047   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14048   MachineFunction *F = MBB->getParent();
14049   MachineFunction::iterator MBBIter = MBB;
14050   ++MBBIter;
14051   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14052   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14053   F->insert(MBBIter, XMMSaveMBB);
14054   F->insert(MBBIter, EndMBB);
14055
14056   // Transfer the remainder of MBB and its successor edges to EndMBB.
14057   EndMBB->splice(EndMBB->begin(), MBB,
14058                  llvm::next(MachineBasicBlock::iterator(MI)),
14059                  MBB->end());
14060   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14061
14062   // The original block will now fall through to the XMM save block.
14063   MBB->addSuccessor(XMMSaveMBB);
14064   // The XMMSaveMBB will fall through to the end block.
14065   XMMSaveMBB->addSuccessor(EndMBB);
14066
14067   // Now add the instructions.
14068   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14069   DebugLoc DL = MI->getDebugLoc();
14070
14071   unsigned CountReg = MI->getOperand(0).getReg();
14072   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14073   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14074
14075   if (!Subtarget->isTargetWin64()) {
14076     // If %al is 0, branch around the XMM save block.
14077     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14078     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14079     MBB->addSuccessor(EndMBB);
14080   }
14081
14082   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14083   // In the XMM save block, save all the XMM argument registers.
14084   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14085     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14086     MachineMemOperand *MMO =
14087       F->getMachineMemOperand(
14088           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14089         MachineMemOperand::MOStore,
14090         /*Size=*/16, /*Align=*/16);
14091     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14092       .addFrameIndex(RegSaveFrameIndex)
14093       .addImm(/*Scale=*/1)
14094       .addReg(/*IndexReg=*/0)
14095       .addImm(/*Disp=*/Offset)
14096       .addReg(/*Segment=*/0)
14097       .addReg(MI->getOperand(i).getReg())
14098       .addMemOperand(MMO);
14099   }
14100
14101   MI->eraseFromParent();   // The pseudo instruction is gone now.
14102
14103   return EndMBB;
14104 }
14105
14106 // The EFLAGS operand of SelectItr might be missing a kill marker
14107 // because there were multiple uses of EFLAGS, and ISel didn't know
14108 // which to mark. Figure out whether SelectItr should have had a
14109 // kill marker, and set it if it should. Returns the correct kill
14110 // marker value.
14111 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14112                                      MachineBasicBlock* BB,
14113                                      const TargetRegisterInfo* TRI) {
14114   // Scan forward through BB for a use/def of EFLAGS.
14115   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14116   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14117     const MachineInstr& mi = *miI;
14118     if (mi.readsRegister(X86::EFLAGS))
14119       return false;
14120     if (mi.definesRegister(X86::EFLAGS))
14121       break; // Should have kill-flag - update below.
14122   }
14123
14124   // If we hit the end of the block, check whether EFLAGS is live into a
14125   // successor.
14126   if (miI == BB->end()) {
14127     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14128                                           sEnd = BB->succ_end();
14129          sItr != sEnd; ++sItr) {
14130       MachineBasicBlock* succ = *sItr;
14131       if (succ->isLiveIn(X86::EFLAGS))
14132         return false;
14133     }
14134   }
14135
14136   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14137   // out. SelectMI should have a kill flag on EFLAGS.
14138   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14139   return true;
14140 }
14141
14142 MachineBasicBlock *
14143 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14144                                      MachineBasicBlock *BB) const {
14145   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14146   DebugLoc DL = MI->getDebugLoc();
14147
14148   // To "insert" a SELECT_CC instruction, we actually have to insert the
14149   // diamond control-flow pattern.  The incoming instruction knows the
14150   // destination vreg to set, the condition code register to branch on, the
14151   // true/false values to select between, and a branch opcode to use.
14152   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14153   MachineFunction::iterator It = BB;
14154   ++It;
14155
14156   //  thisMBB:
14157   //  ...
14158   //   TrueVal = ...
14159   //   cmpTY ccX, r1, r2
14160   //   bCC copy1MBB
14161   //   fallthrough --> copy0MBB
14162   MachineBasicBlock *thisMBB = BB;
14163   MachineFunction *F = BB->getParent();
14164   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14165   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14166   F->insert(It, copy0MBB);
14167   F->insert(It, sinkMBB);
14168
14169   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14170   // live into the sink and copy blocks.
14171   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14172   if (!MI->killsRegister(X86::EFLAGS) &&
14173       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14174     copy0MBB->addLiveIn(X86::EFLAGS);
14175     sinkMBB->addLiveIn(X86::EFLAGS);
14176   }
14177
14178   // Transfer the remainder of BB and its successor edges to sinkMBB.
14179   sinkMBB->splice(sinkMBB->begin(), BB,
14180                   llvm::next(MachineBasicBlock::iterator(MI)),
14181                   BB->end());
14182   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14183
14184   // Add the true and fallthrough blocks as its successors.
14185   BB->addSuccessor(copy0MBB);
14186   BB->addSuccessor(sinkMBB);
14187
14188   // Create the conditional branch instruction.
14189   unsigned Opc =
14190     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14191   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14192
14193   //  copy0MBB:
14194   //   %FalseValue = ...
14195   //   # fallthrough to sinkMBB
14196   copy0MBB->addSuccessor(sinkMBB);
14197
14198   //  sinkMBB:
14199   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14200   //  ...
14201   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14202           TII->get(X86::PHI), MI->getOperand(0).getReg())
14203     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14204     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14205
14206   MI->eraseFromParent();   // The pseudo instruction is gone now.
14207   return sinkMBB;
14208 }
14209
14210 MachineBasicBlock *
14211 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14212                                         bool Is64Bit) const {
14213   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14214   DebugLoc DL = MI->getDebugLoc();
14215   MachineFunction *MF = BB->getParent();
14216   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14217
14218   assert(getTargetMachine().Options.EnableSegmentedStacks);
14219
14220   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14221   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14222
14223   // BB:
14224   //  ... [Till the alloca]
14225   // If stacklet is not large enough, jump to mallocMBB
14226   //
14227   // bumpMBB:
14228   //  Allocate by subtracting from RSP
14229   //  Jump to continueMBB
14230   //
14231   // mallocMBB:
14232   //  Allocate by call to runtime
14233   //
14234   // continueMBB:
14235   //  ...
14236   //  [rest of original BB]
14237   //
14238
14239   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14240   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14241   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14242
14243   MachineRegisterInfo &MRI = MF->getRegInfo();
14244   const TargetRegisterClass *AddrRegClass =
14245     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14246
14247   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14248     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14249     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14250     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14251     sizeVReg = MI->getOperand(1).getReg(),
14252     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14253
14254   MachineFunction::iterator MBBIter = BB;
14255   ++MBBIter;
14256
14257   MF->insert(MBBIter, bumpMBB);
14258   MF->insert(MBBIter, mallocMBB);
14259   MF->insert(MBBIter, continueMBB);
14260
14261   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14262                       (MachineBasicBlock::iterator(MI)), BB->end());
14263   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14264
14265   // Add code to the main basic block to check if the stack limit has been hit,
14266   // and if so, jump to mallocMBB otherwise to bumpMBB.
14267   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14268   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14269     .addReg(tmpSPVReg).addReg(sizeVReg);
14270   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14271     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14272     .addReg(SPLimitVReg);
14273   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14274
14275   // bumpMBB simply decreases the stack pointer, since we know the current
14276   // stacklet has enough space.
14277   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14278     .addReg(SPLimitVReg);
14279   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14280     .addReg(SPLimitVReg);
14281   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14282
14283   // Calls into a routine in libgcc to allocate more space from the heap.
14284   const uint32_t *RegMask =
14285     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14286   if (Is64Bit) {
14287     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14288       .addReg(sizeVReg);
14289     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14290       .addExternalSymbol("__morestack_allocate_stack_space")
14291       .addRegMask(RegMask)
14292       .addReg(X86::RDI, RegState::Implicit)
14293       .addReg(X86::RAX, RegState::ImplicitDefine);
14294   } else {
14295     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14296       .addImm(12);
14297     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14298     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14299       .addExternalSymbol("__morestack_allocate_stack_space")
14300       .addRegMask(RegMask)
14301       .addReg(X86::EAX, RegState::ImplicitDefine);
14302   }
14303
14304   if (!Is64Bit)
14305     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14306       .addImm(16);
14307
14308   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14309     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14310   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14311
14312   // Set up the CFG correctly.
14313   BB->addSuccessor(bumpMBB);
14314   BB->addSuccessor(mallocMBB);
14315   mallocMBB->addSuccessor(continueMBB);
14316   bumpMBB->addSuccessor(continueMBB);
14317
14318   // Take care of the PHI nodes.
14319   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14320           MI->getOperand(0).getReg())
14321     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14322     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14323
14324   // Delete the original pseudo instruction.
14325   MI->eraseFromParent();
14326
14327   // And we're done.
14328   return continueMBB;
14329 }
14330
14331 MachineBasicBlock *
14332 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14333                                           MachineBasicBlock *BB) const {
14334   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14335   DebugLoc DL = MI->getDebugLoc();
14336
14337   assert(!Subtarget->isTargetEnvMacho());
14338
14339   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14340   // non-trivial part is impdef of ESP.
14341
14342   if (Subtarget->isTargetWin64()) {
14343     if (Subtarget->isTargetCygMing()) {
14344       // ___chkstk(Mingw64):
14345       // Clobbers R10, R11, RAX and EFLAGS.
14346       // Updates RSP.
14347       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14348         .addExternalSymbol("___chkstk")
14349         .addReg(X86::RAX, RegState::Implicit)
14350         .addReg(X86::RSP, RegState::Implicit)
14351         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14352         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14353         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14354     } else {
14355       // __chkstk(MSVCRT): does not update stack pointer.
14356       // Clobbers R10, R11 and EFLAGS.
14357       // FIXME: RAX(allocated size) might be reused and not killed.
14358       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14359         .addExternalSymbol("__chkstk")
14360         .addReg(X86::RAX, RegState::Implicit)
14361         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14362       // RAX has the offset to subtracted from RSP.
14363       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14364         .addReg(X86::RSP)
14365         .addReg(X86::RAX);
14366     }
14367   } else {
14368     const char *StackProbeSymbol =
14369       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14370
14371     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14372       .addExternalSymbol(StackProbeSymbol)
14373       .addReg(X86::EAX, RegState::Implicit)
14374       .addReg(X86::ESP, RegState::Implicit)
14375       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14376       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14377       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14378   }
14379
14380   MI->eraseFromParent();   // The pseudo instruction is gone now.
14381   return BB;
14382 }
14383
14384 MachineBasicBlock *
14385 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14386                                       MachineBasicBlock *BB) const {
14387   // This is pretty easy.  We're taking the value that we received from
14388   // our load from the relocation, sticking it in either RDI (x86-64)
14389   // or EAX and doing an indirect call.  The return value will then
14390   // be in the normal return register.
14391   const X86InstrInfo *TII
14392     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14393   DebugLoc DL = MI->getDebugLoc();
14394   MachineFunction *F = BB->getParent();
14395
14396   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14397   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14398
14399   // Get a register mask for the lowered call.
14400   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14401   // proper register mask.
14402   const uint32_t *RegMask =
14403     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14404   if (Subtarget->is64Bit()) {
14405     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14406                                       TII->get(X86::MOV64rm), X86::RDI)
14407     .addReg(X86::RIP)
14408     .addImm(0).addReg(0)
14409     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14410                       MI->getOperand(3).getTargetFlags())
14411     .addReg(0);
14412     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14413     addDirectMem(MIB, X86::RDI);
14414     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14415   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14416     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14417                                       TII->get(X86::MOV32rm), X86::EAX)
14418     .addReg(0)
14419     .addImm(0).addReg(0)
14420     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14421                       MI->getOperand(3).getTargetFlags())
14422     .addReg(0);
14423     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14424     addDirectMem(MIB, X86::EAX);
14425     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14426   } else {
14427     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14428                                       TII->get(X86::MOV32rm), X86::EAX)
14429     .addReg(TII->getGlobalBaseReg(F))
14430     .addImm(0).addReg(0)
14431     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14432                       MI->getOperand(3).getTargetFlags())
14433     .addReg(0);
14434     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14435     addDirectMem(MIB, X86::EAX);
14436     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14437   }
14438
14439   MI->eraseFromParent(); // The pseudo instruction is gone now.
14440   return BB;
14441 }
14442
14443 MachineBasicBlock *
14444 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14445                                     MachineBasicBlock *MBB) const {
14446   DebugLoc DL = MI->getDebugLoc();
14447   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14448
14449   MachineFunction *MF = MBB->getParent();
14450   MachineRegisterInfo &MRI = MF->getRegInfo();
14451
14452   const BasicBlock *BB = MBB->getBasicBlock();
14453   MachineFunction::iterator I = MBB;
14454   ++I;
14455
14456   // Memory Reference
14457   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14458   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14459
14460   unsigned DstReg;
14461   unsigned MemOpndSlot = 0;
14462
14463   unsigned CurOp = 0;
14464
14465   DstReg = MI->getOperand(CurOp++).getReg();
14466   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14467   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14468   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14469   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14470
14471   MemOpndSlot = CurOp;
14472
14473   MVT PVT = getPointerTy();
14474   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14475          "Invalid Pointer Size!");
14476
14477   // For v = setjmp(buf), we generate
14478   //
14479   // thisMBB:
14480   //  buf[LabelOffset] = restoreMBB
14481   //  SjLjSetup restoreMBB
14482   //
14483   // mainMBB:
14484   //  v_main = 0
14485   //
14486   // sinkMBB:
14487   //  v = phi(main, restore)
14488   //
14489   // restoreMBB:
14490   //  v_restore = 1
14491
14492   MachineBasicBlock *thisMBB = MBB;
14493   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14494   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14495   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14496   MF->insert(I, mainMBB);
14497   MF->insert(I, sinkMBB);
14498   MF->push_back(restoreMBB);
14499
14500   MachineInstrBuilder MIB;
14501
14502   // Transfer the remainder of BB and its successor edges to sinkMBB.
14503   sinkMBB->splice(sinkMBB->begin(), MBB,
14504                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14505   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14506
14507   // thisMBB:
14508   unsigned PtrStoreOpc = 0;
14509   unsigned LabelReg = 0;
14510   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14511   Reloc::Model RM = getTargetMachine().getRelocationModel();
14512   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14513                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14514
14515   // Prepare IP either in reg or imm.
14516   if (!UseImmLabel) {
14517     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14518     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14519     LabelReg = MRI.createVirtualRegister(PtrRC);
14520     if (Subtarget->is64Bit()) {
14521       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14522               .addReg(X86::RIP)
14523               .addImm(0)
14524               .addReg(0)
14525               .addMBB(restoreMBB)
14526               .addReg(0);
14527     } else {
14528       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14529       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14530               .addReg(XII->getGlobalBaseReg(MF))
14531               .addImm(0)
14532               .addReg(0)
14533               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14534               .addReg(0);
14535     }
14536   } else
14537     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14538   // Store IP
14539   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14540   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14541     if (i == X86::AddrDisp)
14542       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14543     else
14544       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14545   }
14546   if (!UseImmLabel)
14547     MIB.addReg(LabelReg);
14548   else
14549     MIB.addMBB(restoreMBB);
14550   MIB.setMemRefs(MMOBegin, MMOEnd);
14551   // Setup
14552   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14553           .addMBB(restoreMBB);
14554   MIB.addRegMask(RegInfo->getNoPreservedMask());
14555   thisMBB->addSuccessor(mainMBB);
14556   thisMBB->addSuccessor(restoreMBB);
14557
14558   // mainMBB:
14559   //  EAX = 0
14560   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14561   mainMBB->addSuccessor(sinkMBB);
14562
14563   // sinkMBB:
14564   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14565           TII->get(X86::PHI), DstReg)
14566     .addReg(mainDstReg).addMBB(mainMBB)
14567     .addReg(restoreDstReg).addMBB(restoreMBB);
14568
14569   // restoreMBB:
14570   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14571   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14572   restoreMBB->addSuccessor(sinkMBB);
14573
14574   MI->eraseFromParent();
14575   return sinkMBB;
14576 }
14577
14578 MachineBasicBlock *
14579 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14580                                      MachineBasicBlock *MBB) const {
14581   DebugLoc DL = MI->getDebugLoc();
14582   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14583
14584   MachineFunction *MF = MBB->getParent();
14585   MachineRegisterInfo &MRI = MF->getRegInfo();
14586
14587   // Memory Reference
14588   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14589   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14590
14591   MVT PVT = getPointerTy();
14592   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14593          "Invalid Pointer Size!");
14594
14595   const TargetRegisterClass *RC =
14596     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14597   unsigned Tmp = MRI.createVirtualRegister(RC);
14598   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14599   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14600   unsigned SP = RegInfo->getStackRegister();
14601
14602   MachineInstrBuilder MIB;
14603
14604   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14605   const int64_t SPOffset = 2 * PVT.getStoreSize();
14606
14607   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14608   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14609
14610   // Reload FP
14611   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14612   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14613     MIB.addOperand(MI->getOperand(i));
14614   MIB.setMemRefs(MMOBegin, MMOEnd);
14615   // Reload IP
14616   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14617   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14618     if (i == X86::AddrDisp)
14619       MIB.addDisp(MI->getOperand(i), LabelOffset);
14620     else
14621       MIB.addOperand(MI->getOperand(i));
14622   }
14623   MIB.setMemRefs(MMOBegin, MMOEnd);
14624   // Reload SP
14625   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14626   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14627     if (i == X86::AddrDisp)
14628       MIB.addDisp(MI->getOperand(i), SPOffset);
14629     else
14630       MIB.addOperand(MI->getOperand(i));
14631   }
14632   MIB.setMemRefs(MMOBegin, MMOEnd);
14633   // Jump
14634   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14635
14636   MI->eraseFromParent();
14637   return MBB;
14638 }
14639
14640 MachineBasicBlock *
14641 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14642                                                MachineBasicBlock *BB) const {
14643   switch (MI->getOpcode()) {
14644   default: llvm_unreachable("Unexpected instr type to insert");
14645   case X86::TAILJMPd64:
14646   case X86::TAILJMPr64:
14647   case X86::TAILJMPm64:
14648     llvm_unreachable("TAILJMP64 would not be touched here.");
14649   case X86::TCRETURNdi64:
14650   case X86::TCRETURNri64:
14651   case X86::TCRETURNmi64:
14652     return BB;
14653   case X86::WIN_ALLOCA:
14654     return EmitLoweredWinAlloca(MI, BB);
14655   case X86::SEG_ALLOCA_32:
14656     return EmitLoweredSegAlloca(MI, BB, false);
14657   case X86::SEG_ALLOCA_64:
14658     return EmitLoweredSegAlloca(MI, BB, true);
14659   case X86::TLSCall_32:
14660   case X86::TLSCall_64:
14661     return EmitLoweredTLSCall(MI, BB);
14662   case X86::CMOV_GR8:
14663   case X86::CMOV_FR32:
14664   case X86::CMOV_FR64:
14665   case X86::CMOV_V4F32:
14666   case X86::CMOV_V2F64:
14667   case X86::CMOV_V2I64:
14668   case X86::CMOV_V8F32:
14669   case X86::CMOV_V4F64:
14670   case X86::CMOV_V4I64:
14671   case X86::CMOV_GR16:
14672   case X86::CMOV_GR32:
14673   case X86::CMOV_RFP32:
14674   case X86::CMOV_RFP64:
14675   case X86::CMOV_RFP80:
14676     return EmitLoweredSelect(MI, BB);
14677
14678   case X86::FP32_TO_INT16_IN_MEM:
14679   case X86::FP32_TO_INT32_IN_MEM:
14680   case X86::FP32_TO_INT64_IN_MEM:
14681   case X86::FP64_TO_INT16_IN_MEM:
14682   case X86::FP64_TO_INT32_IN_MEM:
14683   case X86::FP64_TO_INT64_IN_MEM:
14684   case X86::FP80_TO_INT16_IN_MEM:
14685   case X86::FP80_TO_INT32_IN_MEM:
14686   case X86::FP80_TO_INT64_IN_MEM: {
14687     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14688     DebugLoc DL = MI->getDebugLoc();
14689
14690     // Change the floating point control register to use "round towards zero"
14691     // mode when truncating to an integer value.
14692     MachineFunction *F = BB->getParent();
14693     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14694     addFrameReference(BuildMI(*BB, MI, DL,
14695                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14696
14697     // Load the old value of the high byte of the control word...
14698     unsigned OldCW =
14699       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14700     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14701                       CWFrameIdx);
14702
14703     // Set the high part to be round to zero...
14704     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14705       .addImm(0xC7F);
14706
14707     // Reload the modified control word now...
14708     addFrameReference(BuildMI(*BB, MI, DL,
14709                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14710
14711     // Restore the memory image of control word to original value
14712     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14713       .addReg(OldCW);
14714
14715     // Get the X86 opcode to use.
14716     unsigned Opc;
14717     switch (MI->getOpcode()) {
14718     default: llvm_unreachable("illegal opcode!");
14719     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14720     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14721     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14722     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14723     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14724     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14725     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14726     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14727     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14728     }
14729
14730     X86AddressMode AM;
14731     MachineOperand &Op = MI->getOperand(0);
14732     if (Op.isReg()) {
14733       AM.BaseType = X86AddressMode::RegBase;
14734       AM.Base.Reg = Op.getReg();
14735     } else {
14736       AM.BaseType = X86AddressMode::FrameIndexBase;
14737       AM.Base.FrameIndex = Op.getIndex();
14738     }
14739     Op = MI->getOperand(1);
14740     if (Op.isImm())
14741       AM.Scale = Op.getImm();
14742     Op = MI->getOperand(2);
14743     if (Op.isImm())
14744       AM.IndexReg = Op.getImm();
14745     Op = MI->getOperand(3);
14746     if (Op.isGlobal()) {
14747       AM.GV = Op.getGlobal();
14748     } else {
14749       AM.Disp = Op.getImm();
14750     }
14751     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14752                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14753
14754     // Reload the original control word now.
14755     addFrameReference(BuildMI(*BB, MI, DL,
14756                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14757
14758     MI->eraseFromParent();   // The pseudo instruction is gone now.
14759     return BB;
14760   }
14761     // String/text processing lowering.
14762   case X86::PCMPISTRM128REG:
14763   case X86::VPCMPISTRM128REG:
14764   case X86::PCMPISTRM128MEM:
14765   case X86::VPCMPISTRM128MEM:
14766   case X86::PCMPESTRM128REG:
14767   case X86::VPCMPESTRM128REG:
14768   case X86::PCMPESTRM128MEM:
14769   case X86::VPCMPESTRM128MEM:
14770     assert(Subtarget->hasSSE42() &&
14771            "Target must have SSE4.2 or AVX features enabled");
14772     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14773
14774   // String/text processing lowering.
14775   case X86::PCMPISTRIREG:
14776   case X86::VPCMPISTRIREG:
14777   case X86::PCMPISTRIMEM:
14778   case X86::VPCMPISTRIMEM:
14779   case X86::PCMPESTRIREG:
14780   case X86::VPCMPESTRIREG:
14781   case X86::PCMPESTRIMEM:
14782   case X86::VPCMPESTRIMEM:
14783     assert(Subtarget->hasSSE42() &&
14784            "Target must have SSE4.2 or AVX features enabled");
14785     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14786
14787   // Thread synchronization.
14788   case X86::MONITOR:
14789     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14790
14791   // xbegin
14792   case X86::XBEGIN:
14793     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14794
14795   // Atomic Lowering.
14796   case X86::ATOMAND8:
14797   case X86::ATOMAND16:
14798   case X86::ATOMAND32:
14799   case X86::ATOMAND64:
14800     // Fall through
14801   case X86::ATOMOR8:
14802   case X86::ATOMOR16:
14803   case X86::ATOMOR32:
14804   case X86::ATOMOR64:
14805     // Fall through
14806   case X86::ATOMXOR16:
14807   case X86::ATOMXOR8:
14808   case X86::ATOMXOR32:
14809   case X86::ATOMXOR64:
14810     // Fall through
14811   case X86::ATOMNAND8:
14812   case X86::ATOMNAND16:
14813   case X86::ATOMNAND32:
14814   case X86::ATOMNAND64:
14815     // Fall through
14816   case X86::ATOMMAX8:
14817   case X86::ATOMMAX16:
14818   case X86::ATOMMAX32:
14819   case X86::ATOMMAX64:
14820     // Fall through
14821   case X86::ATOMMIN8:
14822   case X86::ATOMMIN16:
14823   case X86::ATOMMIN32:
14824   case X86::ATOMMIN64:
14825     // Fall through
14826   case X86::ATOMUMAX8:
14827   case X86::ATOMUMAX16:
14828   case X86::ATOMUMAX32:
14829   case X86::ATOMUMAX64:
14830     // Fall through
14831   case X86::ATOMUMIN8:
14832   case X86::ATOMUMIN16:
14833   case X86::ATOMUMIN32:
14834   case X86::ATOMUMIN64:
14835     return EmitAtomicLoadArith(MI, BB);
14836
14837   // This group does 64-bit operations on a 32-bit host.
14838   case X86::ATOMAND6432:
14839   case X86::ATOMOR6432:
14840   case X86::ATOMXOR6432:
14841   case X86::ATOMNAND6432:
14842   case X86::ATOMADD6432:
14843   case X86::ATOMSUB6432:
14844   case X86::ATOMMAX6432:
14845   case X86::ATOMMIN6432:
14846   case X86::ATOMUMAX6432:
14847   case X86::ATOMUMIN6432:
14848   case X86::ATOMSWAP6432:
14849     return EmitAtomicLoadArith6432(MI, BB);
14850
14851   case X86::VASTART_SAVE_XMM_REGS:
14852     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14853
14854   case X86::VAARG_64:
14855     return EmitVAARG64WithCustomInserter(MI, BB);
14856
14857   case X86::EH_SjLj_SetJmp32:
14858   case X86::EH_SjLj_SetJmp64:
14859     return emitEHSjLjSetJmp(MI, BB);
14860
14861   case X86::EH_SjLj_LongJmp32:
14862   case X86::EH_SjLj_LongJmp64:
14863     return emitEHSjLjLongJmp(MI, BB);
14864   }
14865 }
14866
14867 //===----------------------------------------------------------------------===//
14868 //                           X86 Optimization Hooks
14869 //===----------------------------------------------------------------------===//
14870
14871 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14872                                                        APInt &KnownZero,
14873                                                        APInt &KnownOne,
14874                                                        const SelectionDAG &DAG,
14875                                                        unsigned Depth) const {
14876   unsigned BitWidth = KnownZero.getBitWidth();
14877   unsigned Opc = Op.getOpcode();
14878   assert((Opc >= ISD::BUILTIN_OP_END ||
14879           Opc == ISD::INTRINSIC_WO_CHAIN ||
14880           Opc == ISD::INTRINSIC_W_CHAIN ||
14881           Opc == ISD::INTRINSIC_VOID) &&
14882          "Should use MaskedValueIsZero if you don't know whether Op"
14883          " is a target node!");
14884
14885   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14886   switch (Opc) {
14887   default: break;
14888   case X86ISD::ADD:
14889   case X86ISD::SUB:
14890   case X86ISD::ADC:
14891   case X86ISD::SBB:
14892   case X86ISD::SMUL:
14893   case X86ISD::UMUL:
14894   case X86ISD::INC:
14895   case X86ISD::DEC:
14896   case X86ISD::OR:
14897   case X86ISD::XOR:
14898   case X86ISD::AND:
14899     // These nodes' second result is a boolean.
14900     if (Op.getResNo() == 0)
14901       break;
14902     // Fallthrough
14903   case X86ISD::SETCC:
14904     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14905     break;
14906   case ISD::INTRINSIC_WO_CHAIN: {
14907     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14908     unsigned NumLoBits = 0;
14909     switch (IntId) {
14910     default: break;
14911     case Intrinsic::x86_sse_movmsk_ps:
14912     case Intrinsic::x86_avx_movmsk_ps_256:
14913     case Intrinsic::x86_sse2_movmsk_pd:
14914     case Intrinsic::x86_avx_movmsk_pd_256:
14915     case Intrinsic::x86_mmx_pmovmskb:
14916     case Intrinsic::x86_sse2_pmovmskb_128:
14917     case Intrinsic::x86_avx2_pmovmskb: {
14918       // High bits of movmskp{s|d}, pmovmskb are known zero.
14919       switch (IntId) {
14920         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14921         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14922         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14923         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14924         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14925         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14926         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14927         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14928       }
14929       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14930       break;
14931     }
14932     }
14933     break;
14934   }
14935   }
14936 }
14937
14938 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14939                                                          unsigned Depth) const {
14940   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14941   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14942     return Op.getValueType().getScalarType().getSizeInBits();
14943
14944   // Fallback case.
14945   return 1;
14946 }
14947
14948 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14949 /// node is a GlobalAddress + offset.
14950 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14951                                        const GlobalValue* &GA,
14952                                        int64_t &Offset) const {
14953   if (N->getOpcode() == X86ISD::Wrapper) {
14954     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14955       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14956       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14957       return true;
14958     }
14959   }
14960   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14961 }
14962
14963 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14964 /// same as extracting the high 128-bit part of 256-bit vector and then
14965 /// inserting the result into the low part of a new 256-bit vector
14966 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14967   EVT VT = SVOp->getValueType(0);
14968   unsigned NumElems = VT.getVectorNumElements();
14969
14970   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14971   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14972     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14973         SVOp->getMaskElt(j) >= 0)
14974       return false;
14975
14976   return true;
14977 }
14978
14979 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14980 /// same as extracting the low 128-bit part of 256-bit vector and then
14981 /// inserting the result into the high part of a new 256-bit vector
14982 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14983   EVT VT = SVOp->getValueType(0);
14984   unsigned NumElems = VT.getVectorNumElements();
14985
14986   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14987   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14988     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14989         SVOp->getMaskElt(j) >= 0)
14990       return false;
14991
14992   return true;
14993 }
14994
14995 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14996 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14997                                         TargetLowering::DAGCombinerInfo &DCI,
14998                                         const X86Subtarget* Subtarget) {
14999   DebugLoc dl = N->getDebugLoc();
15000   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15001   SDValue V1 = SVOp->getOperand(0);
15002   SDValue V2 = SVOp->getOperand(1);
15003   EVT VT = SVOp->getValueType(0);
15004   unsigned NumElems = VT.getVectorNumElements();
15005
15006   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15007       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15008     //
15009     //                   0,0,0,...
15010     //                      |
15011     //    V      UNDEF    BUILD_VECTOR    UNDEF
15012     //     \      /           \           /
15013     //  CONCAT_VECTOR         CONCAT_VECTOR
15014     //         \                  /
15015     //          \                /
15016     //          RESULT: V + zero extended
15017     //
15018     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15019         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15020         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15021       return SDValue();
15022
15023     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15024       return SDValue();
15025
15026     // To match the shuffle mask, the first half of the mask should
15027     // be exactly the first vector, and all the rest a splat with the
15028     // first element of the second one.
15029     for (unsigned i = 0; i != NumElems/2; ++i)
15030       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15031           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15032         return SDValue();
15033
15034     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15035     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15036       if (Ld->hasNUsesOfValue(1, 0)) {
15037         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15038         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15039         SDValue ResNode =
15040           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
15041                                   Ld->getMemoryVT(),
15042                                   Ld->getPointerInfo(),
15043                                   Ld->getAlignment(),
15044                                   false/*isVolatile*/, true/*ReadMem*/,
15045                                   false/*WriteMem*/);
15046
15047         // Make sure the newly-created LOAD is in the same position as Ld in
15048         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15049         // and update uses of Ld's output chain to use the TokenFactor.
15050         if (Ld->hasAnyUseOfValue(1)) {
15051           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15052                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15053           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15054           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15055                                  SDValue(ResNode.getNode(), 1));
15056         }
15057
15058         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15059       }
15060     }
15061
15062     // Emit a zeroed vector and insert the desired subvector on its
15063     // first half.
15064     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15065     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15066     return DCI.CombineTo(N, InsV);
15067   }
15068
15069   //===--------------------------------------------------------------------===//
15070   // Combine some shuffles into subvector extracts and inserts:
15071   //
15072
15073   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15074   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15075     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15076     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15077     return DCI.CombineTo(N, InsV);
15078   }
15079
15080   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15081   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15082     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15083     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15084     return DCI.CombineTo(N, InsV);
15085   }
15086
15087   return SDValue();
15088 }
15089
15090 /// PerformShuffleCombine - Performs several different shuffle combines.
15091 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15092                                      TargetLowering::DAGCombinerInfo &DCI,
15093                                      const X86Subtarget *Subtarget) {
15094   DebugLoc dl = N->getDebugLoc();
15095   EVT VT = N->getValueType(0);
15096
15097   // Don't create instructions with illegal types after legalize types has run.
15098   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15099   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15100     return SDValue();
15101
15102   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15103   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15104       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15105     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15106
15107   // Only handle 128 wide vector from here on.
15108   if (!VT.is128BitVector())
15109     return SDValue();
15110
15111   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15112   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15113   // consecutive, non-overlapping, and in the right order.
15114   SmallVector<SDValue, 16> Elts;
15115   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15116     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15117
15118   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15119 }
15120
15121 /// PerformTruncateCombine - Converts truncate operation to
15122 /// a sequence of vector shuffle operations.
15123 /// It is possible when we truncate 256-bit vector to 128-bit vector
15124 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15125                                       TargetLowering::DAGCombinerInfo &DCI,
15126                                       const X86Subtarget *Subtarget)  {
15127   return SDValue();
15128 }
15129
15130 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15131 /// specific shuffle of a load can be folded into a single element load.
15132 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15133 /// shuffles have been customed lowered so we need to handle those here.
15134 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15135                                          TargetLowering::DAGCombinerInfo &DCI) {
15136   if (DCI.isBeforeLegalizeOps())
15137     return SDValue();
15138
15139   SDValue InVec = N->getOperand(0);
15140   SDValue EltNo = N->getOperand(1);
15141
15142   if (!isa<ConstantSDNode>(EltNo))
15143     return SDValue();
15144
15145   EVT VT = InVec.getValueType();
15146
15147   bool HasShuffleIntoBitcast = false;
15148   if (InVec.getOpcode() == ISD::BITCAST) {
15149     // Don't duplicate a load with other uses.
15150     if (!InVec.hasOneUse())
15151       return SDValue();
15152     EVT BCVT = InVec.getOperand(0).getValueType();
15153     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15154       return SDValue();
15155     InVec = InVec.getOperand(0);
15156     HasShuffleIntoBitcast = true;
15157   }
15158
15159   if (!isTargetShuffle(InVec.getOpcode()))
15160     return SDValue();
15161
15162   // Don't duplicate a load with other uses.
15163   if (!InVec.hasOneUse())
15164     return SDValue();
15165
15166   SmallVector<int, 16> ShuffleMask;
15167   bool UnaryShuffle;
15168   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15169                             UnaryShuffle))
15170     return SDValue();
15171
15172   // Select the input vector, guarding against out of range extract vector.
15173   unsigned NumElems = VT.getVectorNumElements();
15174   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15175   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15176   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15177                                          : InVec.getOperand(1);
15178
15179   // If inputs to shuffle are the same for both ops, then allow 2 uses
15180   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15181
15182   if (LdNode.getOpcode() == ISD::BITCAST) {
15183     // Don't duplicate a load with other uses.
15184     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15185       return SDValue();
15186
15187     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15188     LdNode = LdNode.getOperand(0);
15189   }
15190
15191   if (!ISD::isNormalLoad(LdNode.getNode()))
15192     return SDValue();
15193
15194   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15195
15196   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15197     return SDValue();
15198
15199   if (HasShuffleIntoBitcast) {
15200     // If there's a bitcast before the shuffle, check if the load type and
15201     // alignment is valid.
15202     unsigned Align = LN0->getAlignment();
15203     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15204     unsigned NewAlign = TLI.getDataLayout()->
15205       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15206
15207     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15208       return SDValue();
15209   }
15210
15211   // All checks match so transform back to vector_shuffle so that DAG combiner
15212   // can finish the job
15213   DebugLoc dl = N->getDebugLoc();
15214
15215   // Create shuffle node taking into account the case that its a unary shuffle
15216   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15217   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15218                                  InVec.getOperand(0), Shuffle,
15219                                  &ShuffleMask[0]);
15220   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15221   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15222                      EltNo);
15223 }
15224
15225 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15226 /// generation and convert it from being a bunch of shuffles and extracts
15227 /// to a simple store and scalar loads to extract the elements.
15228 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15229                                          TargetLowering::DAGCombinerInfo &DCI) {
15230   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15231   if (NewOp.getNode())
15232     return NewOp;
15233
15234   SDValue InputVector = N->getOperand(0);
15235   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15236   // from mmx to v2i32 has a single usage.
15237   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15238       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15239       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15240     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15241                        N->getValueType(0),
15242                        InputVector.getNode()->getOperand(0));
15243
15244   // Only operate on vectors of 4 elements, where the alternative shuffling
15245   // gets to be more expensive.
15246   if (InputVector.getValueType() != MVT::v4i32)
15247     return SDValue();
15248
15249   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15250   // single use which is a sign-extend or zero-extend, and all elements are
15251   // used.
15252   SmallVector<SDNode *, 4> Uses;
15253   unsigned ExtractedElements = 0;
15254   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15255        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15256     if (UI.getUse().getResNo() != InputVector.getResNo())
15257       return SDValue();
15258
15259     SDNode *Extract = *UI;
15260     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15261       return SDValue();
15262
15263     if (Extract->getValueType(0) != MVT::i32)
15264       return SDValue();
15265     if (!Extract->hasOneUse())
15266       return SDValue();
15267     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15268         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15269       return SDValue();
15270     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15271       return SDValue();
15272
15273     // Record which element was extracted.
15274     ExtractedElements |=
15275       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15276
15277     Uses.push_back(Extract);
15278   }
15279
15280   // If not all the elements were used, this may not be worthwhile.
15281   if (ExtractedElements != 15)
15282     return SDValue();
15283
15284   // Ok, we've now decided to do the transformation.
15285   DebugLoc dl = InputVector.getDebugLoc();
15286
15287   // Store the value to a temporary stack slot.
15288   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15289   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15290                             MachinePointerInfo(), false, false, 0);
15291
15292   // Replace each use (extract) with a load of the appropriate element.
15293   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15294        UE = Uses.end(); UI != UE; ++UI) {
15295     SDNode *Extract = *UI;
15296
15297     // cOMpute the element's address.
15298     SDValue Idx = Extract->getOperand(1);
15299     unsigned EltSize =
15300         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15301     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15302     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15303     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15304
15305     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15306                                      StackPtr, OffsetVal);
15307
15308     // Load the scalar.
15309     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15310                                      ScalarAddr, MachinePointerInfo(),
15311                                      false, false, false, 0);
15312
15313     // Replace the exact with the load.
15314     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15315   }
15316
15317   // The replacement was made in place; don't return anything.
15318   return SDValue();
15319 }
15320
15321 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15322 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15323                                    SDValue RHS, SelectionDAG &DAG,
15324                                    const X86Subtarget *Subtarget) {
15325   if (!VT.isVector())
15326     return 0;
15327
15328   switch (VT.getSimpleVT().SimpleTy) {
15329   default: return 0;
15330   case MVT::v32i8:
15331   case MVT::v16i16:
15332   case MVT::v8i32:
15333     if (!Subtarget->hasAVX2())
15334       return 0;
15335   case MVT::v16i8:
15336   case MVT::v8i16:
15337   case MVT::v4i32:
15338     if (!Subtarget->hasSSE2())
15339       return 0;
15340   }
15341
15342   // SSE2 has only a small subset of the operations.
15343   bool hasUnsigned = Subtarget->hasSSE41() ||
15344                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15345   bool hasSigned = Subtarget->hasSSE41() ||
15346                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15347
15348   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15349
15350   // Check for x CC y ? x : y.
15351   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15352       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15353     switch (CC) {
15354     default: break;
15355     case ISD::SETULT:
15356     case ISD::SETULE:
15357       return hasUnsigned ? X86ISD::UMIN : 0;
15358     case ISD::SETUGT:
15359     case ISD::SETUGE:
15360       return hasUnsigned ? X86ISD::UMAX : 0;
15361     case ISD::SETLT:
15362     case ISD::SETLE:
15363       return hasSigned ? X86ISD::SMIN : 0;
15364     case ISD::SETGT:
15365     case ISD::SETGE:
15366       return hasSigned ? X86ISD::SMAX : 0;
15367     }
15368   // Check for x CC y ? y : x -- a min/max with reversed arms.
15369   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15370              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15371     switch (CC) {
15372     default: break;
15373     case ISD::SETULT:
15374     case ISD::SETULE:
15375       return hasUnsigned ? X86ISD::UMAX : 0;
15376     case ISD::SETUGT:
15377     case ISD::SETUGE:
15378       return hasUnsigned ? X86ISD::UMIN : 0;
15379     case ISD::SETLT:
15380     case ISD::SETLE:
15381       return hasSigned ? X86ISD::SMAX : 0;
15382     case ISD::SETGT:
15383     case ISD::SETGE:
15384       return hasSigned ? X86ISD::SMIN : 0;
15385     }
15386   }
15387
15388   return 0;
15389 }
15390
15391 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15392 /// nodes.
15393 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15394                                     TargetLowering::DAGCombinerInfo &DCI,
15395                                     const X86Subtarget *Subtarget) {
15396   DebugLoc DL = N->getDebugLoc();
15397   SDValue Cond = N->getOperand(0);
15398   // Get the LHS/RHS of the select.
15399   SDValue LHS = N->getOperand(1);
15400   SDValue RHS = N->getOperand(2);
15401   EVT VT = LHS.getValueType();
15402
15403   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15404   // instructions match the semantics of the common C idiom x<y?x:y but not
15405   // x<=y?x:y, because of how they handle negative zero (which can be
15406   // ignored in unsafe-math mode).
15407   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15408       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15409       (Subtarget->hasSSE2() ||
15410        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15411     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15412
15413     unsigned Opcode = 0;
15414     // Check for x CC y ? x : y.
15415     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15416         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15417       switch (CC) {
15418       default: break;
15419       case ISD::SETULT:
15420         // Converting this to a min would handle NaNs incorrectly, and swapping
15421         // the operands would cause it to handle comparisons between positive
15422         // and negative zero incorrectly.
15423         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15424           if (!DAG.getTarget().Options.UnsafeFPMath &&
15425               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15426             break;
15427           std::swap(LHS, RHS);
15428         }
15429         Opcode = X86ISD::FMIN;
15430         break;
15431       case ISD::SETOLE:
15432         // Converting this to a min would handle comparisons between positive
15433         // and negative zero incorrectly.
15434         if (!DAG.getTarget().Options.UnsafeFPMath &&
15435             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15436           break;
15437         Opcode = X86ISD::FMIN;
15438         break;
15439       case ISD::SETULE:
15440         // Converting this to a min would handle both negative zeros and NaNs
15441         // incorrectly, but we can swap the operands to fix both.
15442         std::swap(LHS, RHS);
15443       case ISD::SETOLT:
15444       case ISD::SETLT:
15445       case ISD::SETLE:
15446         Opcode = X86ISD::FMIN;
15447         break;
15448
15449       case ISD::SETOGE:
15450         // Converting this to a max would handle comparisons between positive
15451         // and negative zero incorrectly.
15452         if (!DAG.getTarget().Options.UnsafeFPMath &&
15453             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15454           break;
15455         Opcode = X86ISD::FMAX;
15456         break;
15457       case ISD::SETUGT:
15458         // Converting this to a max would handle NaNs incorrectly, and swapping
15459         // the operands would cause it to handle comparisons between positive
15460         // and negative zero incorrectly.
15461         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15462           if (!DAG.getTarget().Options.UnsafeFPMath &&
15463               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15464             break;
15465           std::swap(LHS, RHS);
15466         }
15467         Opcode = X86ISD::FMAX;
15468         break;
15469       case ISD::SETUGE:
15470         // Converting this to a max would handle both negative zeros and NaNs
15471         // incorrectly, but we can swap the operands to fix both.
15472         std::swap(LHS, RHS);
15473       case ISD::SETOGT:
15474       case ISD::SETGT:
15475       case ISD::SETGE:
15476         Opcode = X86ISD::FMAX;
15477         break;
15478       }
15479     // Check for x CC y ? y : x -- a min/max with reversed arms.
15480     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15481                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15482       switch (CC) {
15483       default: break;
15484       case ISD::SETOGE:
15485         // Converting this to a min would handle comparisons between positive
15486         // and negative zero incorrectly, and swapping the operands would
15487         // cause it to handle NaNs incorrectly.
15488         if (!DAG.getTarget().Options.UnsafeFPMath &&
15489             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15490           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15491             break;
15492           std::swap(LHS, RHS);
15493         }
15494         Opcode = X86ISD::FMIN;
15495         break;
15496       case ISD::SETUGT:
15497         // Converting this to a min would handle NaNs incorrectly.
15498         if (!DAG.getTarget().Options.UnsafeFPMath &&
15499             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15500           break;
15501         Opcode = X86ISD::FMIN;
15502         break;
15503       case ISD::SETUGE:
15504         // Converting this to a min would handle both negative zeros and NaNs
15505         // incorrectly, but we can swap the operands to fix both.
15506         std::swap(LHS, RHS);
15507       case ISD::SETOGT:
15508       case ISD::SETGT:
15509       case ISD::SETGE:
15510         Opcode = X86ISD::FMIN;
15511         break;
15512
15513       case ISD::SETULT:
15514         // Converting this to a max would handle NaNs incorrectly.
15515         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15516           break;
15517         Opcode = X86ISD::FMAX;
15518         break;
15519       case ISD::SETOLE:
15520         // Converting this to a max would handle comparisons between positive
15521         // and negative zero incorrectly, and swapping the operands would
15522         // cause it to handle NaNs incorrectly.
15523         if (!DAG.getTarget().Options.UnsafeFPMath &&
15524             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15525           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15526             break;
15527           std::swap(LHS, RHS);
15528         }
15529         Opcode = X86ISD::FMAX;
15530         break;
15531       case ISD::SETULE:
15532         // Converting this to a max would handle both negative zeros and NaNs
15533         // incorrectly, but we can swap the operands to fix both.
15534         std::swap(LHS, RHS);
15535       case ISD::SETOLT:
15536       case ISD::SETLT:
15537       case ISD::SETLE:
15538         Opcode = X86ISD::FMAX;
15539         break;
15540       }
15541     }
15542
15543     if (Opcode)
15544       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15545   }
15546
15547   // If this is a select between two integer constants, try to do some
15548   // optimizations.
15549   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15550     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15551       // Don't do this for crazy integer types.
15552       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15553         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15554         // so that TrueC (the true value) is larger than FalseC.
15555         bool NeedsCondInvert = false;
15556
15557         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15558             // Efficiently invertible.
15559             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15560              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15561               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15562           NeedsCondInvert = true;
15563           std::swap(TrueC, FalseC);
15564         }
15565
15566         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15567         if (FalseC->getAPIntValue() == 0 &&
15568             TrueC->getAPIntValue().isPowerOf2()) {
15569           if (NeedsCondInvert) // Invert the condition if needed.
15570             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15571                                DAG.getConstant(1, Cond.getValueType()));
15572
15573           // Zero extend the condition if needed.
15574           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15575
15576           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15577           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15578                              DAG.getConstant(ShAmt, MVT::i8));
15579         }
15580
15581         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15582         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15583           if (NeedsCondInvert) // Invert the condition if needed.
15584             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15585                                DAG.getConstant(1, Cond.getValueType()));
15586
15587           // Zero extend the condition if needed.
15588           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15589                              FalseC->getValueType(0), Cond);
15590           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15591                              SDValue(FalseC, 0));
15592         }
15593
15594         // Optimize cases that will turn into an LEA instruction.  This requires
15595         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15596         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15597           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15598           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15599
15600           bool isFastMultiplier = false;
15601           if (Diff < 10) {
15602             switch ((unsigned char)Diff) {
15603               default: break;
15604               case 1:  // result = add base, cond
15605               case 2:  // result = lea base(    , cond*2)
15606               case 3:  // result = lea base(cond, cond*2)
15607               case 4:  // result = lea base(    , cond*4)
15608               case 5:  // result = lea base(cond, cond*4)
15609               case 8:  // result = lea base(    , cond*8)
15610               case 9:  // result = lea base(cond, cond*8)
15611                 isFastMultiplier = true;
15612                 break;
15613             }
15614           }
15615
15616           if (isFastMultiplier) {
15617             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15618             if (NeedsCondInvert) // Invert the condition if needed.
15619               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15620                                  DAG.getConstant(1, Cond.getValueType()));
15621
15622             // Zero extend the condition if needed.
15623             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15624                                Cond);
15625             // Scale the condition by the difference.
15626             if (Diff != 1)
15627               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15628                                  DAG.getConstant(Diff, Cond.getValueType()));
15629
15630             // Add the base if non-zero.
15631             if (FalseC->getAPIntValue() != 0)
15632               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15633                                  SDValue(FalseC, 0));
15634             return Cond;
15635           }
15636         }
15637       }
15638   }
15639
15640   // Canonicalize max and min:
15641   // (x > y) ? x : y -> (x >= y) ? x : y
15642   // (x < y) ? x : y -> (x <= y) ? x : y
15643   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15644   // the need for an extra compare
15645   // against zero. e.g.
15646   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15647   // subl   %esi, %edi
15648   // testl  %edi, %edi
15649   // movl   $0, %eax
15650   // cmovgl %edi, %eax
15651   // =>
15652   // xorl   %eax, %eax
15653   // subl   %esi, $edi
15654   // cmovsl %eax, %edi
15655   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15656       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15657       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15658     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15659     switch (CC) {
15660     default: break;
15661     case ISD::SETLT:
15662     case ISD::SETGT: {
15663       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15664       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15665                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15666       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15667     }
15668     }
15669   }
15670
15671   // Match VSELECTs into subs with unsigned saturation.
15672   if (!DCI.isBeforeLegalize() &&
15673       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15674       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15675       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15676        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15677     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15678
15679     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15680     // left side invert the predicate to simplify logic below.
15681     SDValue Other;
15682     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15683       Other = RHS;
15684       CC = ISD::getSetCCInverse(CC, true);
15685     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15686       Other = LHS;
15687     }
15688
15689     if (Other.getNode() && Other->getNumOperands() == 2 &&
15690         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15691       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15692       SDValue CondRHS = Cond->getOperand(1);
15693
15694       // Look for a general sub with unsigned saturation first.
15695       // x >= y ? x-y : 0 --> subus x, y
15696       // x >  y ? x-y : 0 --> subus x, y
15697       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15698           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15699         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15700
15701       // If the RHS is a constant we have to reverse the const canonicalization.
15702       // x > C-1 ? x+-C : 0 --> subus x, C
15703       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15704           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15705         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15706         if (CondRHS.getConstantOperandVal(0) == -A-1)
15707           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15708                              DAG.getConstant(-A, VT));
15709       }
15710
15711       // Another special case: If C was a sign bit, the sub has been
15712       // canonicalized into a xor.
15713       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15714       //        it's safe to decanonicalize the xor?
15715       // x s< 0 ? x^C : 0 --> subus x, C
15716       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15717           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15718           isSplatVector(OpRHS.getNode())) {
15719         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15720         if (A.isSignBit())
15721           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15722       }
15723     }
15724   }
15725
15726   // Try to match a min/max vector operation.
15727   if (!DCI.isBeforeLegalize() &&
15728       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15729     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15730       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15731
15732   // If we know that this node is legal then we know that it is going to be
15733   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15734   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15735   // to simplify previous instructions.
15736   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15737   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15738       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15739     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15740
15741     // Don't optimize vector selects that map to mask-registers.
15742     if (BitWidth == 1)
15743       return SDValue();
15744
15745     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15746     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15747
15748     APInt KnownZero, KnownOne;
15749     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15750                                           DCI.isBeforeLegalizeOps());
15751     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15752         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15753       DCI.CommitTargetLoweringOpt(TLO);
15754   }
15755
15756   return SDValue();
15757 }
15758
15759 // Check whether a boolean test is testing a boolean value generated by
15760 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15761 // code.
15762 //
15763 // Simplify the following patterns:
15764 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15765 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15766 // to (Op EFLAGS Cond)
15767 //
15768 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15769 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15770 // to (Op EFLAGS !Cond)
15771 //
15772 // where Op could be BRCOND or CMOV.
15773 //
15774 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15775   // Quit if not CMP and SUB with its value result used.
15776   if (Cmp.getOpcode() != X86ISD::CMP &&
15777       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15778       return SDValue();
15779
15780   // Quit if not used as a boolean value.
15781   if (CC != X86::COND_E && CC != X86::COND_NE)
15782     return SDValue();
15783
15784   // Check CMP operands. One of them should be 0 or 1 and the other should be
15785   // an SetCC or extended from it.
15786   SDValue Op1 = Cmp.getOperand(0);
15787   SDValue Op2 = Cmp.getOperand(1);
15788
15789   SDValue SetCC;
15790   const ConstantSDNode* C = 0;
15791   bool needOppositeCond = (CC == X86::COND_E);
15792
15793   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15794     SetCC = Op2;
15795   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15796     SetCC = Op1;
15797   else // Quit if all operands are not constants.
15798     return SDValue();
15799
15800   if (C->getZExtValue() == 1)
15801     needOppositeCond = !needOppositeCond;
15802   else if (C->getZExtValue() != 0)
15803     // Quit if the constant is neither 0 or 1.
15804     return SDValue();
15805
15806   // Skip 'zext' node.
15807   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15808     SetCC = SetCC.getOperand(0);
15809
15810   switch (SetCC.getOpcode()) {
15811   case X86ISD::SETCC:
15812     // Set the condition code or opposite one if necessary.
15813     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15814     if (needOppositeCond)
15815       CC = X86::GetOppositeBranchCondition(CC);
15816     return SetCC.getOperand(1);
15817   case X86ISD::CMOV: {
15818     // Check whether false/true value has canonical one, i.e. 0 or 1.
15819     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15820     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15821     // Quit if true value is not a constant.
15822     if (!TVal)
15823       return SDValue();
15824     // Quit if false value is not a constant.
15825     if (!FVal) {
15826       // A special case for rdrand, where 0 is set if false cond is found.
15827       SDValue Op = SetCC.getOperand(0);
15828       if (Op.getOpcode() != X86ISD::RDRAND)
15829         return SDValue();
15830     }
15831     // Quit if false value is not the constant 0 or 1.
15832     bool FValIsFalse = true;
15833     if (FVal && FVal->getZExtValue() != 0) {
15834       if (FVal->getZExtValue() != 1)
15835         return SDValue();
15836       // If FVal is 1, opposite cond is needed.
15837       needOppositeCond = !needOppositeCond;
15838       FValIsFalse = false;
15839     }
15840     // Quit if TVal is not the constant opposite of FVal.
15841     if (FValIsFalse && TVal->getZExtValue() != 1)
15842       return SDValue();
15843     if (!FValIsFalse && TVal->getZExtValue() != 0)
15844       return SDValue();
15845     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15846     if (needOppositeCond)
15847       CC = X86::GetOppositeBranchCondition(CC);
15848     return SetCC.getOperand(3);
15849   }
15850   }
15851
15852   return SDValue();
15853 }
15854
15855 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15856 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15857                                   TargetLowering::DAGCombinerInfo &DCI,
15858                                   const X86Subtarget *Subtarget) {
15859   DebugLoc DL = N->getDebugLoc();
15860
15861   // If the flag operand isn't dead, don't touch this CMOV.
15862   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15863     return SDValue();
15864
15865   SDValue FalseOp = N->getOperand(0);
15866   SDValue TrueOp = N->getOperand(1);
15867   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15868   SDValue Cond = N->getOperand(3);
15869
15870   if (CC == X86::COND_E || CC == X86::COND_NE) {
15871     switch (Cond.getOpcode()) {
15872     default: break;
15873     case X86ISD::BSR:
15874     case X86ISD::BSF:
15875       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15876       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15877         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15878     }
15879   }
15880
15881   SDValue Flags;
15882
15883   Flags = checkBoolTestSetCCCombine(Cond, CC);
15884   if (Flags.getNode() &&
15885       // Extra check as FCMOV only supports a subset of X86 cond.
15886       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15887     SDValue Ops[] = { FalseOp, TrueOp,
15888                       DAG.getConstant(CC, MVT::i8), Flags };
15889     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15890                        Ops, array_lengthof(Ops));
15891   }
15892
15893   // If this is a select between two integer constants, try to do some
15894   // optimizations.  Note that the operands are ordered the opposite of SELECT
15895   // operands.
15896   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15897     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15898       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15899       // larger than FalseC (the false value).
15900       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15901         CC = X86::GetOppositeBranchCondition(CC);
15902         std::swap(TrueC, FalseC);
15903         std::swap(TrueOp, FalseOp);
15904       }
15905
15906       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15907       // This is efficient for any integer data type (including i8/i16) and
15908       // shift amount.
15909       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15910         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15911                            DAG.getConstant(CC, MVT::i8), Cond);
15912
15913         // Zero extend the condition if needed.
15914         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15915
15916         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15917         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15918                            DAG.getConstant(ShAmt, MVT::i8));
15919         if (N->getNumValues() == 2)  // Dead flag value?
15920           return DCI.CombineTo(N, Cond, SDValue());
15921         return Cond;
15922       }
15923
15924       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15925       // for any integer data type, including i8/i16.
15926       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15927         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15928                            DAG.getConstant(CC, MVT::i8), Cond);
15929
15930         // Zero extend the condition if needed.
15931         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15932                            FalseC->getValueType(0), Cond);
15933         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15934                            SDValue(FalseC, 0));
15935
15936         if (N->getNumValues() == 2)  // Dead flag value?
15937           return DCI.CombineTo(N, Cond, SDValue());
15938         return Cond;
15939       }
15940
15941       // Optimize cases that will turn into an LEA instruction.  This requires
15942       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15943       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15944         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15945         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15946
15947         bool isFastMultiplier = false;
15948         if (Diff < 10) {
15949           switch ((unsigned char)Diff) {
15950           default: break;
15951           case 1:  // result = add base, cond
15952           case 2:  // result = lea base(    , cond*2)
15953           case 3:  // result = lea base(cond, cond*2)
15954           case 4:  // result = lea base(    , cond*4)
15955           case 5:  // result = lea base(cond, cond*4)
15956           case 8:  // result = lea base(    , cond*8)
15957           case 9:  // result = lea base(cond, cond*8)
15958             isFastMultiplier = true;
15959             break;
15960           }
15961         }
15962
15963         if (isFastMultiplier) {
15964           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15965           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15966                              DAG.getConstant(CC, MVT::i8), Cond);
15967           // Zero extend the condition if needed.
15968           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15969                              Cond);
15970           // Scale the condition by the difference.
15971           if (Diff != 1)
15972             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15973                                DAG.getConstant(Diff, Cond.getValueType()));
15974
15975           // Add the base if non-zero.
15976           if (FalseC->getAPIntValue() != 0)
15977             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15978                                SDValue(FalseC, 0));
15979           if (N->getNumValues() == 2)  // Dead flag value?
15980             return DCI.CombineTo(N, Cond, SDValue());
15981           return Cond;
15982         }
15983       }
15984     }
15985   }
15986
15987   // Handle these cases:
15988   //   (select (x != c), e, c) -> select (x != c), e, x),
15989   //   (select (x == c), c, e) -> select (x == c), x, e)
15990   // where the c is an integer constant, and the "select" is the combination
15991   // of CMOV and CMP.
15992   //
15993   // The rationale for this change is that the conditional-move from a constant
15994   // needs two instructions, however, conditional-move from a register needs
15995   // only one instruction.
15996   //
15997   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15998   //  some instruction-combining opportunities. This opt needs to be
15999   //  postponed as late as possible.
16000   //
16001   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16002     // the DCI.xxxx conditions are provided to postpone the optimization as
16003     // late as possible.
16004
16005     ConstantSDNode *CmpAgainst = 0;
16006     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16007         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16008         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16009
16010       if (CC == X86::COND_NE &&
16011           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16012         CC = X86::GetOppositeBranchCondition(CC);
16013         std::swap(TrueOp, FalseOp);
16014       }
16015
16016       if (CC == X86::COND_E &&
16017           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16018         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16019                           DAG.getConstant(CC, MVT::i8), Cond };
16020         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16021                            array_lengthof(Ops));
16022       }
16023     }
16024   }
16025
16026   return SDValue();
16027 }
16028
16029 /// PerformMulCombine - Optimize a single multiply with constant into two
16030 /// in order to implement it with two cheaper instructions, e.g.
16031 /// LEA + SHL, LEA + LEA.
16032 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16033                                  TargetLowering::DAGCombinerInfo &DCI) {
16034   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16035     return SDValue();
16036
16037   EVT VT = N->getValueType(0);
16038   if (VT != MVT::i64)
16039     return SDValue();
16040
16041   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16042   if (!C)
16043     return SDValue();
16044   uint64_t MulAmt = C->getZExtValue();
16045   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16046     return SDValue();
16047
16048   uint64_t MulAmt1 = 0;
16049   uint64_t MulAmt2 = 0;
16050   if ((MulAmt % 9) == 0) {
16051     MulAmt1 = 9;
16052     MulAmt2 = MulAmt / 9;
16053   } else if ((MulAmt % 5) == 0) {
16054     MulAmt1 = 5;
16055     MulAmt2 = MulAmt / 5;
16056   } else if ((MulAmt % 3) == 0) {
16057     MulAmt1 = 3;
16058     MulAmt2 = MulAmt / 3;
16059   }
16060   if (MulAmt2 &&
16061       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16062     DebugLoc DL = N->getDebugLoc();
16063
16064     if (isPowerOf2_64(MulAmt2) &&
16065         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16066       // If second multiplifer is pow2, issue it first. We want the multiply by
16067       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16068       // is an add.
16069       std::swap(MulAmt1, MulAmt2);
16070
16071     SDValue NewMul;
16072     if (isPowerOf2_64(MulAmt1))
16073       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16074                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16075     else
16076       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16077                            DAG.getConstant(MulAmt1, VT));
16078
16079     if (isPowerOf2_64(MulAmt2))
16080       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16081                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16082     else
16083       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16084                            DAG.getConstant(MulAmt2, VT));
16085
16086     // Do not add new nodes to DAG combiner worklist.
16087     DCI.CombineTo(N, NewMul, false);
16088   }
16089   return SDValue();
16090 }
16091
16092 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16093   SDValue N0 = N->getOperand(0);
16094   SDValue N1 = N->getOperand(1);
16095   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16096   EVT VT = N0.getValueType();
16097
16098   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16099   // since the result of setcc_c is all zero's or all ones.
16100   if (VT.isInteger() && !VT.isVector() &&
16101       N1C && N0.getOpcode() == ISD::AND &&
16102       N0.getOperand(1).getOpcode() == ISD::Constant) {
16103     SDValue N00 = N0.getOperand(0);
16104     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16105         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16106           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16107          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16108       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16109       APInt ShAmt = N1C->getAPIntValue();
16110       Mask = Mask.shl(ShAmt);
16111       if (Mask != 0)
16112         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16113                            N00, DAG.getConstant(Mask, VT));
16114     }
16115   }
16116
16117   // Hardware support for vector shifts is sparse which makes us scalarize the
16118   // vector operations in many cases. Also, on sandybridge ADD is faster than
16119   // shl.
16120   // (shl V, 1) -> add V,V
16121   if (isSplatVector(N1.getNode())) {
16122     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16123     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16124     // We shift all of the values by one. In many cases we do not have
16125     // hardware support for this operation. This is better expressed as an ADD
16126     // of two values.
16127     if (N1C && (1 == N1C->getZExtValue())) {
16128       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16129     }
16130   }
16131
16132   return SDValue();
16133 }
16134
16135 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
16136 ///                       when possible.
16137 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16138                                    TargetLowering::DAGCombinerInfo &DCI,
16139                                    const X86Subtarget *Subtarget) {
16140   if (N->getOpcode() == ISD::SHL) {
16141     SDValue V = PerformSHLCombine(N, DAG);
16142     if (V.getNode()) return V;
16143   }
16144
16145   return SDValue();
16146 }
16147
16148 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16149 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16150 // and friends.  Likewise for OR -> CMPNEQSS.
16151 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16152                             TargetLowering::DAGCombinerInfo &DCI,
16153                             const X86Subtarget *Subtarget) {
16154   unsigned opcode;
16155
16156   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16157   // we're requiring SSE2 for both.
16158   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16159     SDValue N0 = N->getOperand(0);
16160     SDValue N1 = N->getOperand(1);
16161     SDValue CMP0 = N0->getOperand(1);
16162     SDValue CMP1 = N1->getOperand(1);
16163     DebugLoc DL = N->getDebugLoc();
16164
16165     // The SETCCs should both refer to the same CMP.
16166     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16167       return SDValue();
16168
16169     SDValue CMP00 = CMP0->getOperand(0);
16170     SDValue CMP01 = CMP0->getOperand(1);
16171     EVT     VT    = CMP00.getValueType();
16172
16173     if (VT == MVT::f32 || VT == MVT::f64) {
16174       bool ExpectingFlags = false;
16175       // Check for any users that want flags:
16176       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16177            !ExpectingFlags && UI != UE; ++UI)
16178         switch (UI->getOpcode()) {
16179         default:
16180         case ISD::BR_CC:
16181         case ISD::BRCOND:
16182         case ISD::SELECT:
16183           ExpectingFlags = true;
16184           break;
16185         case ISD::CopyToReg:
16186         case ISD::SIGN_EXTEND:
16187         case ISD::ZERO_EXTEND:
16188         case ISD::ANY_EXTEND:
16189           break;
16190         }
16191
16192       if (!ExpectingFlags) {
16193         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16194         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16195
16196         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16197           X86::CondCode tmp = cc0;
16198           cc0 = cc1;
16199           cc1 = tmp;
16200         }
16201
16202         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16203             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16204           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16205           X86ISD::NodeType NTOperator = is64BitFP ?
16206             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16207           // FIXME: need symbolic constants for these magic numbers.
16208           // See X86ATTInstPrinter.cpp:printSSECC().
16209           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16210           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16211                                               DAG.getConstant(x86cc, MVT::i8));
16212           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16213                                               OnesOrZeroesF);
16214           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16215                                       DAG.getConstant(1, MVT::i32));
16216           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16217           return OneBitOfTruth;
16218         }
16219       }
16220     }
16221   }
16222   return SDValue();
16223 }
16224
16225 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16226 /// so it can be folded inside ANDNP.
16227 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16228   EVT VT = N->getValueType(0);
16229
16230   // Match direct AllOnes for 128 and 256-bit vectors
16231   if (ISD::isBuildVectorAllOnes(N))
16232     return true;
16233
16234   // Look through a bit convert.
16235   if (N->getOpcode() == ISD::BITCAST)
16236     N = N->getOperand(0).getNode();
16237
16238   // Sometimes the operand may come from a insert_subvector building a 256-bit
16239   // allones vector
16240   if (VT.is256BitVector() &&
16241       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16242     SDValue V1 = N->getOperand(0);
16243     SDValue V2 = N->getOperand(1);
16244
16245     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16246         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16247         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16248         ISD::isBuildVectorAllOnes(V2.getNode()))
16249       return true;
16250   }
16251
16252   return false;
16253 }
16254
16255 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16256 // register. In most cases we actually compare or select YMM-sized registers
16257 // and mixing the two types creates horrible code. This method optimizes
16258 // some of the transition sequences.
16259 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16260                                  TargetLowering::DAGCombinerInfo &DCI,
16261                                  const X86Subtarget *Subtarget) {
16262   EVT VT = N->getValueType(0);
16263   if (!VT.is256BitVector())
16264     return SDValue();
16265
16266   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16267           N->getOpcode() == ISD::ZERO_EXTEND ||
16268           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16269
16270   SDValue Narrow = N->getOperand(0);
16271   EVT NarrowVT = Narrow->getValueType(0);
16272   if (!NarrowVT.is128BitVector())
16273     return SDValue();
16274
16275   if (Narrow->getOpcode() != ISD::XOR &&
16276       Narrow->getOpcode() != ISD::AND &&
16277       Narrow->getOpcode() != ISD::OR)
16278     return SDValue();
16279
16280   SDValue N0  = Narrow->getOperand(0);
16281   SDValue N1  = Narrow->getOperand(1);
16282   DebugLoc DL = Narrow->getDebugLoc();
16283
16284   // The Left side has to be a trunc.
16285   if (N0.getOpcode() != ISD::TRUNCATE)
16286     return SDValue();
16287
16288   // The type of the truncated inputs.
16289   EVT WideVT = N0->getOperand(0)->getValueType(0);
16290   if (WideVT != VT)
16291     return SDValue();
16292
16293   // The right side has to be a 'trunc' or a constant vector.
16294   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16295   bool RHSConst = (isSplatVector(N1.getNode()) &&
16296                    isa<ConstantSDNode>(N1->getOperand(0)));
16297   if (!RHSTrunc && !RHSConst)
16298     return SDValue();
16299
16300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16301
16302   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16303     return SDValue();
16304
16305   // Set N0 and N1 to hold the inputs to the new wide operation.
16306   N0 = N0->getOperand(0);
16307   if (RHSConst) {
16308     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16309                      N1->getOperand(0));
16310     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16311     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16312   } else if (RHSTrunc) {
16313     N1 = N1->getOperand(0);
16314   }
16315
16316   // Generate the wide operation.
16317   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16318   unsigned Opcode = N->getOpcode();
16319   switch (Opcode) {
16320   case ISD::ANY_EXTEND:
16321     return Op;
16322   case ISD::ZERO_EXTEND: {
16323     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16324     APInt Mask = APInt::getAllOnesValue(InBits);
16325     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16326     return DAG.getNode(ISD::AND, DL, VT,
16327                        Op, DAG.getConstant(Mask, VT));
16328   }
16329   case ISD::SIGN_EXTEND:
16330     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16331                        Op, DAG.getValueType(NarrowVT));
16332   default:
16333     llvm_unreachable("Unexpected opcode");
16334   }
16335 }
16336
16337 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16338                                  TargetLowering::DAGCombinerInfo &DCI,
16339                                  const X86Subtarget *Subtarget) {
16340   EVT VT = N->getValueType(0);
16341   if (DCI.isBeforeLegalizeOps())
16342     return SDValue();
16343
16344   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16345   if (R.getNode())
16346     return R;
16347
16348   // Create BLSI, and BLSR instructions
16349   // BLSI is X & (-X)
16350   // BLSR is X & (X-1)
16351   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16352     SDValue N0 = N->getOperand(0);
16353     SDValue N1 = N->getOperand(1);
16354     DebugLoc DL = N->getDebugLoc();
16355
16356     // Check LHS for neg
16357     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16358         isZero(N0.getOperand(0)))
16359       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16360
16361     // Check RHS for neg
16362     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16363         isZero(N1.getOperand(0)))
16364       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16365
16366     // Check LHS for X-1
16367     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16368         isAllOnes(N0.getOperand(1)))
16369       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16370
16371     // Check RHS for X-1
16372     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16373         isAllOnes(N1.getOperand(1)))
16374       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16375
16376     return SDValue();
16377   }
16378
16379   // Want to form ANDNP nodes:
16380   // 1) In the hopes of then easily combining them with OR and AND nodes
16381   //    to form PBLEND/PSIGN.
16382   // 2) To match ANDN packed intrinsics
16383   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16384     return SDValue();
16385
16386   SDValue N0 = N->getOperand(0);
16387   SDValue N1 = N->getOperand(1);
16388   DebugLoc DL = N->getDebugLoc();
16389
16390   // Check LHS for vnot
16391   if (N0.getOpcode() == ISD::XOR &&
16392       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16393       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16394     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16395
16396   // Check RHS for vnot
16397   if (N1.getOpcode() == ISD::XOR &&
16398       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16399       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16400     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16401
16402   return SDValue();
16403 }
16404
16405 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16406                                 TargetLowering::DAGCombinerInfo &DCI,
16407                                 const X86Subtarget *Subtarget) {
16408   EVT VT = N->getValueType(0);
16409   if (DCI.isBeforeLegalizeOps())
16410     return SDValue();
16411
16412   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16413   if (R.getNode())
16414     return R;
16415
16416   SDValue N0 = N->getOperand(0);
16417   SDValue N1 = N->getOperand(1);
16418
16419   // look for psign/blend
16420   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16421     if (!Subtarget->hasSSSE3() ||
16422         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16423       return SDValue();
16424
16425     // Canonicalize pandn to RHS
16426     if (N0.getOpcode() == X86ISD::ANDNP)
16427       std::swap(N0, N1);
16428     // or (and (m, y), (pandn m, x))
16429     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16430       SDValue Mask = N1.getOperand(0);
16431       SDValue X    = N1.getOperand(1);
16432       SDValue Y;
16433       if (N0.getOperand(0) == Mask)
16434         Y = N0.getOperand(1);
16435       if (N0.getOperand(1) == Mask)
16436         Y = N0.getOperand(0);
16437
16438       // Check to see if the mask appeared in both the AND and ANDNP and
16439       if (!Y.getNode())
16440         return SDValue();
16441
16442       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16443       // Look through mask bitcast.
16444       if (Mask.getOpcode() == ISD::BITCAST)
16445         Mask = Mask.getOperand(0);
16446       if (X.getOpcode() == ISD::BITCAST)
16447         X = X.getOperand(0);
16448       if (Y.getOpcode() == ISD::BITCAST)
16449         Y = Y.getOperand(0);
16450
16451       EVT MaskVT = Mask.getValueType();
16452
16453       // Validate that the Mask operand is a vector sra node.
16454       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16455       // there is no psrai.b
16456       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16457       unsigned SraAmt = ~0;
16458       if (Mask.getOpcode() == ISD::SRA) {
16459         SDValue Amt = Mask.getOperand(1);
16460         if (isSplatVector(Amt.getNode())) {
16461           SDValue SclrAmt = Amt->getOperand(0);
16462           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16463             SraAmt = C->getZExtValue();
16464         }
16465       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16466         SDValue SraC = Mask.getOperand(1);
16467         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16468       }
16469       if ((SraAmt + 1) != EltBits)
16470         return SDValue();
16471
16472       DebugLoc DL = N->getDebugLoc();
16473
16474       // Now we know we at least have a plendvb with the mask val.  See if
16475       // we can form a psignb/w/d.
16476       // psign = x.type == y.type == mask.type && y = sub(0, x);
16477       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16478           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16479           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16480         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16481                "Unsupported VT for PSIGN");
16482         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16483         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16484       }
16485       // PBLENDVB only available on SSE 4.1
16486       if (!Subtarget->hasSSE41())
16487         return SDValue();
16488
16489       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16490
16491       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16492       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16493       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16494       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16495       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16496     }
16497   }
16498
16499   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16500     return SDValue();
16501
16502   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16503   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16504     std::swap(N0, N1);
16505   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16506     return SDValue();
16507   if (!N0.hasOneUse() || !N1.hasOneUse())
16508     return SDValue();
16509
16510   SDValue ShAmt0 = N0.getOperand(1);
16511   if (ShAmt0.getValueType() != MVT::i8)
16512     return SDValue();
16513   SDValue ShAmt1 = N1.getOperand(1);
16514   if (ShAmt1.getValueType() != MVT::i8)
16515     return SDValue();
16516   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16517     ShAmt0 = ShAmt0.getOperand(0);
16518   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16519     ShAmt1 = ShAmt1.getOperand(0);
16520
16521   DebugLoc DL = N->getDebugLoc();
16522   unsigned Opc = X86ISD::SHLD;
16523   SDValue Op0 = N0.getOperand(0);
16524   SDValue Op1 = N1.getOperand(0);
16525   if (ShAmt0.getOpcode() == ISD::SUB) {
16526     Opc = X86ISD::SHRD;
16527     std::swap(Op0, Op1);
16528     std::swap(ShAmt0, ShAmt1);
16529   }
16530
16531   unsigned Bits = VT.getSizeInBits();
16532   if (ShAmt1.getOpcode() == ISD::SUB) {
16533     SDValue Sum = ShAmt1.getOperand(0);
16534     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16535       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16536       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16537         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16538       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16539         return DAG.getNode(Opc, DL, VT,
16540                            Op0, Op1,
16541                            DAG.getNode(ISD::TRUNCATE, DL,
16542                                        MVT::i8, ShAmt0));
16543     }
16544   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16545     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16546     if (ShAmt0C &&
16547         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16548       return DAG.getNode(Opc, DL, VT,
16549                          N0.getOperand(0), N1.getOperand(0),
16550                          DAG.getNode(ISD::TRUNCATE, DL,
16551                                        MVT::i8, ShAmt0));
16552   }
16553
16554   return SDValue();
16555 }
16556
16557 // Generate NEG and CMOV for integer abs.
16558 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16559   EVT VT = N->getValueType(0);
16560
16561   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16562   // 8-bit integer abs to NEG and CMOV.
16563   if (VT.isInteger() && VT.getSizeInBits() == 8)
16564     return SDValue();
16565
16566   SDValue N0 = N->getOperand(0);
16567   SDValue N1 = N->getOperand(1);
16568   DebugLoc DL = N->getDebugLoc();
16569
16570   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16571   // and change it to SUB and CMOV.
16572   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16573       N0.getOpcode() == ISD::ADD &&
16574       N0.getOperand(1) == N1 &&
16575       N1.getOpcode() == ISD::SRA &&
16576       N1.getOperand(0) == N0.getOperand(0))
16577     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16578       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16579         // Generate SUB & CMOV.
16580         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16581                                   DAG.getConstant(0, VT), N0.getOperand(0));
16582
16583         SDValue Ops[] = { N0.getOperand(0), Neg,
16584                           DAG.getConstant(X86::COND_GE, MVT::i8),
16585                           SDValue(Neg.getNode(), 1) };
16586         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16587                            Ops, array_lengthof(Ops));
16588       }
16589   return SDValue();
16590 }
16591
16592 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16593 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16594                                  TargetLowering::DAGCombinerInfo &DCI,
16595                                  const X86Subtarget *Subtarget) {
16596   EVT VT = N->getValueType(0);
16597   if (DCI.isBeforeLegalizeOps())
16598     return SDValue();
16599
16600   if (Subtarget->hasCMov()) {
16601     SDValue RV = performIntegerAbsCombine(N, DAG);
16602     if (RV.getNode())
16603       return RV;
16604   }
16605
16606   // Try forming BMI if it is available.
16607   if (!Subtarget->hasBMI())
16608     return SDValue();
16609
16610   if (VT != MVT::i32 && VT != MVT::i64)
16611     return SDValue();
16612
16613   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16614
16615   // Create BLSMSK instructions by finding X ^ (X-1)
16616   SDValue N0 = N->getOperand(0);
16617   SDValue N1 = N->getOperand(1);
16618   DebugLoc DL = N->getDebugLoc();
16619
16620   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16621       isAllOnes(N0.getOperand(1)))
16622     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16623
16624   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16625       isAllOnes(N1.getOperand(1)))
16626     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16627
16628   return SDValue();
16629 }
16630
16631 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16632 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16633                                   TargetLowering::DAGCombinerInfo &DCI,
16634                                   const X86Subtarget *Subtarget) {
16635   LoadSDNode *Ld = cast<LoadSDNode>(N);
16636   EVT RegVT = Ld->getValueType(0);
16637   EVT MemVT = Ld->getMemoryVT();
16638   DebugLoc dl = Ld->getDebugLoc();
16639   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16640   unsigned RegSz = RegVT.getSizeInBits();
16641
16642   ISD::LoadExtType Ext = Ld->getExtensionType();
16643   unsigned Alignment = Ld->getAlignment();
16644   bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
16645
16646   // On Sandybridge unaligned 256bit loads are inefficient.
16647   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16648       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16649     unsigned NumElems = RegVT.getVectorNumElements();
16650     if (NumElems < 2)
16651       return SDValue();
16652
16653     SDValue Ptr = Ld->getBasePtr();
16654     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16655
16656     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16657                                   NumElems/2);
16658     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16659                                 Ld->getPointerInfo(), Ld->isVolatile(),
16660                                 Ld->isNonTemporal(), Ld->isInvariant(),
16661                                 Alignment);
16662     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16663     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16664                                 Ld->getPointerInfo(), Ld->isVolatile(),
16665                                 Ld->isNonTemporal(), Ld->isInvariant(),
16666                                 std::max(Alignment/2U, 1U));
16667     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16668                              Load1.getValue(1),
16669                              Load2.getValue(1));
16670
16671     SDValue NewVec = DAG.getUNDEF(RegVT);
16672     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16673     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16674     return DCI.CombineTo(N, NewVec, TF, true);
16675   }
16676
16677   // If this is a vector EXT Load then attempt to optimize it using a
16678   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16679   // expansion is still better than scalar code.
16680   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16681   // emit a shuffle and a arithmetic shift.
16682   // TODO: It is possible to support ZExt by zeroing the undef values
16683   // during the shuffle phase or after the shuffle.
16684   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16685       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16686     assert(MemVT != RegVT && "Cannot extend to the same type");
16687     assert(MemVT.isVector() && "Must load a vector from memory");
16688
16689     unsigned NumElems = RegVT.getVectorNumElements();
16690     unsigned MemSz = MemVT.getSizeInBits();
16691     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16692
16693     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16694       return SDValue();
16695
16696     // All sizes must be a power of two.
16697     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16698       return SDValue();
16699
16700     // Attempt to load the original value using scalar loads.
16701     // Find the largest scalar type that divides the total loaded size.
16702     MVT SclrLoadTy = MVT::i8;
16703     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16704          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16705       MVT Tp = (MVT::SimpleValueType)tp;
16706       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16707         SclrLoadTy = Tp;
16708       }
16709     }
16710
16711     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16712     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16713         (64 <= MemSz))
16714       SclrLoadTy = MVT::f64;
16715
16716     // Calculate the number of scalar loads that we need to perform
16717     // in order to load our vector from memory.
16718     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16719     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16720       return SDValue();
16721
16722     unsigned loadRegZize = RegSz;
16723     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16724       loadRegZize /= 2;
16725
16726     // Represent our vector as a sequence of elements which are the
16727     // largest scalar that we can load.
16728     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16729       loadRegZize/SclrLoadTy.getSizeInBits());
16730
16731     // Represent the data using the same element type that is stored in
16732     // memory. In practice, we ''widen'' MemVT.
16733     EVT WideVecVT =
16734           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16735                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16736
16737     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16738       "Invalid vector type");
16739
16740     // We can't shuffle using an illegal type.
16741     if (!TLI.isTypeLegal(WideVecVT))
16742       return SDValue();
16743
16744     SmallVector<SDValue, 8> Chains;
16745     SDValue Ptr = Ld->getBasePtr();
16746     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16747                                         TLI.getPointerTy());
16748     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16749
16750     for (unsigned i = 0; i < NumLoads; ++i) {
16751       // Perform a single load.
16752       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16753                                        Ptr, Ld->getPointerInfo(),
16754                                        Ld->isVolatile(), Ld->isNonTemporal(),
16755                                        Ld->isInvariant(), Ld->getAlignment());
16756       Chains.push_back(ScalarLoad.getValue(1));
16757       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16758       // another round of DAGCombining.
16759       if (i == 0)
16760         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16761       else
16762         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16763                           ScalarLoad, DAG.getIntPtrConstant(i));
16764
16765       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16766     }
16767
16768     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16769                                Chains.size());
16770
16771     // Bitcast the loaded value to a vector of the original element type, in
16772     // the size of the target vector type.
16773     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16774     unsigned SizeRatio = RegSz/MemSz;
16775
16776     if (Ext == ISD::SEXTLOAD) {
16777       // If we have SSE4.1 we can directly emit a VSEXT node.
16778       if (Subtarget->hasSSE41()) {
16779         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16780         return DCI.CombineTo(N, Sext, TF, true);
16781       }
16782
16783       // Otherwise we'll shuffle the small elements in the high bits of the
16784       // larger type and perform an arithmetic shift. If the shift is not legal
16785       // it's better to scalarize.
16786       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16787         return SDValue();
16788
16789       // Redistribute the loaded elements into the different locations.
16790       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16791       for (unsigned i = 0; i != NumElems; ++i)
16792         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16793
16794       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16795                                            DAG.getUNDEF(WideVecVT),
16796                                            &ShuffleVec[0]);
16797
16798       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16799
16800       // Build the arithmetic shift.
16801       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16802                      MemVT.getVectorElementType().getSizeInBits();
16803       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16804                           DAG.getConstant(Amt, RegVT));
16805
16806       return DCI.CombineTo(N, Shuff, TF, true);
16807     }
16808
16809     // Redistribute the loaded elements into the different locations.
16810     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16811     for (unsigned i = 0; i != NumElems; ++i)
16812       ShuffleVec[i*SizeRatio] = i;
16813
16814     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16815                                          DAG.getUNDEF(WideVecVT),
16816                                          &ShuffleVec[0]);
16817
16818     // Bitcast to the requested type.
16819     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16820     // Replace the original load with the new sequence
16821     // and return the new chain.
16822     return DCI.CombineTo(N, Shuff, TF, true);
16823   }
16824
16825   return SDValue();
16826 }
16827
16828 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16829 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16830                                    const X86Subtarget *Subtarget) {
16831   StoreSDNode *St = cast<StoreSDNode>(N);
16832   EVT VT = St->getValue().getValueType();
16833   EVT StVT = St->getMemoryVT();
16834   DebugLoc dl = St->getDebugLoc();
16835   SDValue StoredVal = St->getOperand(1);
16836   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16837   unsigned Alignment = St->getAlignment();
16838   bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
16839
16840   // If we are saving a concatenation of two XMM registers, perform two stores.
16841   // On Sandy Bridge, 256-bit memory operations are executed by two
16842   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16843   // memory  operation.
16844   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16845       StVT == VT && !IsAligned) {
16846     unsigned NumElems = VT.getVectorNumElements();
16847     if (NumElems < 2)
16848       return SDValue();
16849
16850     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16851     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16852
16853     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16854     SDValue Ptr0 = St->getBasePtr();
16855     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16856
16857     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16858                                 St->getPointerInfo(), St->isVolatile(),
16859                                 St->isNonTemporal(), Alignment);
16860     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16861                                 St->getPointerInfo(), St->isVolatile(),
16862                                 St->isNonTemporal(),
16863                                 std::max(Alignment/2U, 1U));
16864     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16865   }
16866
16867   // Optimize trunc store (of multiple scalars) to shuffle and store.
16868   // First, pack all of the elements in one place. Next, store to memory
16869   // in fewer chunks.
16870   if (St->isTruncatingStore() && VT.isVector()) {
16871     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16872     unsigned NumElems = VT.getVectorNumElements();
16873     assert(StVT != VT && "Cannot truncate to the same type");
16874     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16875     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16876
16877     // From, To sizes and ElemCount must be pow of two
16878     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16879     // We are going to use the original vector elt for storing.
16880     // Accumulated smaller vector elements must be a multiple of the store size.
16881     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16882
16883     unsigned SizeRatio  = FromSz / ToSz;
16884
16885     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16886
16887     // Create a type on which we perform the shuffle
16888     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16889             StVT.getScalarType(), NumElems*SizeRatio);
16890
16891     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16892
16893     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16894     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16895     for (unsigned i = 0; i != NumElems; ++i)
16896       ShuffleVec[i] = i * SizeRatio;
16897
16898     // Can't shuffle using an illegal type.
16899     if (!TLI.isTypeLegal(WideVecVT))
16900       return SDValue();
16901
16902     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16903                                          DAG.getUNDEF(WideVecVT),
16904                                          &ShuffleVec[0]);
16905     // At this point all of the data is stored at the bottom of the
16906     // register. We now need to save it to mem.
16907
16908     // Find the largest store unit
16909     MVT StoreType = MVT::i8;
16910     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16911          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16912       MVT Tp = (MVT::SimpleValueType)tp;
16913       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16914         StoreType = Tp;
16915     }
16916
16917     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16918     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16919         (64 <= NumElems * ToSz))
16920       StoreType = MVT::f64;
16921
16922     // Bitcast the original vector into a vector of store-size units
16923     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16924             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16925     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16926     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16927     SmallVector<SDValue, 8> Chains;
16928     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16929                                         TLI.getPointerTy());
16930     SDValue Ptr = St->getBasePtr();
16931
16932     // Perform one or more big stores into memory.
16933     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16934       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16935                                    StoreType, ShuffWide,
16936                                    DAG.getIntPtrConstant(i));
16937       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16938                                 St->getPointerInfo(), St->isVolatile(),
16939                                 St->isNonTemporal(), St->getAlignment());
16940       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16941       Chains.push_back(Ch);
16942     }
16943
16944     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16945                                Chains.size());
16946   }
16947
16948   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16949   // the FP state in cases where an emms may be missing.
16950   // A preferable solution to the general problem is to figure out the right
16951   // places to insert EMMS.  This qualifies as a quick hack.
16952
16953   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16954   if (VT.getSizeInBits() != 64)
16955     return SDValue();
16956
16957   const Function *F = DAG.getMachineFunction().getFunction();
16958   bool NoImplicitFloatOps = F->getAttributes().
16959     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16960   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16961                      && Subtarget->hasSSE2();
16962   if ((VT.isVector() ||
16963        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16964       isa<LoadSDNode>(St->getValue()) &&
16965       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16966       St->getChain().hasOneUse() && !St->isVolatile()) {
16967     SDNode* LdVal = St->getValue().getNode();
16968     LoadSDNode *Ld = 0;
16969     int TokenFactorIndex = -1;
16970     SmallVector<SDValue, 8> Ops;
16971     SDNode* ChainVal = St->getChain().getNode();
16972     // Must be a store of a load.  We currently handle two cases:  the load
16973     // is a direct child, and it's under an intervening TokenFactor.  It is
16974     // possible to dig deeper under nested TokenFactors.
16975     if (ChainVal == LdVal)
16976       Ld = cast<LoadSDNode>(St->getChain());
16977     else if (St->getValue().hasOneUse() &&
16978              ChainVal->getOpcode() == ISD::TokenFactor) {
16979       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16980         if (ChainVal->getOperand(i).getNode() == LdVal) {
16981           TokenFactorIndex = i;
16982           Ld = cast<LoadSDNode>(St->getValue());
16983         } else
16984           Ops.push_back(ChainVal->getOperand(i));
16985       }
16986     }
16987
16988     if (!Ld || !ISD::isNormalLoad(Ld))
16989       return SDValue();
16990
16991     // If this is not the MMX case, i.e. we are just turning i64 load/store
16992     // into f64 load/store, avoid the transformation if there are multiple
16993     // uses of the loaded value.
16994     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16995       return SDValue();
16996
16997     DebugLoc LdDL = Ld->getDebugLoc();
16998     DebugLoc StDL = N->getDebugLoc();
16999     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17000     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17001     // pair instead.
17002     if (Subtarget->is64Bit() || F64IsLegal) {
17003       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17004       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17005                                   Ld->getPointerInfo(), Ld->isVolatile(),
17006                                   Ld->isNonTemporal(), Ld->isInvariant(),
17007                                   Ld->getAlignment());
17008       SDValue NewChain = NewLd.getValue(1);
17009       if (TokenFactorIndex != -1) {
17010         Ops.push_back(NewChain);
17011         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17012                                Ops.size());
17013       }
17014       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17015                           St->getPointerInfo(),
17016                           St->isVolatile(), St->isNonTemporal(),
17017                           St->getAlignment());
17018     }
17019
17020     // Otherwise, lower to two pairs of 32-bit loads / stores.
17021     SDValue LoAddr = Ld->getBasePtr();
17022     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17023                                  DAG.getConstant(4, MVT::i32));
17024
17025     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17026                                Ld->getPointerInfo(),
17027                                Ld->isVolatile(), Ld->isNonTemporal(),
17028                                Ld->isInvariant(), Ld->getAlignment());
17029     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17030                                Ld->getPointerInfo().getWithOffset(4),
17031                                Ld->isVolatile(), Ld->isNonTemporal(),
17032                                Ld->isInvariant(),
17033                                MinAlign(Ld->getAlignment(), 4));
17034
17035     SDValue NewChain = LoLd.getValue(1);
17036     if (TokenFactorIndex != -1) {
17037       Ops.push_back(LoLd);
17038       Ops.push_back(HiLd);
17039       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17040                              Ops.size());
17041     }
17042
17043     LoAddr = St->getBasePtr();
17044     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17045                          DAG.getConstant(4, MVT::i32));
17046
17047     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17048                                 St->getPointerInfo(),
17049                                 St->isVolatile(), St->isNonTemporal(),
17050                                 St->getAlignment());
17051     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17052                                 St->getPointerInfo().getWithOffset(4),
17053                                 St->isVolatile(),
17054                                 St->isNonTemporal(),
17055                                 MinAlign(St->getAlignment(), 4));
17056     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17057   }
17058   return SDValue();
17059 }
17060
17061 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17062 /// and return the operands for the horizontal operation in LHS and RHS.  A
17063 /// horizontal operation performs the binary operation on successive elements
17064 /// of its first operand, then on successive elements of its second operand,
17065 /// returning the resulting values in a vector.  For example, if
17066 ///   A = < float a0, float a1, float a2, float a3 >
17067 /// and
17068 ///   B = < float b0, float b1, float b2, float b3 >
17069 /// then the result of doing a horizontal operation on A and B is
17070 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17071 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17072 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17073 /// set to A, RHS to B, and the routine returns 'true'.
17074 /// Note that the binary operation should have the property that if one of the
17075 /// operands is UNDEF then the result is UNDEF.
17076 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17077   // Look for the following pattern: if
17078   //   A = < float a0, float a1, float a2, float a3 >
17079   //   B = < float b0, float b1, float b2, float b3 >
17080   // and
17081   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17082   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17083   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17084   // which is A horizontal-op B.
17085
17086   // At least one of the operands should be a vector shuffle.
17087   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17088       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17089     return false;
17090
17091   EVT VT = LHS.getValueType();
17092
17093   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17094          "Unsupported vector type for horizontal add/sub");
17095
17096   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17097   // operate independently on 128-bit lanes.
17098   unsigned NumElts = VT.getVectorNumElements();
17099   unsigned NumLanes = VT.getSizeInBits()/128;
17100   unsigned NumLaneElts = NumElts / NumLanes;
17101   assert((NumLaneElts % 2 == 0) &&
17102          "Vector type should have an even number of elements in each lane");
17103   unsigned HalfLaneElts = NumLaneElts/2;
17104
17105   // View LHS in the form
17106   //   LHS = VECTOR_SHUFFLE A, B, LMask
17107   // If LHS is not a shuffle then pretend it is the shuffle
17108   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17109   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17110   // type VT.
17111   SDValue A, B;
17112   SmallVector<int, 16> LMask(NumElts);
17113   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17114     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17115       A = LHS.getOperand(0);
17116     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17117       B = LHS.getOperand(1);
17118     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17119     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17120   } else {
17121     if (LHS.getOpcode() != ISD::UNDEF)
17122       A = LHS;
17123     for (unsigned i = 0; i != NumElts; ++i)
17124       LMask[i] = i;
17125   }
17126
17127   // Likewise, view RHS in the form
17128   //   RHS = VECTOR_SHUFFLE C, D, RMask
17129   SDValue C, D;
17130   SmallVector<int, 16> RMask(NumElts);
17131   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17132     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17133       C = RHS.getOperand(0);
17134     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17135       D = RHS.getOperand(1);
17136     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17137     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17138   } else {
17139     if (RHS.getOpcode() != ISD::UNDEF)
17140       C = RHS;
17141     for (unsigned i = 0; i != NumElts; ++i)
17142       RMask[i] = i;
17143   }
17144
17145   // Check that the shuffles are both shuffling the same vectors.
17146   if (!(A == C && B == D) && !(A == D && B == C))
17147     return false;
17148
17149   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17150   if (!A.getNode() && !B.getNode())
17151     return false;
17152
17153   // If A and B occur in reverse order in RHS, then "swap" them (which means
17154   // rewriting the mask).
17155   if (A != C)
17156     CommuteVectorShuffleMask(RMask, NumElts);
17157
17158   // At this point LHS and RHS are equivalent to
17159   //   LHS = VECTOR_SHUFFLE A, B, LMask
17160   //   RHS = VECTOR_SHUFFLE A, B, RMask
17161   // Check that the masks correspond to performing a horizontal operation.
17162   for (unsigned i = 0; i != NumElts; ++i) {
17163     int LIdx = LMask[i], RIdx = RMask[i];
17164
17165     // Ignore any UNDEF components.
17166     if (LIdx < 0 || RIdx < 0 ||
17167         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17168         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17169       continue;
17170
17171     // Check that successive elements are being operated on.  If not, this is
17172     // not a horizontal operation.
17173     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17174     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17175     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17176     if (!(LIdx == Index && RIdx == Index + 1) &&
17177         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17178       return false;
17179   }
17180
17181   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17182   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17183   return true;
17184 }
17185
17186 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17187 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17188                                   const X86Subtarget *Subtarget) {
17189   EVT VT = N->getValueType(0);
17190   SDValue LHS = N->getOperand(0);
17191   SDValue RHS = N->getOperand(1);
17192
17193   // Try to synthesize horizontal adds from adds of shuffles.
17194   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17195        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17196       isHorizontalBinOp(LHS, RHS, true))
17197     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17198   return SDValue();
17199 }
17200
17201 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17202 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17203                                   const X86Subtarget *Subtarget) {
17204   EVT VT = N->getValueType(0);
17205   SDValue LHS = N->getOperand(0);
17206   SDValue RHS = N->getOperand(1);
17207
17208   // Try to synthesize horizontal subs from subs of shuffles.
17209   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17210        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17211       isHorizontalBinOp(LHS, RHS, false))
17212     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17213   return SDValue();
17214 }
17215
17216 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17217 /// X86ISD::FXOR nodes.
17218 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17219   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17220   // F[X]OR(0.0, x) -> x
17221   // F[X]OR(x, 0.0) -> x
17222   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17223     if (C->getValueAPF().isPosZero())
17224       return N->getOperand(1);
17225   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17226     if (C->getValueAPF().isPosZero())
17227       return N->getOperand(0);
17228   return SDValue();
17229 }
17230
17231 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17232 /// X86ISD::FMAX nodes.
17233 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17234   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17235
17236   // Only perform optimizations if UnsafeMath is used.
17237   if (!DAG.getTarget().Options.UnsafeFPMath)
17238     return SDValue();
17239
17240   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17241   // into FMINC and FMAXC, which are Commutative operations.
17242   unsigned NewOp = 0;
17243   switch (N->getOpcode()) {
17244     default: llvm_unreachable("unknown opcode");
17245     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17246     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17247   }
17248
17249   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17250                      N->getOperand(0), N->getOperand(1));
17251 }
17252
17253 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17254 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17255   // FAND(0.0, x) -> 0.0
17256   // FAND(x, 0.0) -> 0.0
17257   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17258     if (C->getValueAPF().isPosZero())
17259       return N->getOperand(0);
17260   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17261     if (C->getValueAPF().isPosZero())
17262       return N->getOperand(1);
17263   return SDValue();
17264 }
17265
17266 static SDValue PerformBTCombine(SDNode *N,
17267                                 SelectionDAG &DAG,
17268                                 TargetLowering::DAGCombinerInfo &DCI) {
17269   // BT ignores high bits in the bit index operand.
17270   SDValue Op1 = N->getOperand(1);
17271   if (Op1.hasOneUse()) {
17272     unsigned BitWidth = Op1.getValueSizeInBits();
17273     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17274     APInt KnownZero, KnownOne;
17275     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17276                                           !DCI.isBeforeLegalizeOps());
17277     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17278     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17279         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17280       DCI.CommitTargetLoweringOpt(TLO);
17281   }
17282   return SDValue();
17283 }
17284
17285 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17286   SDValue Op = N->getOperand(0);
17287   if (Op.getOpcode() == ISD::BITCAST)
17288     Op = Op.getOperand(0);
17289   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17290   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17291       VT.getVectorElementType().getSizeInBits() ==
17292       OpVT.getVectorElementType().getSizeInBits()) {
17293     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17294   }
17295   return SDValue();
17296 }
17297
17298 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 
17299                                                const X86Subtarget *Subtarget) {
17300   EVT VT = N->getValueType(0);
17301   if (!VT.isVector())
17302     return SDValue();
17303
17304   SDValue N0 = N->getOperand(0);
17305   SDValue N1 = N->getOperand(1);
17306   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17307   DebugLoc dl = N->getDebugLoc();
17308
17309   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17310   // both SSE and AVX2 since there is no sign-extended shift right
17311   // operation on a vector with 64-bit elements.
17312   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17313   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17314   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17315       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17316     SDValue N00 = N0.getOperand(0);
17317
17318     // EXTLOAD has a better solution on AVX2, 
17319     // it may be replaced with X86ISD::VSEXT node.
17320     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17321       if (!ISD::isNormalLoad(N00.getNode()))
17322         return SDValue();
17323
17324     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17325         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 
17326                                   N00, N1);
17327       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17328     }
17329   }
17330   return SDValue();
17331 }
17332
17333 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17334                                   TargetLowering::DAGCombinerInfo &DCI,
17335                                   const X86Subtarget *Subtarget) {
17336   if (!DCI.isBeforeLegalizeOps())
17337     return SDValue();
17338
17339   if (!Subtarget->hasFp256())
17340     return SDValue();
17341
17342   EVT VT = N->getValueType(0);
17343   if (VT.isVector() && VT.getSizeInBits() == 256) {
17344     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17345     if (R.getNode())
17346       return R;
17347   }
17348
17349   return SDValue();
17350 }
17351
17352 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17353                                  const X86Subtarget* Subtarget) {
17354   DebugLoc dl = N->getDebugLoc();
17355   EVT VT = N->getValueType(0);
17356
17357   // Let legalize expand this if it isn't a legal type yet.
17358   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17359     return SDValue();
17360
17361   EVT ScalarVT = VT.getScalarType();
17362   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17363       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17364     return SDValue();
17365
17366   SDValue A = N->getOperand(0);
17367   SDValue B = N->getOperand(1);
17368   SDValue C = N->getOperand(2);
17369
17370   bool NegA = (A.getOpcode() == ISD::FNEG);
17371   bool NegB = (B.getOpcode() == ISD::FNEG);
17372   bool NegC = (C.getOpcode() == ISD::FNEG);
17373
17374   // Negative multiplication when NegA xor NegB
17375   bool NegMul = (NegA != NegB);
17376   if (NegA)
17377     A = A.getOperand(0);
17378   if (NegB)
17379     B = B.getOperand(0);
17380   if (NegC)
17381     C = C.getOperand(0);
17382
17383   unsigned Opcode;
17384   if (!NegMul)
17385     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17386   else
17387     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17388
17389   return DAG.getNode(Opcode, dl, VT, A, B, C);
17390 }
17391
17392 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17393                                   TargetLowering::DAGCombinerInfo &DCI,
17394                                   const X86Subtarget *Subtarget) {
17395   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17396   //           (and (i32 x86isd::setcc_carry), 1)
17397   // This eliminates the zext. This transformation is necessary because
17398   // ISD::SETCC is always legalized to i8.
17399   DebugLoc dl = N->getDebugLoc();
17400   SDValue N0 = N->getOperand(0);
17401   EVT VT = N->getValueType(0);
17402
17403   if (N0.getOpcode() == ISD::AND &&
17404       N0.hasOneUse() &&
17405       N0.getOperand(0).hasOneUse()) {
17406     SDValue N00 = N0.getOperand(0);
17407     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17408       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17409       if (!C || C->getZExtValue() != 1)
17410         return SDValue();
17411       return DAG.getNode(ISD::AND, dl, VT,
17412                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17413                                      N00.getOperand(0), N00.getOperand(1)),
17414                          DAG.getConstant(1, VT));
17415     }
17416   }
17417
17418   if (VT.is256BitVector()) {
17419     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17420     if (R.getNode())
17421       return R;
17422   }
17423
17424   return SDValue();
17425 }
17426
17427 // Optimize x == -y --> x+y == 0
17428 //          x != -y --> x+y != 0
17429 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17430   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17431   SDValue LHS = N->getOperand(0);
17432   SDValue RHS = N->getOperand(1);
17433
17434   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17435     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17436       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17437         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17438                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17439         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17440                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17441       }
17442   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17443     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17444       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17445         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17446                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17447         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17448                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17449       }
17450   return SDValue();
17451 }
17452
17453 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17454 // as "sbb reg,reg", since it can be extended without zext and produces
17455 // an all-ones bit which is more useful than 0/1 in some cases.
17456 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17457   return DAG.getNode(ISD::AND, DL, MVT::i8,
17458                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17459                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17460                      DAG.getConstant(1, MVT::i8));
17461 }
17462
17463 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17464 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17465                                    TargetLowering::DAGCombinerInfo &DCI,
17466                                    const X86Subtarget *Subtarget) {
17467   DebugLoc DL = N->getDebugLoc();
17468   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17469   SDValue EFLAGS = N->getOperand(1);
17470
17471   if (CC == X86::COND_A) {
17472     // Try to convert COND_A into COND_B in an attempt to facilitate
17473     // materializing "setb reg".
17474     //
17475     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17476     // cannot take an immediate as its first operand.
17477     //
17478     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17479         EFLAGS.getValueType().isInteger() &&
17480         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17481       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17482                                    EFLAGS.getNode()->getVTList(),
17483                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17484       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17485       return MaterializeSETB(DL, NewEFLAGS, DAG);
17486     }
17487   }
17488
17489   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17490   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17491   // cases.
17492   if (CC == X86::COND_B)
17493     return MaterializeSETB(DL, EFLAGS, DAG);
17494
17495   SDValue Flags;
17496
17497   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17498   if (Flags.getNode()) {
17499     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17500     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17501   }
17502
17503   return SDValue();
17504 }
17505
17506 // Optimize branch condition evaluation.
17507 //
17508 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17509                                     TargetLowering::DAGCombinerInfo &DCI,
17510                                     const X86Subtarget *Subtarget) {
17511   DebugLoc DL = N->getDebugLoc();
17512   SDValue Chain = N->getOperand(0);
17513   SDValue Dest = N->getOperand(1);
17514   SDValue EFLAGS = N->getOperand(3);
17515   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17516
17517   SDValue Flags;
17518
17519   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17520   if (Flags.getNode()) {
17521     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17522     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17523                        Flags);
17524   }
17525
17526   return SDValue();
17527 }
17528
17529 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17530                                         const X86TargetLowering *XTLI) {
17531   SDValue Op0 = N->getOperand(0);
17532   EVT InVT = Op0->getValueType(0);
17533
17534   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17535   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17536     DebugLoc dl = N->getDebugLoc();
17537     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17538     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17539     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17540   }
17541
17542   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17543   // a 32-bit target where SSE doesn't support i64->FP operations.
17544   if (Op0.getOpcode() == ISD::LOAD) {
17545     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17546     EVT VT = Ld->getValueType(0);
17547     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17548         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17549         !XTLI->getSubtarget()->is64Bit() &&
17550         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17551       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17552                                           Ld->getChain(), Op0, DAG);
17553       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17554       return FILDChain;
17555     }
17556   }
17557   return SDValue();
17558 }
17559
17560 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17561 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17562                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17563   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17564   // the result is either zero or one (depending on the input carry bit).
17565   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17566   if (X86::isZeroNode(N->getOperand(0)) &&
17567       X86::isZeroNode(N->getOperand(1)) &&
17568       // We don't have a good way to replace an EFLAGS use, so only do this when
17569       // dead right now.
17570       SDValue(N, 1).use_empty()) {
17571     DebugLoc DL = N->getDebugLoc();
17572     EVT VT = N->getValueType(0);
17573     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17574     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17575                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17576                                            DAG.getConstant(X86::COND_B,MVT::i8),
17577                                            N->getOperand(2)),
17578                                DAG.getConstant(1, VT));
17579     return DCI.CombineTo(N, Res1, CarryOut);
17580   }
17581
17582   return SDValue();
17583 }
17584
17585 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17586 //      (add Y, (setne X, 0)) -> sbb -1, Y
17587 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17588 //      (sub (setne X, 0), Y) -> adc -1, Y
17589 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17590   DebugLoc DL = N->getDebugLoc();
17591
17592   // Look through ZExts.
17593   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17594   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17595     return SDValue();
17596
17597   SDValue SetCC = Ext.getOperand(0);
17598   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17599     return SDValue();
17600
17601   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17602   if (CC != X86::COND_E && CC != X86::COND_NE)
17603     return SDValue();
17604
17605   SDValue Cmp = SetCC.getOperand(1);
17606   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17607       !X86::isZeroNode(Cmp.getOperand(1)) ||
17608       !Cmp.getOperand(0).getValueType().isInteger())
17609     return SDValue();
17610
17611   SDValue CmpOp0 = Cmp.getOperand(0);
17612   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17613                                DAG.getConstant(1, CmpOp0.getValueType()));
17614
17615   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17616   if (CC == X86::COND_NE)
17617     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17618                        DL, OtherVal.getValueType(), OtherVal,
17619                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17620   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17621                      DL, OtherVal.getValueType(), OtherVal,
17622                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17623 }
17624
17625 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17626 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17627                                  const X86Subtarget *Subtarget) {
17628   EVT VT = N->getValueType(0);
17629   SDValue Op0 = N->getOperand(0);
17630   SDValue Op1 = N->getOperand(1);
17631
17632   // Try to synthesize horizontal adds from adds of shuffles.
17633   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17634        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17635       isHorizontalBinOp(Op0, Op1, true))
17636     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17637
17638   return OptimizeConditionalInDecrement(N, DAG);
17639 }
17640
17641 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17642                                  const X86Subtarget *Subtarget) {
17643   SDValue Op0 = N->getOperand(0);
17644   SDValue Op1 = N->getOperand(1);
17645
17646   // X86 can't encode an immediate LHS of a sub. See if we can push the
17647   // negation into a preceding instruction.
17648   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17649     // If the RHS of the sub is a XOR with one use and a constant, invert the
17650     // immediate. Then add one to the LHS of the sub so we can turn
17651     // X-Y -> X+~Y+1, saving one register.
17652     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17653         isa<ConstantSDNode>(Op1.getOperand(1))) {
17654       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17655       EVT VT = Op0.getValueType();
17656       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17657                                    Op1.getOperand(0),
17658                                    DAG.getConstant(~XorC, VT));
17659       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17660                          DAG.getConstant(C->getAPIntValue()+1, VT));
17661     }
17662   }
17663
17664   // Try to synthesize horizontal adds from adds of shuffles.
17665   EVT VT = N->getValueType(0);
17666   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17667        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17668       isHorizontalBinOp(Op0, Op1, true))
17669     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17670
17671   return OptimizeConditionalInDecrement(N, DAG);
17672 }
17673
17674 /// performVZEXTCombine - Performs build vector combines
17675 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17676                                         TargetLowering::DAGCombinerInfo &DCI,
17677                                         const X86Subtarget *Subtarget) {
17678   // (vzext (bitcast (vzext (x)) -> (vzext x)
17679   SDValue In = N->getOperand(0);
17680   while (In.getOpcode() == ISD::BITCAST)
17681     In = In.getOperand(0);
17682
17683   if (In.getOpcode() != X86ISD::VZEXT)
17684     return SDValue();
17685
17686   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17687                      In.getOperand(0));
17688 }
17689
17690 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17691                                              DAGCombinerInfo &DCI) const {
17692   SelectionDAG &DAG = DCI.DAG;
17693   switch (N->getOpcode()) {
17694   default: break;
17695   case ISD::EXTRACT_VECTOR_ELT:
17696     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17697   case ISD::VSELECT:
17698   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17699   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17700   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17701   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17702   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17703   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17704   case ISD::SHL:
17705   case ISD::SRA:
17706   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17707   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17708   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17709   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17710   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17711   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17712   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17713   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17714   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17715   case X86ISD::FXOR:
17716   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17717   case X86ISD::FMIN:
17718   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17719   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17720   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17721   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17722   case ISD::ANY_EXTEND:
17723   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17724   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17725   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17726   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17727   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17728   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17729   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17730   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17731   case X86ISD::SHUFP:       // Handle all target specific shuffles
17732   case X86ISD::PALIGNR:
17733   case X86ISD::UNPCKH:
17734   case X86ISD::UNPCKL:
17735   case X86ISD::MOVHLPS:
17736   case X86ISD::MOVLHPS:
17737   case X86ISD::PSHUFD:
17738   case X86ISD::PSHUFHW:
17739   case X86ISD::PSHUFLW:
17740   case X86ISD::MOVSS:
17741   case X86ISD::MOVSD:
17742   case X86ISD::VPERMILP:
17743   case X86ISD::VPERM2X128:
17744   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17745   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17746   }
17747
17748   return SDValue();
17749 }
17750
17751 /// isTypeDesirableForOp - Return true if the target has native support for
17752 /// the specified value type and it is 'desirable' to use the type for the
17753 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17754 /// instruction encodings are longer and some i16 instructions are slow.
17755 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17756   if (!isTypeLegal(VT))
17757     return false;
17758   if (VT != MVT::i16)
17759     return true;
17760
17761   switch (Opc) {
17762   default:
17763     return true;
17764   case ISD::LOAD:
17765   case ISD::SIGN_EXTEND:
17766   case ISD::ZERO_EXTEND:
17767   case ISD::ANY_EXTEND:
17768   case ISD::SHL:
17769   case ISD::SRL:
17770   case ISD::SUB:
17771   case ISD::ADD:
17772   case ISD::MUL:
17773   case ISD::AND:
17774   case ISD::OR:
17775   case ISD::XOR:
17776     return false;
17777   }
17778 }
17779
17780 /// IsDesirableToPromoteOp - This method query the target whether it is
17781 /// beneficial for dag combiner to promote the specified node. If true, it
17782 /// should return the desired promotion type by reference.
17783 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17784   EVT VT = Op.getValueType();
17785   if (VT != MVT::i16)
17786     return false;
17787
17788   bool Promote = false;
17789   bool Commute = false;
17790   switch (Op.getOpcode()) {
17791   default: break;
17792   case ISD::LOAD: {
17793     LoadSDNode *LD = cast<LoadSDNode>(Op);
17794     // If the non-extending load has a single use and it's not live out, then it
17795     // might be folded.
17796     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17797                                                      Op.hasOneUse()*/) {
17798       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17799              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17800         // The only case where we'd want to promote LOAD (rather then it being
17801         // promoted as an operand is when it's only use is liveout.
17802         if (UI->getOpcode() != ISD::CopyToReg)
17803           return false;
17804       }
17805     }
17806     Promote = true;
17807     break;
17808   }
17809   case ISD::SIGN_EXTEND:
17810   case ISD::ZERO_EXTEND:
17811   case ISD::ANY_EXTEND:
17812     Promote = true;
17813     break;
17814   case ISD::SHL:
17815   case ISD::SRL: {
17816     SDValue N0 = Op.getOperand(0);
17817     // Look out for (store (shl (load), x)).
17818     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17819       return false;
17820     Promote = true;
17821     break;
17822   }
17823   case ISD::ADD:
17824   case ISD::MUL:
17825   case ISD::AND:
17826   case ISD::OR:
17827   case ISD::XOR:
17828     Commute = true;
17829     // fallthrough
17830   case ISD::SUB: {
17831     SDValue N0 = Op.getOperand(0);
17832     SDValue N1 = Op.getOperand(1);
17833     if (!Commute && MayFoldLoad(N1))
17834       return false;
17835     // Avoid disabling potential load folding opportunities.
17836     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17837       return false;
17838     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17839       return false;
17840     Promote = true;
17841   }
17842   }
17843
17844   PVT = MVT::i32;
17845   return Promote;
17846 }
17847
17848 //===----------------------------------------------------------------------===//
17849 //                           X86 Inline Assembly Support
17850 //===----------------------------------------------------------------------===//
17851
17852 namespace {
17853   // Helper to match a string separated by whitespace.
17854   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17855     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17856
17857     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17858       StringRef piece(*args[i]);
17859       if (!s.startswith(piece)) // Check if the piece matches.
17860         return false;
17861
17862       s = s.substr(piece.size());
17863       StringRef::size_type pos = s.find_first_not_of(" \t");
17864       if (pos == 0) // We matched a prefix.
17865         return false;
17866
17867       s = s.substr(pos);
17868     }
17869
17870     return s.empty();
17871   }
17872   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17873 }
17874
17875 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17876   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17877
17878   std::string AsmStr = IA->getAsmString();
17879
17880   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17881   if (!Ty || Ty->getBitWidth() % 16 != 0)
17882     return false;
17883
17884   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17885   SmallVector<StringRef, 4> AsmPieces;
17886   SplitString(AsmStr, AsmPieces, ";\n");
17887
17888   switch (AsmPieces.size()) {
17889   default: return false;
17890   case 1:
17891     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17892     // we will turn this bswap into something that will be lowered to logical
17893     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17894     // lower so don't worry about this.
17895     // bswap $0
17896     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17897         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17898         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17899         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17900         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17901         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17902       // No need to check constraints, nothing other than the equivalent of
17903       // "=r,0" would be valid here.
17904       return IntrinsicLowering::LowerToByteSwap(CI);
17905     }
17906
17907     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17908     if (CI->getType()->isIntegerTy(16) &&
17909         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17910         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17911          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17912       AsmPieces.clear();
17913       const std::string &ConstraintsStr = IA->getConstraintString();
17914       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17915       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17916       if (AsmPieces.size() == 4 &&
17917           AsmPieces[0] == "~{cc}" &&
17918           AsmPieces[1] == "~{dirflag}" &&
17919           AsmPieces[2] == "~{flags}" &&
17920           AsmPieces[3] == "~{fpsr}")
17921       return IntrinsicLowering::LowerToByteSwap(CI);
17922     }
17923     break;
17924   case 3:
17925     if (CI->getType()->isIntegerTy(32) &&
17926         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17927         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17928         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17929         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17930       AsmPieces.clear();
17931       const std::string &ConstraintsStr = IA->getConstraintString();
17932       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17933       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17934       if (AsmPieces.size() == 4 &&
17935           AsmPieces[0] == "~{cc}" &&
17936           AsmPieces[1] == "~{dirflag}" &&
17937           AsmPieces[2] == "~{flags}" &&
17938           AsmPieces[3] == "~{fpsr}")
17939         return IntrinsicLowering::LowerToByteSwap(CI);
17940     }
17941
17942     if (CI->getType()->isIntegerTy(64)) {
17943       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17944       if (Constraints.size() >= 2 &&
17945           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17946           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17947         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17948         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17949             matchAsm(AsmPieces[1], "bswap", "%edx") &&
17950             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17951           return IntrinsicLowering::LowerToByteSwap(CI);
17952       }
17953     }
17954     break;
17955   }
17956   return false;
17957 }
17958
17959 /// getConstraintType - Given a constraint letter, return the type of
17960 /// constraint it is for this target.
17961 X86TargetLowering::ConstraintType
17962 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17963   if (Constraint.size() == 1) {
17964     switch (Constraint[0]) {
17965     case 'R':
17966     case 'q':
17967     case 'Q':
17968     case 'f':
17969     case 't':
17970     case 'u':
17971     case 'y':
17972     case 'x':
17973     case 'Y':
17974     case 'l':
17975       return C_RegisterClass;
17976     case 'a':
17977     case 'b':
17978     case 'c':
17979     case 'd':
17980     case 'S':
17981     case 'D':
17982     case 'A':
17983       return C_Register;
17984     case 'I':
17985     case 'J':
17986     case 'K':
17987     case 'L':
17988     case 'M':
17989     case 'N':
17990     case 'G':
17991     case 'C':
17992     case 'e':
17993     case 'Z':
17994       return C_Other;
17995     default:
17996       break;
17997     }
17998   }
17999   return TargetLowering::getConstraintType(Constraint);
18000 }
18001
18002 /// Examine constraint type and operand type and determine a weight value.
18003 /// This object must already have been set up with the operand type
18004 /// and the current alternative constraint selected.
18005 TargetLowering::ConstraintWeight
18006   X86TargetLowering::getSingleConstraintMatchWeight(
18007     AsmOperandInfo &info, const char *constraint) const {
18008   ConstraintWeight weight = CW_Invalid;
18009   Value *CallOperandVal = info.CallOperandVal;
18010     // If we don't have a value, we can't do a match,
18011     // but allow it at the lowest weight.
18012   if (CallOperandVal == NULL)
18013     return CW_Default;
18014   Type *type = CallOperandVal->getType();
18015   // Look at the constraint type.
18016   switch (*constraint) {
18017   default:
18018     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18019   case 'R':
18020   case 'q':
18021   case 'Q':
18022   case 'a':
18023   case 'b':
18024   case 'c':
18025   case 'd':
18026   case 'S':
18027   case 'D':
18028   case 'A':
18029     if (CallOperandVal->getType()->isIntegerTy())
18030       weight = CW_SpecificReg;
18031     break;
18032   case 'f':
18033   case 't':
18034   case 'u':
18035     if (type->isFloatingPointTy())
18036       weight = CW_SpecificReg;
18037     break;
18038   case 'y':
18039     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18040       weight = CW_SpecificReg;
18041     break;
18042   case 'x':
18043   case 'Y':
18044     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18045         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18046       weight = CW_Register;
18047     break;
18048   case 'I':
18049     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18050       if (C->getZExtValue() <= 31)
18051         weight = CW_Constant;
18052     }
18053     break;
18054   case 'J':
18055     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18056       if (C->getZExtValue() <= 63)
18057         weight = CW_Constant;
18058     }
18059     break;
18060   case 'K':
18061     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18062       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18063         weight = CW_Constant;
18064     }
18065     break;
18066   case 'L':
18067     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18068       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18069         weight = CW_Constant;
18070     }
18071     break;
18072   case 'M':
18073     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18074       if (C->getZExtValue() <= 3)
18075         weight = CW_Constant;
18076     }
18077     break;
18078   case 'N':
18079     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18080       if (C->getZExtValue() <= 0xff)
18081         weight = CW_Constant;
18082     }
18083     break;
18084   case 'G':
18085   case 'C':
18086     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18087       weight = CW_Constant;
18088     }
18089     break;
18090   case 'e':
18091     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18092       if ((C->getSExtValue() >= -0x80000000LL) &&
18093           (C->getSExtValue() <= 0x7fffffffLL))
18094         weight = CW_Constant;
18095     }
18096     break;
18097   case 'Z':
18098     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18099       if (C->getZExtValue() <= 0xffffffff)
18100         weight = CW_Constant;
18101     }
18102     break;
18103   }
18104   return weight;
18105 }
18106
18107 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18108 /// with another that has more specific requirements based on the type of the
18109 /// corresponding operand.
18110 const char *X86TargetLowering::
18111 LowerXConstraint(EVT ConstraintVT) const {
18112   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18113   // 'f' like normal targets.
18114   if (ConstraintVT.isFloatingPoint()) {
18115     if (Subtarget->hasSSE2())
18116       return "Y";
18117     if (Subtarget->hasSSE1())
18118       return "x";
18119   }
18120
18121   return TargetLowering::LowerXConstraint(ConstraintVT);
18122 }
18123
18124 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18125 /// vector.  If it is invalid, don't add anything to Ops.
18126 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18127                                                      std::string &Constraint,
18128                                                      std::vector<SDValue>&Ops,
18129                                                      SelectionDAG &DAG) const {
18130   SDValue Result(0, 0);
18131
18132   // Only support length 1 constraints for now.
18133   if (Constraint.length() > 1) return;
18134
18135   char ConstraintLetter = Constraint[0];
18136   switch (ConstraintLetter) {
18137   default: break;
18138   case 'I':
18139     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18140       if (C->getZExtValue() <= 31) {
18141         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18142         break;
18143       }
18144     }
18145     return;
18146   case 'J':
18147     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18148       if (C->getZExtValue() <= 63) {
18149         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18150         break;
18151       }
18152     }
18153     return;
18154   case 'K':
18155     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18156       if (isInt<8>(C->getSExtValue())) {
18157         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18158         break;
18159       }
18160     }
18161     return;
18162   case 'N':
18163     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18164       if (C->getZExtValue() <= 255) {
18165         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18166         break;
18167       }
18168     }
18169     return;
18170   case 'e': {
18171     // 32-bit signed value
18172     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18173       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18174                                            C->getSExtValue())) {
18175         // Widen to 64 bits here to get it sign extended.
18176         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18177         break;
18178       }
18179     // FIXME gcc accepts some relocatable values here too, but only in certain
18180     // memory models; it's complicated.
18181     }
18182     return;
18183   }
18184   case 'Z': {
18185     // 32-bit unsigned value
18186     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18187       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18188                                            C->getZExtValue())) {
18189         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18190         break;
18191       }
18192     }
18193     // FIXME gcc accepts some relocatable values here too, but only in certain
18194     // memory models; it's complicated.
18195     return;
18196   }
18197   case 'i': {
18198     // Literal immediates are always ok.
18199     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18200       // Widen to 64 bits here to get it sign extended.
18201       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18202       break;
18203     }
18204
18205     // In any sort of PIC mode addresses need to be computed at runtime by
18206     // adding in a register or some sort of table lookup.  These can't
18207     // be used as immediates.
18208     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18209       return;
18210
18211     // If we are in non-pic codegen mode, we allow the address of a global (with
18212     // an optional displacement) to be used with 'i'.
18213     GlobalAddressSDNode *GA = 0;
18214     int64_t Offset = 0;
18215
18216     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18217     while (1) {
18218       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18219         Offset += GA->getOffset();
18220         break;
18221       } else if (Op.getOpcode() == ISD::ADD) {
18222         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18223           Offset += C->getZExtValue();
18224           Op = Op.getOperand(0);
18225           continue;
18226         }
18227       } else if (Op.getOpcode() == ISD::SUB) {
18228         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18229           Offset += -C->getZExtValue();
18230           Op = Op.getOperand(0);
18231           continue;
18232         }
18233       }
18234
18235       // Otherwise, this isn't something we can handle, reject it.
18236       return;
18237     }
18238
18239     const GlobalValue *GV = GA->getGlobal();
18240     // If we require an extra load to get this address, as in PIC mode, we
18241     // can't accept it.
18242     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18243                                                         getTargetMachine())))
18244       return;
18245
18246     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18247                                         GA->getValueType(0), Offset);
18248     break;
18249   }
18250   }
18251
18252   if (Result.getNode()) {
18253     Ops.push_back(Result);
18254     return;
18255   }
18256   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18257 }
18258
18259 std::pair<unsigned, const TargetRegisterClass*>
18260 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18261                                                 EVT VT) const {
18262   // First, see if this is a constraint that directly corresponds to an LLVM
18263   // register class.
18264   if (Constraint.size() == 1) {
18265     // GCC Constraint Letters
18266     switch (Constraint[0]) {
18267     default: break;
18268       // TODO: Slight differences here in allocation order and leaving
18269       // RIP in the class. Do they matter any more here than they do
18270       // in the normal allocation?
18271     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18272       if (Subtarget->is64Bit()) {
18273         if (VT == MVT::i32 || VT == MVT::f32)
18274           return std::make_pair(0U, &X86::GR32RegClass);
18275         if (VT == MVT::i16)
18276           return std::make_pair(0U, &X86::GR16RegClass);
18277         if (VT == MVT::i8 || VT == MVT::i1)
18278           return std::make_pair(0U, &X86::GR8RegClass);
18279         if (VT == MVT::i64 || VT == MVT::f64)
18280           return std::make_pair(0U, &X86::GR64RegClass);
18281         break;
18282       }
18283       // 32-bit fallthrough
18284     case 'Q':   // Q_REGS
18285       if (VT == MVT::i32 || VT == MVT::f32)
18286         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18287       if (VT == MVT::i16)
18288         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18289       if (VT == MVT::i8 || VT == MVT::i1)
18290         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18291       if (VT == MVT::i64)
18292         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18293       break;
18294     case 'r':   // GENERAL_REGS
18295     case 'l':   // INDEX_REGS
18296       if (VT == MVT::i8 || VT == MVT::i1)
18297         return std::make_pair(0U, &X86::GR8RegClass);
18298       if (VT == MVT::i16)
18299         return std::make_pair(0U, &X86::GR16RegClass);
18300       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18301         return std::make_pair(0U, &X86::GR32RegClass);
18302       return std::make_pair(0U, &X86::GR64RegClass);
18303     case 'R':   // LEGACY_REGS
18304       if (VT == MVT::i8 || VT == MVT::i1)
18305         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18306       if (VT == MVT::i16)
18307         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18308       if (VT == MVT::i32 || !Subtarget->is64Bit())
18309         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18310       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18311     case 'f':  // FP Stack registers.
18312       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18313       // value to the correct fpstack register class.
18314       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18315         return std::make_pair(0U, &X86::RFP32RegClass);
18316       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18317         return std::make_pair(0U, &X86::RFP64RegClass);
18318       return std::make_pair(0U, &X86::RFP80RegClass);
18319     case 'y':   // MMX_REGS if MMX allowed.
18320       if (!Subtarget->hasMMX()) break;
18321       return std::make_pair(0U, &X86::VR64RegClass);
18322     case 'Y':   // SSE_REGS if SSE2 allowed
18323       if (!Subtarget->hasSSE2()) break;
18324       // FALL THROUGH.
18325     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18326       if (!Subtarget->hasSSE1()) break;
18327
18328       switch (VT.getSimpleVT().SimpleTy) {
18329       default: break;
18330       // Scalar SSE types.
18331       case MVT::f32:
18332       case MVT::i32:
18333         return std::make_pair(0U, &X86::FR32RegClass);
18334       case MVT::f64:
18335       case MVT::i64:
18336         return std::make_pair(0U, &X86::FR64RegClass);
18337       // Vector types.
18338       case MVT::v16i8:
18339       case MVT::v8i16:
18340       case MVT::v4i32:
18341       case MVT::v2i64:
18342       case MVT::v4f32:
18343       case MVT::v2f64:
18344         return std::make_pair(0U, &X86::VR128RegClass);
18345       // AVX types.
18346       case MVT::v32i8:
18347       case MVT::v16i16:
18348       case MVT::v8i32:
18349       case MVT::v4i64:
18350       case MVT::v8f32:
18351       case MVT::v4f64:
18352         return std::make_pair(0U, &X86::VR256RegClass);
18353       }
18354       break;
18355     }
18356   }
18357
18358   // Use the default implementation in TargetLowering to convert the register
18359   // constraint into a member of a register class.
18360   std::pair<unsigned, const TargetRegisterClass*> Res;
18361   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18362
18363   // Not found as a standard register?
18364   if (Res.second == 0) {
18365     // Map st(0) -> st(7) -> ST0
18366     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18367         tolower(Constraint[1]) == 's' &&
18368         tolower(Constraint[2]) == 't' &&
18369         Constraint[3] == '(' &&
18370         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18371         Constraint[5] == ')' &&
18372         Constraint[6] == '}') {
18373
18374       Res.first = X86::ST0+Constraint[4]-'0';
18375       Res.second = &X86::RFP80RegClass;
18376       return Res;
18377     }
18378
18379     // GCC allows "st(0)" to be called just plain "st".
18380     if (StringRef("{st}").equals_lower(Constraint)) {
18381       Res.first = X86::ST0;
18382       Res.second = &X86::RFP80RegClass;
18383       return Res;
18384     }
18385
18386     // flags -> EFLAGS
18387     if (StringRef("{flags}").equals_lower(Constraint)) {
18388       Res.first = X86::EFLAGS;
18389       Res.second = &X86::CCRRegClass;
18390       return Res;
18391     }
18392
18393     // 'A' means EAX + EDX.
18394     if (Constraint == "A") {
18395       Res.first = X86::EAX;
18396       Res.second = &X86::GR32_ADRegClass;
18397       return Res;
18398     }
18399     return Res;
18400   }
18401
18402   // Otherwise, check to see if this is a register class of the wrong value
18403   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18404   // turn into {ax},{dx}.
18405   if (Res.second->hasType(VT))
18406     return Res;   // Correct type already, nothing to do.
18407
18408   // All of the single-register GCC register classes map their values onto
18409   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18410   // really want an 8-bit or 32-bit register, map to the appropriate register
18411   // class and return the appropriate register.
18412   if (Res.second == &X86::GR16RegClass) {
18413     if (VT == MVT::i8 || VT == MVT::i1) {
18414       unsigned DestReg = 0;
18415       switch (Res.first) {
18416       default: break;
18417       case X86::AX: DestReg = X86::AL; break;
18418       case X86::DX: DestReg = X86::DL; break;
18419       case X86::CX: DestReg = X86::CL; break;
18420       case X86::BX: DestReg = X86::BL; break;
18421       }
18422       if (DestReg) {
18423         Res.first = DestReg;
18424         Res.second = &X86::GR8RegClass;
18425       }
18426     } else if (VT == MVT::i32 || VT == MVT::f32) {
18427       unsigned DestReg = 0;
18428       switch (Res.first) {
18429       default: break;
18430       case X86::AX: DestReg = X86::EAX; break;
18431       case X86::DX: DestReg = X86::EDX; break;
18432       case X86::CX: DestReg = X86::ECX; break;
18433       case X86::BX: DestReg = X86::EBX; break;
18434       case X86::SI: DestReg = X86::ESI; break;
18435       case X86::DI: DestReg = X86::EDI; break;
18436       case X86::BP: DestReg = X86::EBP; break;
18437       case X86::SP: DestReg = X86::ESP; break;
18438       }
18439       if (DestReg) {
18440         Res.first = DestReg;
18441         Res.second = &X86::GR32RegClass;
18442       }
18443     } else if (VT == MVT::i64 || VT == MVT::f64) {
18444       unsigned DestReg = 0;
18445       switch (Res.first) {
18446       default: break;
18447       case X86::AX: DestReg = X86::RAX; break;
18448       case X86::DX: DestReg = X86::RDX; break;
18449       case X86::CX: DestReg = X86::RCX; break;
18450       case X86::BX: DestReg = X86::RBX; break;
18451       case X86::SI: DestReg = X86::RSI; break;
18452       case X86::DI: DestReg = X86::RDI; break;
18453       case X86::BP: DestReg = X86::RBP; break;
18454       case X86::SP: DestReg = X86::RSP; break;
18455       }
18456       if (DestReg) {
18457         Res.first = DestReg;
18458         Res.second = &X86::GR64RegClass;
18459       }
18460     }
18461   } else if (Res.second == &X86::FR32RegClass ||
18462              Res.second == &X86::FR64RegClass ||
18463              Res.second == &X86::VR128RegClass) {
18464     // Handle references to XMM physical registers that got mapped into the
18465     // wrong class.  This can happen with constraints like {xmm0} where the
18466     // target independent register mapper will just pick the first match it can
18467     // find, ignoring the required type.
18468
18469     if (VT == MVT::f32 || VT == MVT::i32)
18470       Res.second = &X86::FR32RegClass;
18471     else if (VT == MVT::f64 || VT == MVT::i64)
18472       Res.second = &X86::FR64RegClass;
18473     else if (X86::VR128RegClass.hasType(VT))
18474       Res.second = &X86::VR128RegClass;
18475     else if (X86::VR256RegClass.hasType(VT))
18476       Res.second = &X86::VR256RegClass;
18477   }
18478
18479   return Res;
18480 }