b19f2f66be65c71b45753d39d56bc62c68c6bef6
[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::Other, Expand);
380   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
381   if (Subtarget->is64Bit())
382     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
383   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
384   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
385   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
386   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
387   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
388   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
389   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
390   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
391
392   // Promote the i8 variants and force them on up to i32 which has a shorter
393   // encoding.
394   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
395   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
396   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
397   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
398   if (Subtarget->hasBMI()) {
399     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
400     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
401     if (Subtarget->is64Bit())
402       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
403   } else {
404     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
405     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
406     if (Subtarget->is64Bit())
407       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
408   }
409
410   if (Subtarget->hasLZCNT()) {
411     // When promoting the i8 variants, force them to i32 for a shorter
412     // encoding.
413     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
414     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
415     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
416     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
417     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
418     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
419     if (Subtarget->is64Bit())
420       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
421   } else {
422     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
423     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
424     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
425     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
426     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
427     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
428     if (Subtarget->is64Bit()) {
429       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
430       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
431     }
432   }
433
434   if (Subtarget->hasPOPCNT()) {
435     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
436   } else {
437     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
438     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
439     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
440     if (Subtarget->is64Bit())
441       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
442   }
443
444   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
445   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
446
447   // These should be promoted to a larger select which is supported.
448   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
449   // X86 wants to expand cmov itself.
450   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
451   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
452   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
453   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
454   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
455   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
456   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
457   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
458   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
459   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
460   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
461   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
462   if (Subtarget->is64Bit()) {
463     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
464     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
465   }
466   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
467   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
468   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
469   // support continuation, user-level threading, and etc.. As a result, no
470   // other SjLj exception interfaces are implemented and please don't build
471   // your own exception handling based on them.
472   // LLVM/Clang supports zero-cost DWARF exception handling.
473   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
474   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
475
476   // Darwin ABI issue.
477   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
478   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
479   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
480   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
481   if (Subtarget->is64Bit())
482     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
483   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
484   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
485   if (Subtarget->is64Bit()) {
486     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
487     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
488     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
489     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
490     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
491   }
492   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
493   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
494   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
495   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
496   if (Subtarget->is64Bit()) {
497     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
498     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
499     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
500   }
501
502   if (Subtarget->hasSSE1())
503     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
504
505   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
506   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
507
508   // On X86 and X86-64, atomic operations are lowered to locked instructions.
509   // Locked instructions, in turn, have implicit fence semantics (all memory
510   // operations are flushed before issuing the locked instruction, and they
511   // are not buffered), so we can fold away the common pattern of
512   // fence-atomic-fence.
513   setShouldFoldAtomicFences(true);
514
515   // Expand certain atomics
516   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
517     MVT VT = IntVTs[i];
518     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
519     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
520     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
521   }
522
523   if (!Subtarget->is64Bit()) {
524     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
525     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
526     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
527     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
528     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
529     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
530     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
531     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
532     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
533     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
534     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
535     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
536   }
537
538   if (Subtarget->hasCmpxchg16b()) {
539     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
540   }
541
542   // FIXME - use subtarget debug flags
543   if (!Subtarget->isTargetDarwin() &&
544       !Subtarget->isTargetELF() &&
545       !Subtarget->isTargetCygMing()) {
546     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
547   }
548
549   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
550   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
551   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
552   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
553   if (Subtarget->is64Bit()) {
554     setExceptionPointerRegister(X86::RAX);
555     setExceptionSelectorRegister(X86::RDX);
556   } else {
557     setExceptionPointerRegister(X86::EAX);
558     setExceptionSelectorRegister(X86::EDX);
559   }
560   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
561   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
562
563   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
564   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
565
566   setOperationAction(ISD::TRAP, MVT::Other, Legal);
567   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
568
569   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
570   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
571   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
572   if (Subtarget->is64Bit()) {
573     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
574     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
575   } else {
576     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
577     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
578   }
579
580   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
581   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
582
583   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
584     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
585                        MVT::i64 : MVT::i32, Custom);
586   else if (TM.Options.EnableSegmentedStacks)
587     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
588                        MVT::i64 : MVT::i32, Custom);
589   else
590     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
591                        MVT::i64 : MVT::i32, Expand);
592
593   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
594     // f32 and f64 use SSE.
595     // Set up the FP register classes.
596     addRegisterClass(MVT::f32, &X86::FR32RegClass);
597     addRegisterClass(MVT::f64, &X86::FR64RegClass);
598
599     // Use ANDPD to simulate FABS.
600     setOperationAction(ISD::FABS , MVT::f64, Custom);
601     setOperationAction(ISD::FABS , MVT::f32, Custom);
602
603     // Use XORP to simulate FNEG.
604     setOperationAction(ISD::FNEG , MVT::f64, Custom);
605     setOperationAction(ISD::FNEG , MVT::f32, Custom);
606
607     // Use ANDPD and ORPD to simulate FCOPYSIGN.
608     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
609     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
610
611     // Lower this to FGETSIGNx86 plus an AND.
612     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
613     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
614
615     // We don't support sin/cos/fmod
616     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
617     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
618     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
619     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
620     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
621     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
622
623     // Expand FP immediates into loads from the stack, except for the special
624     // cases we handle.
625     addLegalFPImmediate(APFloat(+0.0)); // xorpd
626     addLegalFPImmediate(APFloat(+0.0f)); // xorps
627   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
628     // Use SSE for f32, x87 for f64.
629     // Set up the FP register classes.
630     addRegisterClass(MVT::f32, &X86::FR32RegClass);
631     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
632
633     // Use ANDPS to simulate FABS.
634     setOperationAction(ISD::FABS , MVT::f32, Custom);
635
636     // Use XORP to simulate FNEG.
637     setOperationAction(ISD::FNEG , MVT::f32, Custom);
638
639     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
640
641     // Use ANDPS and ORPS to simulate FCOPYSIGN.
642     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
643     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
644
645     // We don't support sin/cos/fmod
646     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
647     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
648     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
649
650     // Special cases we handle for FP constants.
651     addLegalFPImmediate(APFloat(+0.0f)); // xorps
652     addLegalFPImmediate(APFloat(+0.0)); // FLD0
653     addLegalFPImmediate(APFloat(+1.0)); // FLD1
654     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
655     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
656
657     if (!TM.Options.UnsafeFPMath) {
658       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
659       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
660       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
661     }
662   } else if (!TM.Options.UseSoftFloat) {
663     // f32 and f64 in x87.
664     // Set up the FP register classes.
665     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
666     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
667
668     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
669     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
670     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
671     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
672
673     if (!TM.Options.UnsafeFPMath) {
674       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
675       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
676       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
677       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
678       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
679       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
680     }
681     addLegalFPImmediate(APFloat(+0.0)); // FLD0
682     addLegalFPImmediate(APFloat(+1.0)); // FLD1
683     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
684     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
685     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
686     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
687     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
688     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
689   }
690
691   // We don't support FMA.
692   setOperationAction(ISD::FMA, MVT::f64, Expand);
693   setOperationAction(ISD::FMA, MVT::f32, Expand);
694
695   // Long double always uses X87.
696   if (!TM.Options.UseSoftFloat) {
697     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
698     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
699     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
700     {
701       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
702       addLegalFPImmediate(TmpFlt);  // FLD0
703       TmpFlt.changeSign();
704       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
705
706       bool ignored;
707       APFloat TmpFlt2(+1.0);
708       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
709                       &ignored);
710       addLegalFPImmediate(TmpFlt2);  // FLD1
711       TmpFlt2.changeSign();
712       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
713     }
714
715     if (!TM.Options.UnsafeFPMath) {
716       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
717       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
718       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
719     }
720
721     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
722     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
723     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
724     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
725     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
726     setOperationAction(ISD::FMA, MVT::f80, Expand);
727   }
728
729   // Always use a library call for pow.
730   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
731   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
732   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
733
734   setOperationAction(ISD::FLOG, MVT::f80, Expand);
735   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
736   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
737   setOperationAction(ISD::FEXP, MVT::f80, Expand);
738   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
739
740   // First set operation action for all vector types to either promote
741   // (for widening) or expand (for scalarization). Then we will selectively
742   // turn on ones that can be effectively codegen'd.
743   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
744            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
745     MVT VT = (MVT::SimpleValueType)i;
746     setOperationAction(ISD::ADD , VT, Expand);
747     setOperationAction(ISD::SUB , VT, Expand);
748     setOperationAction(ISD::FADD, VT, Expand);
749     setOperationAction(ISD::FNEG, VT, Expand);
750     setOperationAction(ISD::FSUB, VT, Expand);
751     setOperationAction(ISD::MUL , VT, Expand);
752     setOperationAction(ISD::FMUL, VT, Expand);
753     setOperationAction(ISD::SDIV, VT, Expand);
754     setOperationAction(ISD::UDIV, VT, Expand);
755     setOperationAction(ISD::FDIV, VT, Expand);
756     setOperationAction(ISD::SREM, VT, Expand);
757     setOperationAction(ISD::UREM, VT, Expand);
758     setOperationAction(ISD::LOAD, VT, Expand);
759     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
760     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
761     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
762     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
763     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
764     setOperationAction(ISD::FABS, VT, Expand);
765     setOperationAction(ISD::FSIN, VT, Expand);
766     setOperationAction(ISD::FSINCOS, VT, Expand);
767     setOperationAction(ISD::FCOS, VT, Expand);
768     setOperationAction(ISD::FSINCOS, VT, Expand);
769     setOperationAction(ISD::FREM, VT, Expand);
770     setOperationAction(ISD::FMA,  VT, Expand);
771     setOperationAction(ISD::FPOWI, VT, Expand);
772     setOperationAction(ISD::FSQRT, VT, Expand);
773     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
774     setOperationAction(ISD::FFLOOR, VT, Expand);
775     setOperationAction(ISD::FCEIL, VT, Expand);
776     setOperationAction(ISD::FTRUNC, VT, Expand);
777     setOperationAction(ISD::FRINT, VT, Expand);
778     setOperationAction(ISD::FNEARBYINT, VT, Expand);
779     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
780     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
781     setOperationAction(ISD::SDIVREM, VT, Expand);
782     setOperationAction(ISD::UDIVREM, VT, Expand);
783     setOperationAction(ISD::FPOW, VT, Expand);
784     setOperationAction(ISD::CTPOP, VT, Expand);
785     setOperationAction(ISD::CTTZ, VT, Expand);
786     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
787     setOperationAction(ISD::CTLZ, VT, Expand);
788     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
789     setOperationAction(ISD::SHL, VT, Expand);
790     setOperationAction(ISD::SRA, VT, Expand);
791     setOperationAction(ISD::SRL, VT, Expand);
792     setOperationAction(ISD::ROTL, VT, Expand);
793     setOperationAction(ISD::ROTR, VT, Expand);
794     setOperationAction(ISD::BSWAP, VT, Expand);
795     setOperationAction(ISD::SETCC, VT, Expand);
796     setOperationAction(ISD::FLOG, VT, Expand);
797     setOperationAction(ISD::FLOG2, VT, Expand);
798     setOperationAction(ISD::FLOG10, VT, Expand);
799     setOperationAction(ISD::FEXP, VT, Expand);
800     setOperationAction(ISD::FEXP2, VT, Expand);
801     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
802     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
803     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
804     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
805     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
806     setOperationAction(ISD::TRUNCATE, VT, Expand);
807     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
808     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
809     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
810     setOperationAction(ISD::VSELECT, VT, Expand);
811     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
812              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
813       setTruncStoreAction(VT,
814                           (MVT::SimpleValueType)InnerVT, Expand);
815     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
816     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
817     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
818   }
819
820   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
821   // with -msoft-float, disable use of MMX as well.
822   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
823     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
824     // No operations on x86mmx supported, everything uses intrinsics.
825   }
826
827   // MMX-sized vectors (other than x86mmx) are expected to be expanded
828   // into smaller operations.
829   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
830   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
831   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
832   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
833   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
834   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
835   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
836   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
837   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
838   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
839   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
840   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
841   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
842   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
843   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
844   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
845   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
846   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
847   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
848   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
849   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
850   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
851   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
852   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
853   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
854   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
855   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
856   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
857   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
858
859   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
860     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
861
862     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
863     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
864     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
865     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
866     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
867     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
868     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
869     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
870     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
871     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
872     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
873     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
874   }
875
876   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
877     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
878
879     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
880     // registers cannot be used even for integer operations.
881     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
882     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
883     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
884     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
885
886     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
887     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
888     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
889     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
890     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
891     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
892     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
893     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
894     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
895     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
896     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
897     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
898     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
899     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
900     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
901     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
902     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
903     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
904
905     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
906     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
907     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
908     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
909
910     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
911     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
912     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
913     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
914     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
915
916     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
917     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
918       MVT VT = (MVT::SimpleValueType)i;
919       // Do not attempt to custom lower non-power-of-2 vectors
920       if (!isPowerOf2_32(VT.getVectorNumElements()))
921         continue;
922       // Do not attempt to custom lower non-128-bit vectors
923       if (!VT.is128BitVector())
924         continue;
925       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
926       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
927       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
928     }
929
930     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
931     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
932     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
933     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
934     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
935     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
936
937     if (Subtarget->is64Bit()) {
938       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
939       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
940     }
941
942     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
943     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
944       MVT VT = (MVT::SimpleValueType)i;
945
946       // Do not attempt to promote non-128-bit vectors
947       if (!VT.is128BitVector())
948         continue;
949
950       setOperationAction(ISD::AND,    VT, Promote);
951       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
952       setOperationAction(ISD::OR,     VT, Promote);
953       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
954       setOperationAction(ISD::XOR,    VT, Promote);
955       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
956       setOperationAction(ISD::LOAD,   VT, Promote);
957       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
958       setOperationAction(ISD::SELECT, VT, Promote);
959       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
960     }
961
962     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
963
964     // Custom lower v2i64 and v2f64 selects.
965     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
966     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
967     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
968     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
969
970     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
971     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
972
973     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
974     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
975     // As there is no 64-bit GPR available, we need build a special custom
976     // sequence to convert from v2i32 to v2f32.
977     if (!Subtarget->is64Bit())
978       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
979
980     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
981     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
982
983     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
984   }
985
986   if (Subtarget->hasSSE41()) {
987     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
988     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
989     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
990     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
991     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
992     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
993     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
994     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
995     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
996     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
997
998     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
999     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1000     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1001     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1002     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1003     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1004     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1005     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1006     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1007     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1008
1009     // FIXME: Do we need to handle scalar-to-vector here?
1010     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1011
1012     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1013     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1014     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1015     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1016     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1017
1018     // i8 and i16 vectors are custom , because the source register and source
1019     // source memory operand types are not the same width.  f32 vectors are
1020     // custom since the immediate controlling the insert encodes additional
1021     // information.
1022     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1023     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1024     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1025     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1026
1027     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1028     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1029     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1030     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1031
1032     // FIXME: these should be Legal but thats only for the case where
1033     // the index is constant.  For now custom expand to deal with that.
1034     if (Subtarget->is64Bit()) {
1035       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1036       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1037     }
1038   }
1039
1040   if (Subtarget->hasSSE2()) {
1041     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1042     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1043
1044     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1045     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1046
1047     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1048     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1049
1050     if (Subtarget->hasInt256()) {
1051       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
1052       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
1053
1054       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
1055       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
1056
1057       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
1058     } else {
1059       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
1060       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
1061
1062       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
1063       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
1064
1065       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
1066     }
1067     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1068     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1069   }
1070
1071   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1072     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1073     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1074     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1075     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1076     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1077     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1078
1079     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1080     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1081     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1082
1083     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1084     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1085     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1086     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1087     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1088     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1089     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1090     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1091     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1092     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1093     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1094     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1095
1096     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1097     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1098     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1099     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1100     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1101     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1102     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1103     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1104     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1105     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1106     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1107     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1108
1109     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1110     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1111
1112     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1113
1114     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1115     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1116     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1117
1118     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1120     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1121
1122     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1123
1124     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1125     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1126
1127     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1128     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1129
1130     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1131     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1132
1133     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1134
1135     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1136     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1137     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1138     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1139
1140     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1141     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1142     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1143
1144     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1145     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1146     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1147     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1148
1149     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1150     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1151     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1152     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1153     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1154     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1155
1156     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1157       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1158       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1159       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1160       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1161       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1162       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1163     }
1164
1165     if (Subtarget->hasInt256()) {
1166       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1167       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1168       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1169       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1170
1171       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1172       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1173       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1174       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1175
1176       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1177       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1178       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1179       // Don't lower v32i8 because there is no 128-bit byte mul
1180
1181       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1182
1183       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1184       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1185
1186       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1187       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1188
1189       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1190
1191       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1192     } else {
1193       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1195       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1197
1198       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1200       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1202
1203       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1205       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1206       // Don't lower v32i8 because there is no 128-bit byte mul
1207
1208       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1209       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1210
1211       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1212       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1213
1214       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1215     }
1216
1217     // Custom lower several nodes for 256-bit types.
1218     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1219              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1220       MVT VT = (MVT::SimpleValueType)i;
1221
1222       // Extract subvector is special because the value type
1223       // (result) is 128-bit but the source is 256-bit wide.
1224       if (VT.is128BitVector())
1225         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1226
1227       // Do not attempt to custom lower other non-256-bit vectors
1228       if (!VT.is256BitVector())
1229         continue;
1230
1231       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1232       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1233       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1234       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1235       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1236       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1237       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1238     }
1239
1240     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1241     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1242       MVT VT = (MVT::SimpleValueType)i;
1243
1244       // Do not attempt to promote non-256-bit vectors
1245       if (!VT.is256BitVector())
1246         continue;
1247
1248       setOperationAction(ISD::AND,    VT, Promote);
1249       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1250       setOperationAction(ISD::OR,     VT, Promote);
1251       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1252       setOperationAction(ISD::XOR,    VT, Promote);
1253       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1254       setOperationAction(ISD::LOAD,   VT, Promote);
1255       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1256       setOperationAction(ISD::SELECT, VT, Promote);
1257       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1258     }
1259   }
1260
1261   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1262   // of this type with custom code.
1263   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1264            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1265     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1266                        Custom);
1267   }
1268
1269   // We want to custom lower some of our intrinsics.
1270   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1271   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1272
1273   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1274   // handle type legalization for these operations here.
1275   //
1276   // FIXME: We really should do custom legalization for addition and
1277   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1278   // than generic legalization for 64-bit multiplication-with-overflow, though.
1279   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1280     // Add/Sub/Mul with overflow operations are custom lowered.
1281     MVT VT = IntVTs[i];
1282     setOperationAction(ISD::SADDO, VT, Custom);
1283     setOperationAction(ISD::UADDO, VT, Custom);
1284     setOperationAction(ISD::SSUBO, VT, Custom);
1285     setOperationAction(ISD::USUBO, VT, Custom);
1286     setOperationAction(ISD::SMULO, VT, Custom);
1287     setOperationAction(ISD::UMULO, VT, Custom);
1288   }
1289
1290   // There are no 8-bit 3-address imul/mul instructions
1291   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1292   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1293
1294   if (!Subtarget->is64Bit()) {
1295     // These libcalls are not available in 32-bit.
1296     setLibcallName(RTLIB::SHL_I128, 0);
1297     setLibcallName(RTLIB::SRL_I128, 0);
1298     setLibcallName(RTLIB::SRA_I128, 0);
1299   }
1300
1301   // Combine sin / cos into one node or libcall if possible.
1302   if (Subtarget->hasSinCos()) {
1303     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1304     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1305     if (Subtarget->isTargetDarwin()) {
1306       // For MacOSX, we don't want to the normal expansion of a libcall to
1307       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1308       // traffic.
1309       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1310       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1311     }
1312   }
1313
1314   // We have target-specific dag combine patterns for the following nodes:
1315   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1316   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1317   setTargetDAGCombine(ISD::VSELECT);
1318   setTargetDAGCombine(ISD::SELECT);
1319   setTargetDAGCombine(ISD::SHL);
1320   setTargetDAGCombine(ISD::SRA);
1321   setTargetDAGCombine(ISD::SRL);
1322   setTargetDAGCombine(ISD::OR);
1323   setTargetDAGCombine(ISD::AND);
1324   setTargetDAGCombine(ISD::ADD);
1325   setTargetDAGCombine(ISD::FADD);
1326   setTargetDAGCombine(ISD::FSUB);
1327   setTargetDAGCombine(ISD::FMA);
1328   setTargetDAGCombine(ISD::SUB);
1329   setTargetDAGCombine(ISD::LOAD);
1330   setTargetDAGCombine(ISD::STORE);
1331   setTargetDAGCombine(ISD::ZERO_EXTEND);
1332   setTargetDAGCombine(ISD::ANY_EXTEND);
1333   setTargetDAGCombine(ISD::SIGN_EXTEND);
1334   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1335   setTargetDAGCombine(ISD::TRUNCATE);
1336   setTargetDAGCombine(ISD::SINT_TO_FP);
1337   setTargetDAGCombine(ISD::SETCC);
1338   if (Subtarget->is64Bit())
1339     setTargetDAGCombine(ISD::MUL);
1340   setTargetDAGCombine(ISD::XOR);
1341
1342   computeRegisterProperties();
1343
1344   // On Darwin, -Os means optimize for size without hurting performance,
1345   // do not reduce the limit.
1346   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1347   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1348   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1349   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1350   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1351   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1352   setPrefLoopAlignment(4); // 2^4 bytes.
1353   BenefitFromCodePlacementOpt = true;
1354
1355   // Predictable cmov don't hurt on atom because it's in-order.
1356   PredictableSelectIsExpensive = !Subtarget->isAtom();
1357
1358   setPrefFunctionAlignment(4); // 2^4 bytes.
1359 }
1360
1361 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1362   if (!VT.isVector()) return MVT::i8;
1363   return VT.changeVectorElementTypeToInteger();
1364 }
1365
1366 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1367 /// the desired ByVal argument alignment.
1368 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1369   if (MaxAlign == 16)
1370     return;
1371   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1372     if (VTy->getBitWidth() == 128)
1373       MaxAlign = 16;
1374   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1375     unsigned EltAlign = 0;
1376     getMaxByValAlign(ATy->getElementType(), EltAlign);
1377     if (EltAlign > MaxAlign)
1378       MaxAlign = EltAlign;
1379   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1380     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1381       unsigned EltAlign = 0;
1382       getMaxByValAlign(STy->getElementType(i), EltAlign);
1383       if (EltAlign > MaxAlign)
1384         MaxAlign = EltAlign;
1385       if (MaxAlign == 16)
1386         break;
1387     }
1388   }
1389 }
1390
1391 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1392 /// function arguments in the caller parameter area. For X86, aggregates
1393 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1394 /// are at 4-byte boundaries.
1395 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1396   if (Subtarget->is64Bit()) {
1397     // Max of 8 and alignment of type.
1398     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1399     if (TyAlign > 8)
1400       return TyAlign;
1401     return 8;
1402   }
1403
1404   unsigned Align = 4;
1405   if (Subtarget->hasSSE1())
1406     getMaxByValAlign(Ty, Align);
1407   return Align;
1408 }
1409
1410 /// getOptimalMemOpType - Returns the target specific optimal type for load
1411 /// and store operations as a result of memset, memcpy, and memmove
1412 /// lowering. If DstAlign is zero that means it's safe to destination
1413 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1414 /// means there isn't a need to check it against alignment requirement,
1415 /// probably because the source does not need to be loaded. If 'IsMemset' is
1416 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1417 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1418 /// source is constant so it does not need to be loaded.
1419 /// It returns EVT::Other if the type should be determined using generic
1420 /// target-independent logic.
1421 EVT
1422 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1423                                        unsigned DstAlign, unsigned SrcAlign,
1424                                        bool IsMemset, bool ZeroMemset,
1425                                        bool MemcpyStrSrc,
1426                                        MachineFunction &MF) const {
1427   const Function *F = MF.getFunction();
1428   if ((!IsMemset || ZeroMemset) &&
1429       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1430                                        Attribute::NoImplicitFloat)) {
1431     if (Size >= 16 &&
1432         (Subtarget->isUnalignedMemAccessFast() ||
1433          ((DstAlign == 0 || DstAlign >= 16) &&
1434           (SrcAlign == 0 || SrcAlign >= 16)))) {
1435       if (Size >= 32) {
1436         if (Subtarget->hasInt256())
1437           return MVT::v8i32;
1438         if (Subtarget->hasFp256())
1439           return MVT::v8f32;
1440       }
1441       if (Subtarget->hasSSE2())
1442         return MVT::v4i32;
1443       if (Subtarget->hasSSE1())
1444         return MVT::v4f32;
1445     } else if (!MemcpyStrSrc && Size >= 8 &&
1446                !Subtarget->is64Bit() &&
1447                Subtarget->hasSSE2()) {
1448       // Do not use f64 to lower memcpy if source is string constant. It's
1449       // better to use i32 to avoid the loads.
1450       return MVT::f64;
1451     }
1452   }
1453   if (Subtarget->is64Bit() && Size >= 8)
1454     return MVT::i64;
1455   return MVT::i32;
1456 }
1457
1458 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1459   if (VT == MVT::f32)
1460     return X86ScalarSSEf32;
1461   else if (VT == MVT::f64)
1462     return X86ScalarSSEf64;
1463   return true;
1464 }
1465
1466 bool
1467 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1468   if (Fast)
1469     *Fast = Subtarget->isUnalignedMemAccessFast();
1470   return true;
1471 }
1472
1473 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1474 /// current function.  The returned value is a member of the
1475 /// MachineJumpTableInfo::JTEntryKind enum.
1476 unsigned X86TargetLowering::getJumpTableEncoding() const {
1477   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1478   // symbol.
1479   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1480       Subtarget->isPICStyleGOT())
1481     return MachineJumpTableInfo::EK_Custom32;
1482
1483   // Otherwise, use the normal jump table encoding heuristics.
1484   return TargetLowering::getJumpTableEncoding();
1485 }
1486
1487 const MCExpr *
1488 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1489                                              const MachineBasicBlock *MBB,
1490                                              unsigned uid,MCContext &Ctx) const{
1491   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1492          Subtarget->isPICStyleGOT());
1493   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1494   // entries.
1495   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1496                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1497 }
1498
1499 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1500 /// jumptable.
1501 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1502                                                     SelectionDAG &DAG) const {
1503   if (!Subtarget->is64Bit())
1504     // This doesn't have DebugLoc associated with it, but is not really the
1505     // same as a Register.
1506     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1507   return Table;
1508 }
1509
1510 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1511 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1512 /// MCExpr.
1513 const MCExpr *X86TargetLowering::
1514 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1515                              MCContext &Ctx) const {
1516   // X86-64 uses RIP relative addressing based on the jump table label.
1517   if (Subtarget->isPICStyleRIPRel())
1518     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1519
1520   // Otherwise, the reference is relative to the PIC base.
1521   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1522 }
1523
1524 // FIXME: Why this routine is here? Move to RegInfo!
1525 std::pair<const TargetRegisterClass*, uint8_t>
1526 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1527   const TargetRegisterClass *RRC = 0;
1528   uint8_t Cost = 1;
1529   switch (VT.SimpleTy) {
1530   default:
1531     return TargetLowering::findRepresentativeClass(VT);
1532   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1533     RRC = Subtarget->is64Bit() ?
1534       (const TargetRegisterClass*)&X86::GR64RegClass :
1535       (const TargetRegisterClass*)&X86::GR32RegClass;
1536     break;
1537   case MVT::x86mmx:
1538     RRC = &X86::VR64RegClass;
1539     break;
1540   case MVT::f32: case MVT::f64:
1541   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1542   case MVT::v4f32: case MVT::v2f64:
1543   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1544   case MVT::v4f64:
1545     RRC = &X86::VR128RegClass;
1546     break;
1547   }
1548   return std::make_pair(RRC, Cost);
1549 }
1550
1551 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1552                                                unsigned &Offset) const {
1553   if (!Subtarget->isTargetLinux())
1554     return false;
1555
1556   if (Subtarget->is64Bit()) {
1557     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1558     Offset = 0x28;
1559     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1560       AddressSpace = 256;
1561     else
1562       AddressSpace = 257;
1563   } else {
1564     // %gs:0x14 on i386
1565     Offset = 0x14;
1566     AddressSpace = 256;
1567   }
1568   return true;
1569 }
1570
1571 //===----------------------------------------------------------------------===//
1572 //               Return Value Calling Convention Implementation
1573 //===----------------------------------------------------------------------===//
1574
1575 #include "X86GenCallingConv.inc"
1576
1577 bool
1578 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1579                                   MachineFunction &MF, bool isVarArg,
1580                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1581                         LLVMContext &Context) const {
1582   SmallVector<CCValAssign, 16> RVLocs;
1583   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1584                  RVLocs, Context);
1585   return CCInfo.CheckReturn(Outs, RetCC_X86);
1586 }
1587
1588 SDValue
1589 X86TargetLowering::LowerReturn(SDValue Chain,
1590                                CallingConv::ID CallConv, bool isVarArg,
1591                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1592                                const SmallVectorImpl<SDValue> &OutVals,
1593                                DebugLoc dl, SelectionDAG &DAG) const {
1594   MachineFunction &MF = DAG.getMachineFunction();
1595   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1596
1597   SmallVector<CCValAssign, 16> RVLocs;
1598   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1599                  RVLocs, *DAG.getContext());
1600   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1601
1602   SDValue Flag;
1603   SmallVector<SDValue, 6> RetOps;
1604   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1605   // Operand #1 = Bytes To Pop
1606   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1607                    MVT::i16));
1608
1609   // Copy the result values into the output registers.
1610   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1611     CCValAssign &VA = RVLocs[i];
1612     assert(VA.isRegLoc() && "Can only return in registers!");
1613     SDValue ValToCopy = OutVals[i];
1614     EVT ValVT = ValToCopy.getValueType();
1615
1616     // Promote values to the appropriate types
1617     if (VA.getLocInfo() == CCValAssign::SExt)
1618       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1619     else if (VA.getLocInfo() == CCValAssign::ZExt)
1620       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1621     else if (VA.getLocInfo() == CCValAssign::AExt)
1622       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1623     else if (VA.getLocInfo() == CCValAssign::BCvt)
1624       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1625
1626     // If this is x86-64, and we disabled SSE, we can't return FP values,
1627     // or SSE or MMX vectors.
1628     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1629          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1630           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1631       report_fatal_error("SSE register return with SSE disabled");
1632     }
1633     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1634     // llvm-gcc has never done it right and no one has noticed, so this
1635     // should be OK for now.
1636     if (ValVT == MVT::f64 &&
1637         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1638       report_fatal_error("SSE2 register return with SSE2 disabled");
1639
1640     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1641     // the RET instruction and handled by the FP Stackifier.
1642     if (VA.getLocReg() == X86::ST0 ||
1643         VA.getLocReg() == X86::ST1) {
1644       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1645       // change the value to the FP stack register class.
1646       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1647         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1648       RetOps.push_back(ValToCopy);
1649       // Don't emit a copytoreg.
1650       continue;
1651     }
1652
1653     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1654     // which is returned in RAX / RDX.
1655     if (Subtarget->is64Bit()) {
1656       if (ValVT == MVT::x86mmx) {
1657         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1658           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1659           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1660                                   ValToCopy);
1661           // If we don't have SSE2 available, convert to v4f32 so the generated
1662           // register is legal.
1663           if (!Subtarget->hasSSE2())
1664             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1665         }
1666       }
1667     }
1668
1669     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1670     Flag = Chain.getValue(1);
1671     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1672   }
1673
1674   // The x86-64 ABIs require that for returning structs by value we copy
1675   // the sret argument into %rax/%eax (depending on ABI) for the return.
1676   // We saved the argument into a virtual register in the entry block,
1677   // so now we copy the value out and into %rax/%eax.
1678   if (Subtarget->is64Bit() &&
1679       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1680     MachineFunction &MF = DAG.getMachineFunction();
1681     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1682     unsigned Reg = FuncInfo->getSRetReturnReg();
1683     assert(Reg &&
1684            "SRetReturnReg should have been set in LowerFormalArguments().");
1685     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1686
1687     unsigned RetValReg = Subtarget->isTarget64BitILP32() ? X86::EAX : X86::RAX;
1688     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1689     Flag = Chain.getValue(1);
1690
1691     // RAX/EAX now acts like a return value.
1692     RetOps.push_back(DAG.getRegister(RetValReg, MVT::i64));
1693   }
1694
1695   RetOps[0] = Chain;  // Update chain.
1696
1697   // Add the flag if we have it.
1698   if (Flag.getNode())
1699     RetOps.push_back(Flag);
1700
1701   return DAG.getNode(X86ISD::RET_FLAG, dl,
1702                      MVT::Other, &RetOps[0], RetOps.size());
1703 }
1704
1705 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1706   if (N->getNumValues() != 1)
1707     return false;
1708   if (!N->hasNUsesOfValue(1, 0))
1709     return false;
1710
1711   SDValue TCChain = Chain;
1712   SDNode *Copy = *N->use_begin();
1713   if (Copy->getOpcode() == ISD::CopyToReg) {
1714     // If the copy has a glue operand, we conservatively assume it isn't safe to
1715     // perform a tail call.
1716     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1717       return false;
1718     TCChain = Copy->getOperand(0);
1719   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1720     return false;
1721
1722   bool HasRet = false;
1723   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1724        UI != UE; ++UI) {
1725     if (UI->getOpcode() != X86ISD::RET_FLAG)
1726       return false;
1727     HasRet = true;
1728   }
1729
1730   if (!HasRet)
1731     return false;
1732
1733   Chain = TCChain;
1734   return true;
1735 }
1736
1737 MVT
1738 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1739                                             ISD::NodeType ExtendKind) const {
1740   MVT ReturnMVT;
1741   // TODO: Is this also valid on 32-bit?
1742   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1743     ReturnMVT = MVT::i8;
1744   else
1745     ReturnMVT = MVT::i32;
1746
1747   MVT MinVT = getRegisterType(ReturnMVT);
1748   return VT.bitsLT(MinVT) ? MinVT : VT;
1749 }
1750
1751 /// LowerCallResult - Lower the result values of a call into the
1752 /// appropriate copies out of appropriate physical registers.
1753 ///
1754 SDValue
1755 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1756                                    CallingConv::ID CallConv, bool isVarArg,
1757                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1758                                    DebugLoc dl, SelectionDAG &DAG,
1759                                    SmallVectorImpl<SDValue> &InVals) const {
1760
1761   // Assign locations to each value returned by this call.
1762   SmallVector<CCValAssign, 16> RVLocs;
1763   bool Is64Bit = Subtarget->is64Bit();
1764   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1765                  getTargetMachine(), RVLocs, *DAG.getContext());
1766   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1767
1768   // Copy all of the result registers out of their specified physreg.
1769   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1770     CCValAssign &VA = RVLocs[i];
1771     EVT CopyVT = VA.getValVT();
1772
1773     // If this is x86-64, and we disabled SSE, we can't return FP values
1774     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1775         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1776       report_fatal_error("SSE register return with SSE disabled");
1777     }
1778
1779     SDValue Val;
1780
1781     // If this is a call to a function that returns an fp value on the floating
1782     // point stack, we must guarantee the value is popped from the stack, so
1783     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1784     // if the return value is not used. We use the FpPOP_RETVAL instruction
1785     // instead.
1786     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1787       // If we prefer to use the value in xmm registers, copy it out as f80 and
1788       // use a truncate to move it from fp stack reg to xmm reg.
1789       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1790       SDValue Ops[] = { Chain, InFlag };
1791       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1792                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1793       Val = Chain.getValue(0);
1794
1795       // Round the f80 to the right size, which also moves it to the appropriate
1796       // xmm register.
1797       if (CopyVT != VA.getValVT())
1798         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1799                           // This truncation won't change the value.
1800                           DAG.getIntPtrConstant(1));
1801     } else {
1802       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1803                                  CopyVT, InFlag).getValue(1);
1804       Val = Chain.getValue(0);
1805     }
1806     InFlag = Chain.getValue(2);
1807     InVals.push_back(Val);
1808   }
1809
1810   return Chain;
1811 }
1812
1813 //===----------------------------------------------------------------------===//
1814 //                C & StdCall & Fast Calling Convention implementation
1815 //===----------------------------------------------------------------------===//
1816 //  StdCall calling convention seems to be standard for many Windows' API
1817 //  routines and around. It differs from C calling convention just a little:
1818 //  callee should clean up the stack, not caller. Symbols should be also
1819 //  decorated in some fancy way :) It doesn't support any vector arguments.
1820 //  For info on fast calling convention see Fast Calling Convention (tail call)
1821 //  implementation LowerX86_32FastCCCallTo.
1822
1823 /// CallIsStructReturn - Determines whether a call uses struct return
1824 /// semantics.
1825 enum StructReturnType {
1826   NotStructReturn,
1827   RegStructReturn,
1828   StackStructReturn
1829 };
1830 static StructReturnType
1831 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1832   if (Outs.empty())
1833     return NotStructReturn;
1834
1835   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1836   if (!Flags.isSRet())
1837     return NotStructReturn;
1838   if (Flags.isInReg())
1839     return RegStructReturn;
1840   return StackStructReturn;
1841 }
1842
1843 /// ArgsAreStructReturn - Determines whether a function uses struct
1844 /// return semantics.
1845 static StructReturnType
1846 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1847   if (Ins.empty())
1848     return NotStructReturn;
1849
1850   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1851   if (!Flags.isSRet())
1852     return NotStructReturn;
1853   if (Flags.isInReg())
1854     return RegStructReturn;
1855   return StackStructReturn;
1856 }
1857
1858 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1859 /// by "Src" to address "Dst" with size and alignment information specified by
1860 /// the specific parameter attribute. The copy will be passed as a byval
1861 /// function parameter.
1862 static SDValue
1863 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1864                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1865                           DebugLoc dl) {
1866   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1867
1868   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1869                        /*isVolatile*/false, /*AlwaysInline=*/true,
1870                        MachinePointerInfo(), MachinePointerInfo());
1871 }
1872
1873 /// IsTailCallConvention - Return true if the calling convention is one that
1874 /// supports tail call optimization.
1875 static bool IsTailCallConvention(CallingConv::ID CC) {
1876   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1877           CC == CallingConv::HiPE);
1878 }
1879
1880 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1881   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1882     return false;
1883
1884   CallSite CS(CI);
1885   CallingConv::ID CalleeCC = CS.getCallingConv();
1886   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1887     return false;
1888
1889   return true;
1890 }
1891
1892 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1893 /// a tailcall target by changing its ABI.
1894 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1895                                    bool GuaranteedTailCallOpt) {
1896   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1897 }
1898
1899 SDValue
1900 X86TargetLowering::LowerMemArgument(SDValue Chain,
1901                                     CallingConv::ID CallConv,
1902                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1903                                     DebugLoc dl, SelectionDAG &DAG,
1904                                     const CCValAssign &VA,
1905                                     MachineFrameInfo *MFI,
1906                                     unsigned i) const {
1907   // Create the nodes corresponding to a load from this parameter slot.
1908   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1909   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1910                               getTargetMachine().Options.GuaranteedTailCallOpt);
1911   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1912   EVT ValVT;
1913
1914   // If value is passed by pointer we have address passed instead of the value
1915   // itself.
1916   if (VA.getLocInfo() == CCValAssign::Indirect)
1917     ValVT = VA.getLocVT();
1918   else
1919     ValVT = VA.getValVT();
1920
1921   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1922   // changed with more analysis.
1923   // In case of tail call optimization mark all arguments mutable. Since they
1924   // could be overwritten by lowering of arguments in case of a tail call.
1925   if (Flags.isByVal()) {
1926     unsigned Bytes = Flags.getByValSize();
1927     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1928     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1929     return DAG.getFrameIndex(FI, getPointerTy());
1930   } else {
1931     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1932                                     VA.getLocMemOffset(), isImmutable);
1933     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1934     return DAG.getLoad(ValVT, dl, Chain, FIN,
1935                        MachinePointerInfo::getFixedStack(FI),
1936                        false, false, false, 0);
1937   }
1938 }
1939
1940 SDValue
1941 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1942                                         CallingConv::ID CallConv,
1943                                         bool isVarArg,
1944                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1945                                         DebugLoc dl,
1946                                         SelectionDAG &DAG,
1947                                         SmallVectorImpl<SDValue> &InVals)
1948                                           const {
1949   MachineFunction &MF = DAG.getMachineFunction();
1950   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1951
1952   const Function* Fn = MF.getFunction();
1953   if (Fn->hasExternalLinkage() &&
1954       Subtarget->isTargetCygMing() &&
1955       Fn->getName() == "main")
1956     FuncInfo->setForceFramePointer(true);
1957
1958   MachineFrameInfo *MFI = MF.getFrameInfo();
1959   bool Is64Bit = Subtarget->is64Bit();
1960   bool IsWindows = Subtarget->isTargetWindows();
1961   bool IsWin64 = Subtarget->isTargetWin64();
1962
1963   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1964          "Var args not supported with calling convention fastcc, ghc or hipe");
1965
1966   // Assign locations to all of the incoming arguments.
1967   SmallVector<CCValAssign, 16> ArgLocs;
1968   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1969                  ArgLocs, *DAG.getContext());
1970
1971   // Allocate shadow area for Win64
1972   if (IsWin64) {
1973     CCInfo.AllocateStack(32, 8);
1974   }
1975
1976   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1977
1978   unsigned LastVal = ~0U;
1979   SDValue ArgValue;
1980   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1981     CCValAssign &VA = ArgLocs[i];
1982     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1983     // places.
1984     assert(VA.getValNo() != LastVal &&
1985            "Don't support value assigned to multiple locs yet");
1986     (void)LastVal;
1987     LastVal = VA.getValNo();
1988
1989     if (VA.isRegLoc()) {
1990       EVT RegVT = VA.getLocVT();
1991       const TargetRegisterClass *RC;
1992       if (RegVT == MVT::i32)
1993         RC = &X86::GR32RegClass;
1994       else if (Is64Bit && RegVT == MVT::i64)
1995         RC = &X86::GR64RegClass;
1996       else if (RegVT == MVT::f32)
1997         RC = &X86::FR32RegClass;
1998       else if (RegVT == MVT::f64)
1999         RC = &X86::FR64RegClass;
2000       else if (RegVT.is256BitVector())
2001         RC = &X86::VR256RegClass;
2002       else if (RegVT.is128BitVector())
2003         RC = &X86::VR128RegClass;
2004       else if (RegVT == MVT::x86mmx)
2005         RC = &X86::VR64RegClass;
2006       else
2007         llvm_unreachable("Unknown argument type!");
2008
2009       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2010       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2011
2012       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2013       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2014       // right size.
2015       if (VA.getLocInfo() == CCValAssign::SExt)
2016         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2017                                DAG.getValueType(VA.getValVT()));
2018       else if (VA.getLocInfo() == CCValAssign::ZExt)
2019         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2020                                DAG.getValueType(VA.getValVT()));
2021       else if (VA.getLocInfo() == CCValAssign::BCvt)
2022         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2023
2024       if (VA.isExtInLoc()) {
2025         // Handle MMX values passed in XMM regs.
2026         if (RegVT.isVector())
2027           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2028         else
2029           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2030       }
2031     } else {
2032       assert(VA.isMemLoc());
2033       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2034     }
2035
2036     // If value is passed via pointer - do a load.
2037     if (VA.getLocInfo() == CCValAssign::Indirect)
2038       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2039                              MachinePointerInfo(), false, false, false, 0);
2040
2041     InVals.push_back(ArgValue);
2042   }
2043
2044   // The x86-64 ABIs require that for returning structs by value we copy
2045   // the sret argument into %rax/%eax (depending on ABI) for the return.
2046   // Save the argument into a virtual register so that we can access it
2047   // from the return points.
2048   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
2049     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2050     unsigned Reg = FuncInfo->getSRetReturnReg();
2051     if (!Reg) {
2052       MVT PtrTy = getPointerTy();
2053       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2054       FuncInfo->setSRetReturnReg(Reg);
2055     }
2056     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2057     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2058   }
2059
2060   unsigned StackSize = CCInfo.getNextStackOffset();
2061   // Align stack specially for tail calls.
2062   if (FuncIsMadeTailCallSafe(CallConv,
2063                              MF.getTarget().Options.GuaranteedTailCallOpt))
2064     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2065
2066   // If the function takes variable number of arguments, make a frame index for
2067   // the start of the first vararg value... for expansion of llvm.va_start.
2068   if (isVarArg) {
2069     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2070                     CallConv != CallingConv::X86_ThisCall)) {
2071       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2072     }
2073     if (Is64Bit) {
2074       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2075
2076       // FIXME: We should really autogenerate these arrays
2077       static const uint16_t GPR64ArgRegsWin64[] = {
2078         X86::RCX, X86::RDX, X86::R8,  X86::R9
2079       };
2080       static const uint16_t GPR64ArgRegs64Bit[] = {
2081         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2082       };
2083       static const uint16_t XMMArgRegs64Bit[] = {
2084         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2085         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2086       };
2087       const uint16_t *GPR64ArgRegs;
2088       unsigned NumXMMRegs = 0;
2089
2090       if (IsWin64) {
2091         // The XMM registers which might contain var arg parameters are shadowed
2092         // in their paired GPR.  So we only need to save the GPR to their home
2093         // slots.
2094         TotalNumIntRegs = 4;
2095         GPR64ArgRegs = GPR64ArgRegsWin64;
2096       } else {
2097         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2098         GPR64ArgRegs = GPR64ArgRegs64Bit;
2099
2100         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2101                                                 TotalNumXMMRegs);
2102       }
2103       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2104                                                        TotalNumIntRegs);
2105
2106       bool NoImplicitFloatOps = Fn->getAttributes().
2107         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2108       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2109              "SSE register cannot be used when SSE is disabled!");
2110       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2111                NoImplicitFloatOps) &&
2112              "SSE register cannot be used when SSE is disabled!");
2113       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2114           !Subtarget->hasSSE1())
2115         // Kernel mode asks for SSE to be disabled, so don't push them
2116         // on the stack.
2117         TotalNumXMMRegs = 0;
2118
2119       if (IsWin64) {
2120         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2121         // Get to the caller-allocated home save location.  Add 8 to account
2122         // for the return address.
2123         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2124         FuncInfo->setRegSaveFrameIndex(
2125           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2126         // Fixup to set vararg frame on shadow area (4 x i64).
2127         if (NumIntRegs < 4)
2128           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2129       } else {
2130         // For X86-64, if there are vararg parameters that are passed via
2131         // registers, then we must store them to their spots on the stack so
2132         // they may be loaded by deferencing the result of va_next.
2133         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2134         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2135         FuncInfo->setRegSaveFrameIndex(
2136           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2137                                false));
2138       }
2139
2140       // Store the integer parameter registers.
2141       SmallVector<SDValue, 8> MemOps;
2142       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2143                                         getPointerTy());
2144       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2145       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2146         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2147                                   DAG.getIntPtrConstant(Offset));
2148         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2149                                      &X86::GR64RegClass);
2150         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2151         SDValue Store =
2152           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2153                        MachinePointerInfo::getFixedStack(
2154                          FuncInfo->getRegSaveFrameIndex(), Offset),
2155                        false, false, 0);
2156         MemOps.push_back(Store);
2157         Offset += 8;
2158       }
2159
2160       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2161         // Now store the XMM (fp + vector) parameter registers.
2162         SmallVector<SDValue, 11> SaveXMMOps;
2163         SaveXMMOps.push_back(Chain);
2164
2165         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2166         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2167         SaveXMMOps.push_back(ALVal);
2168
2169         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2170                                FuncInfo->getRegSaveFrameIndex()));
2171         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2172                                FuncInfo->getVarArgsFPOffset()));
2173
2174         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2175           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2176                                        &X86::VR128RegClass);
2177           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2178           SaveXMMOps.push_back(Val);
2179         }
2180         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2181                                      MVT::Other,
2182                                      &SaveXMMOps[0], SaveXMMOps.size()));
2183       }
2184
2185       if (!MemOps.empty())
2186         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2187                             &MemOps[0], MemOps.size());
2188     }
2189   }
2190
2191   // Some CCs need callee pop.
2192   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2193                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2194     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2195   } else {
2196     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2197     // If this is an sret function, the return should pop the hidden pointer.
2198     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2199         argsAreStructReturn(Ins) == StackStructReturn)
2200       FuncInfo->setBytesToPopOnReturn(4);
2201   }
2202
2203   if (!Is64Bit) {
2204     // RegSaveFrameIndex is X86-64 only.
2205     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2206     if (CallConv == CallingConv::X86_FastCall ||
2207         CallConv == CallingConv::X86_ThisCall)
2208       // fastcc functions can't have varargs.
2209       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2210   }
2211
2212   FuncInfo->setArgumentStackSize(StackSize);
2213
2214   return Chain;
2215 }
2216
2217 SDValue
2218 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2219                                     SDValue StackPtr, SDValue Arg,
2220                                     DebugLoc dl, SelectionDAG &DAG,
2221                                     const CCValAssign &VA,
2222                                     ISD::ArgFlagsTy Flags) const {
2223   unsigned LocMemOffset = VA.getLocMemOffset();
2224   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2225   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2226   if (Flags.isByVal())
2227     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2228
2229   return DAG.getStore(Chain, dl, Arg, PtrOff,
2230                       MachinePointerInfo::getStack(LocMemOffset),
2231                       false, false, 0);
2232 }
2233
2234 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2235 /// optimization is performed and it is required.
2236 SDValue
2237 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2238                                            SDValue &OutRetAddr, SDValue Chain,
2239                                            bool IsTailCall, bool Is64Bit,
2240                                            int FPDiff, DebugLoc dl) const {
2241   // Adjust the Return address stack slot.
2242   EVT VT = getPointerTy();
2243   OutRetAddr = getReturnAddressFrameIndex(DAG);
2244
2245   // Load the "old" Return address.
2246   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2247                            false, false, false, 0);
2248   return SDValue(OutRetAddr.getNode(), 1);
2249 }
2250
2251 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2252 /// optimization is performed and it is required (FPDiff!=0).
2253 static SDValue
2254 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2255                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2256                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2257   // Store the return address to the appropriate stack slot.
2258   if (!FPDiff) return Chain;
2259   // Calculate the new stack slot for the return address.
2260   int NewReturnAddrFI =
2261     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2262   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2263   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2264                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2265                        false, false, 0);
2266   return Chain;
2267 }
2268
2269 SDValue
2270 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2271                              SmallVectorImpl<SDValue> &InVals) const {
2272   SelectionDAG &DAG                     = CLI.DAG;
2273   DebugLoc &dl                          = CLI.DL;
2274   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2275   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2276   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2277   SDValue Chain                         = CLI.Chain;
2278   SDValue Callee                        = CLI.Callee;
2279   CallingConv::ID CallConv              = CLI.CallConv;
2280   bool &isTailCall                      = CLI.IsTailCall;
2281   bool isVarArg                         = CLI.IsVarArg;
2282
2283   MachineFunction &MF = DAG.getMachineFunction();
2284   bool Is64Bit        = Subtarget->is64Bit();
2285   bool IsWin64        = Subtarget->isTargetWin64();
2286   bool IsWindows      = Subtarget->isTargetWindows();
2287   StructReturnType SR = callIsStructReturn(Outs);
2288   bool IsSibcall      = false;
2289
2290   if (MF.getTarget().Options.DisableTailCalls)
2291     isTailCall = false;
2292
2293   if (isTailCall) {
2294     // Check if it's really possible to do a tail call.
2295     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2296                     isVarArg, SR != NotStructReturn,
2297                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2298                     Outs, OutVals, Ins, DAG);
2299
2300     // Sibcalls are automatically detected tailcalls which do not require
2301     // ABI changes.
2302     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2303       IsSibcall = true;
2304
2305     if (isTailCall)
2306       ++NumTailCalls;
2307   }
2308
2309   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2310          "Var args not supported with calling convention fastcc, ghc or hipe");
2311
2312   // Analyze operands of the call, assigning locations to each operand.
2313   SmallVector<CCValAssign, 16> ArgLocs;
2314   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2315                  ArgLocs, *DAG.getContext());
2316
2317   // Allocate shadow area for Win64
2318   if (IsWin64) {
2319     CCInfo.AllocateStack(32, 8);
2320   }
2321
2322   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2323
2324   // Get a count of how many bytes are to be pushed on the stack.
2325   unsigned NumBytes = CCInfo.getNextStackOffset();
2326   if (IsSibcall)
2327     // This is a sibcall. The memory operands are available in caller's
2328     // own caller's stack.
2329     NumBytes = 0;
2330   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2331            IsTailCallConvention(CallConv))
2332     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2333
2334   int FPDiff = 0;
2335   if (isTailCall && !IsSibcall) {
2336     // Lower arguments at fp - stackoffset + fpdiff.
2337     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2338     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2339
2340     FPDiff = NumBytesCallerPushed - NumBytes;
2341
2342     // Set the delta of movement of the returnaddr stackslot.
2343     // But only set if delta is greater than previous delta.
2344     if (FPDiff < X86Info->getTCReturnAddrDelta())
2345       X86Info->setTCReturnAddrDelta(FPDiff);
2346   }
2347
2348   if (!IsSibcall)
2349     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2350
2351   SDValue RetAddrFrIdx;
2352   // Load return address for tail calls.
2353   if (isTailCall && FPDiff)
2354     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2355                                     Is64Bit, FPDiff, dl);
2356
2357   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2358   SmallVector<SDValue, 8> MemOpChains;
2359   SDValue StackPtr;
2360
2361   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2362   // of tail call optimization arguments are handle later.
2363   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2364     CCValAssign &VA = ArgLocs[i];
2365     EVT RegVT = VA.getLocVT();
2366     SDValue Arg = OutVals[i];
2367     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2368     bool isByVal = Flags.isByVal();
2369
2370     // Promote the value if needed.
2371     switch (VA.getLocInfo()) {
2372     default: llvm_unreachable("Unknown loc info!");
2373     case CCValAssign::Full: break;
2374     case CCValAssign::SExt:
2375       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2376       break;
2377     case CCValAssign::ZExt:
2378       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2379       break;
2380     case CCValAssign::AExt:
2381       if (RegVT.is128BitVector()) {
2382         // Special case: passing MMX values in XMM registers.
2383         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2384         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2385         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2386       } else
2387         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2388       break;
2389     case CCValAssign::BCvt:
2390       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2391       break;
2392     case CCValAssign::Indirect: {
2393       // Store the argument.
2394       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2395       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2396       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2397                            MachinePointerInfo::getFixedStack(FI),
2398                            false, false, 0);
2399       Arg = SpillSlot;
2400       break;
2401     }
2402     }
2403
2404     if (VA.isRegLoc()) {
2405       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2406       if (isVarArg && IsWin64) {
2407         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2408         // shadow reg if callee is a varargs function.
2409         unsigned ShadowReg = 0;
2410         switch (VA.getLocReg()) {
2411         case X86::XMM0: ShadowReg = X86::RCX; break;
2412         case X86::XMM1: ShadowReg = X86::RDX; break;
2413         case X86::XMM2: ShadowReg = X86::R8; break;
2414         case X86::XMM3: ShadowReg = X86::R9; break;
2415         }
2416         if (ShadowReg)
2417           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2418       }
2419     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2420       assert(VA.isMemLoc());
2421       if (StackPtr.getNode() == 0)
2422         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2423                                       getPointerTy());
2424       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2425                                              dl, DAG, VA, Flags));
2426     }
2427   }
2428
2429   if (!MemOpChains.empty())
2430     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2431                         &MemOpChains[0], MemOpChains.size());
2432
2433   if (Subtarget->isPICStyleGOT()) {
2434     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2435     // GOT pointer.
2436     if (!isTailCall) {
2437       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2438                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2439     } else {
2440       // If we are tail calling and generating PIC/GOT style code load the
2441       // address of the callee into ECX. The value in ecx is used as target of
2442       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2443       // for tail calls on PIC/GOT architectures. Normally we would just put the
2444       // address of GOT into ebx and then call target@PLT. But for tail calls
2445       // ebx would be restored (since ebx is callee saved) before jumping to the
2446       // target@PLT.
2447
2448       // Note: The actual moving to ECX is done further down.
2449       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2450       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2451           !G->getGlobal()->hasProtectedVisibility())
2452         Callee = LowerGlobalAddress(Callee, DAG);
2453       else if (isa<ExternalSymbolSDNode>(Callee))
2454         Callee = LowerExternalSymbol(Callee, DAG);
2455     }
2456   }
2457
2458   if (Is64Bit && isVarArg && !IsWin64) {
2459     // From AMD64 ABI document:
2460     // For calls that may call functions that use varargs or stdargs
2461     // (prototype-less calls or calls to functions containing ellipsis (...) in
2462     // the declaration) %al is used as hidden argument to specify the number
2463     // of SSE registers used. The contents of %al do not need to match exactly
2464     // the number of registers, but must be an ubound on the number of SSE
2465     // registers used and is in the range 0 - 8 inclusive.
2466
2467     // Count the number of XMM registers allocated.
2468     static const uint16_t XMMArgRegs[] = {
2469       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2470       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2471     };
2472     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2473     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2474            && "SSE registers cannot be used when SSE is disabled");
2475
2476     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2477                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2478   }
2479
2480   // For tail calls lower the arguments to the 'real' stack slot.
2481   if (isTailCall) {
2482     // Force all the incoming stack arguments to be loaded from the stack
2483     // before any new outgoing arguments are stored to the stack, because the
2484     // outgoing stack slots may alias the incoming argument stack slots, and
2485     // the alias isn't otherwise explicit. This is slightly more conservative
2486     // than necessary, because it means that each store effectively depends
2487     // on every argument instead of just those arguments it would clobber.
2488     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2489
2490     SmallVector<SDValue, 8> MemOpChains2;
2491     SDValue FIN;
2492     int FI = 0;
2493     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2494       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2495         CCValAssign &VA = ArgLocs[i];
2496         if (VA.isRegLoc())
2497           continue;
2498         assert(VA.isMemLoc());
2499         SDValue Arg = OutVals[i];
2500         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2501         // Create frame index.
2502         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2503         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2504         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2505         FIN = DAG.getFrameIndex(FI, getPointerTy());
2506
2507         if (Flags.isByVal()) {
2508           // Copy relative to framepointer.
2509           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2510           if (StackPtr.getNode() == 0)
2511             StackPtr = DAG.getCopyFromReg(Chain, dl,
2512                                           RegInfo->getStackRegister(),
2513                                           getPointerTy());
2514           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2515
2516           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2517                                                            ArgChain,
2518                                                            Flags, DAG, dl));
2519         } else {
2520           // Store relative to framepointer.
2521           MemOpChains2.push_back(
2522             DAG.getStore(ArgChain, dl, Arg, FIN,
2523                          MachinePointerInfo::getFixedStack(FI),
2524                          false, false, 0));
2525         }
2526       }
2527     }
2528
2529     if (!MemOpChains2.empty())
2530       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2531                           &MemOpChains2[0], MemOpChains2.size());
2532
2533     // Store the return address to the appropriate stack slot.
2534     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2535                                      getPointerTy(), RegInfo->getSlotSize(),
2536                                      FPDiff, dl);
2537   }
2538
2539   // Build a sequence of copy-to-reg nodes chained together with token chain
2540   // and flag operands which copy the outgoing args into registers.
2541   SDValue InFlag;
2542   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2543     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2544                              RegsToPass[i].second, InFlag);
2545     InFlag = Chain.getValue(1);
2546   }
2547
2548   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2549     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2550     // In the 64-bit large code model, we have to make all calls
2551     // through a register, since the call instruction's 32-bit
2552     // pc-relative offset may not be large enough to hold the whole
2553     // address.
2554   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2555     // If the callee is a GlobalAddress node (quite common, every direct call
2556     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2557     // it.
2558
2559     // We should use extra load for direct calls to dllimported functions in
2560     // non-JIT mode.
2561     const GlobalValue *GV = G->getGlobal();
2562     if (!GV->hasDLLImportLinkage()) {
2563       unsigned char OpFlags = 0;
2564       bool ExtraLoad = false;
2565       unsigned WrapperKind = ISD::DELETED_NODE;
2566
2567       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2568       // external symbols most go through the PLT in PIC mode.  If the symbol
2569       // has hidden or protected visibility, or if it is static or local, then
2570       // we don't need to use the PLT - we can directly call it.
2571       if (Subtarget->isTargetELF() &&
2572           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2573           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2574         OpFlags = X86II::MO_PLT;
2575       } else if (Subtarget->isPICStyleStubAny() &&
2576                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2577                  (!Subtarget->getTargetTriple().isMacOSX() ||
2578                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2579         // PC-relative references to external symbols should go through $stub,
2580         // unless we're building with the leopard linker or later, which
2581         // automatically synthesizes these stubs.
2582         OpFlags = X86II::MO_DARWIN_STUB;
2583       } else if (Subtarget->isPICStyleRIPRel() &&
2584                  isa<Function>(GV) &&
2585                  cast<Function>(GV)->getAttributes().
2586                    hasAttribute(AttributeSet::FunctionIndex,
2587                                 Attribute::NonLazyBind)) {
2588         // If the function is marked as non-lazy, generate an indirect call
2589         // which loads from the GOT directly. This avoids runtime overhead
2590         // at the cost of eager binding (and one extra byte of encoding).
2591         OpFlags = X86II::MO_GOTPCREL;
2592         WrapperKind = X86ISD::WrapperRIP;
2593         ExtraLoad = true;
2594       }
2595
2596       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2597                                           G->getOffset(), OpFlags);
2598
2599       // Add a wrapper if needed.
2600       if (WrapperKind != ISD::DELETED_NODE)
2601         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2602       // Add extra indirection if needed.
2603       if (ExtraLoad)
2604         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2605                              MachinePointerInfo::getGOT(),
2606                              false, false, false, 0);
2607     }
2608   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2609     unsigned char OpFlags = 0;
2610
2611     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2612     // external symbols should go through the PLT.
2613     if (Subtarget->isTargetELF() &&
2614         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2615       OpFlags = X86II::MO_PLT;
2616     } else if (Subtarget->isPICStyleStubAny() &&
2617                (!Subtarget->getTargetTriple().isMacOSX() ||
2618                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2619       // PC-relative references to external symbols should go through $stub,
2620       // unless we're building with the leopard linker or later, which
2621       // automatically synthesizes these stubs.
2622       OpFlags = X86II::MO_DARWIN_STUB;
2623     }
2624
2625     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2626                                          OpFlags);
2627   }
2628
2629   // Returns a chain & a flag for retval copy to use.
2630   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2631   SmallVector<SDValue, 8> Ops;
2632
2633   if (!IsSibcall && isTailCall) {
2634     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2635                            DAG.getIntPtrConstant(0, true), InFlag);
2636     InFlag = Chain.getValue(1);
2637   }
2638
2639   Ops.push_back(Chain);
2640   Ops.push_back(Callee);
2641
2642   if (isTailCall)
2643     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2644
2645   // Add argument registers to the end of the list so that they are known live
2646   // into the call.
2647   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2648     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2649                                   RegsToPass[i].second.getValueType()));
2650
2651   // Add a register mask operand representing the call-preserved registers.
2652   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2653   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2654   assert(Mask && "Missing call preserved mask for calling convention");
2655   Ops.push_back(DAG.getRegisterMask(Mask));
2656
2657   if (InFlag.getNode())
2658     Ops.push_back(InFlag);
2659
2660   if (isTailCall) {
2661     // We used to do:
2662     //// If this is the first return lowered for this function, add the regs
2663     //// to the liveout set for the function.
2664     // This isn't right, although it's probably harmless on x86; liveouts
2665     // should be computed from returns not tail calls.  Consider a void
2666     // function making a tail call to a function returning int.
2667     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2668   }
2669
2670   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2671   InFlag = Chain.getValue(1);
2672
2673   // Create the CALLSEQ_END node.
2674   unsigned NumBytesForCalleeToPush;
2675   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2676                        getTargetMachine().Options.GuaranteedTailCallOpt))
2677     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2678   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2679            SR == StackStructReturn)
2680     // If this is a call to a struct-return function, the callee
2681     // pops the hidden struct pointer, so we have to push it back.
2682     // This is common for Darwin/X86, Linux & Mingw32 targets.
2683     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2684     NumBytesForCalleeToPush = 4;
2685   else
2686     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2687
2688   // Returns a flag for retval copy to use.
2689   if (!IsSibcall) {
2690     Chain = DAG.getCALLSEQ_END(Chain,
2691                                DAG.getIntPtrConstant(NumBytes, true),
2692                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2693                                                      true),
2694                                InFlag);
2695     InFlag = Chain.getValue(1);
2696   }
2697
2698   // Handle result values, copying them out of physregs into vregs that we
2699   // return.
2700   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2701                          Ins, dl, DAG, InVals);
2702 }
2703
2704 //===----------------------------------------------------------------------===//
2705 //                Fast Calling Convention (tail call) implementation
2706 //===----------------------------------------------------------------------===//
2707
2708 //  Like std call, callee cleans arguments, convention except that ECX is
2709 //  reserved for storing the tail called function address. Only 2 registers are
2710 //  free for argument passing (inreg). Tail call optimization is performed
2711 //  provided:
2712 //                * tailcallopt is enabled
2713 //                * caller/callee are fastcc
2714 //  On X86_64 architecture with GOT-style position independent code only local
2715 //  (within module) calls are supported at the moment.
2716 //  To keep the stack aligned according to platform abi the function
2717 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2718 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2719 //  If a tail called function callee has more arguments than the caller the
2720 //  caller needs to make sure that there is room to move the RETADDR to. This is
2721 //  achieved by reserving an area the size of the argument delta right after the
2722 //  original REtADDR, but before the saved framepointer or the spilled registers
2723 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2724 //  stack layout:
2725 //    arg1
2726 //    arg2
2727 //    RETADDR
2728 //    [ new RETADDR
2729 //      move area ]
2730 //    (possible EBP)
2731 //    ESI
2732 //    EDI
2733 //    local1 ..
2734
2735 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2736 /// for a 16 byte align requirement.
2737 unsigned
2738 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2739                                                SelectionDAG& DAG) const {
2740   MachineFunction &MF = DAG.getMachineFunction();
2741   const TargetMachine &TM = MF.getTarget();
2742   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2743   unsigned StackAlignment = TFI.getStackAlignment();
2744   uint64_t AlignMask = StackAlignment - 1;
2745   int64_t Offset = StackSize;
2746   unsigned SlotSize = RegInfo->getSlotSize();
2747   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2748     // Number smaller than 12 so just add the difference.
2749     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2750   } else {
2751     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2752     Offset = ((~AlignMask) & Offset) + StackAlignment +
2753       (StackAlignment-SlotSize);
2754   }
2755   return Offset;
2756 }
2757
2758 /// MatchingStackOffset - Return true if the given stack call argument is
2759 /// already available in the same position (relatively) of the caller's
2760 /// incoming argument stack.
2761 static
2762 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2763                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2764                          const X86InstrInfo *TII) {
2765   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2766   int FI = INT_MAX;
2767   if (Arg.getOpcode() == ISD::CopyFromReg) {
2768     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2769     if (!TargetRegisterInfo::isVirtualRegister(VR))
2770       return false;
2771     MachineInstr *Def = MRI->getVRegDef(VR);
2772     if (!Def)
2773       return false;
2774     if (!Flags.isByVal()) {
2775       if (!TII->isLoadFromStackSlot(Def, FI))
2776         return false;
2777     } else {
2778       unsigned Opcode = Def->getOpcode();
2779       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2780           Def->getOperand(1).isFI()) {
2781         FI = Def->getOperand(1).getIndex();
2782         Bytes = Flags.getByValSize();
2783       } else
2784         return false;
2785     }
2786   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2787     if (Flags.isByVal())
2788       // ByVal argument is passed in as a pointer but it's now being
2789       // dereferenced. e.g.
2790       // define @foo(%struct.X* %A) {
2791       //   tail call @bar(%struct.X* byval %A)
2792       // }
2793       return false;
2794     SDValue Ptr = Ld->getBasePtr();
2795     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2796     if (!FINode)
2797       return false;
2798     FI = FINode->getIndex();
2799   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2800     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2801     FI = FINode->getIndex();
2802     Bytes = Flags.getByValSize();
2803   } else
2804     return false;
2805
2806   assert(FI != INT_MAX);
2807   if (!MFI->isFixedObjectIndex(FI))
2808     return false;
2809   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2810 }
2811
2812 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2813 /// for tail call optimization. Targets which want to do tail call
2814 /// optimization should implement this function.
2815 bool
2816 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2817                                                      CallingConv::ID CalleeCC,
2818                                                      bool isVarArg,
2819                                                      bool isCalleeStructRet,
2820                                                      bool isCallerStructRet,
2821                                                      Type *RetTy,
2822                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2823                                     const SmallVectorImpl<SDValue> &OutVals,
2824                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2825                                                      SelectionDAG &DAG) const {
2826   if (!IsTailCallConvention(CalleeCC) &&
2827       CalleeCC != CallingConv::C)
2828     return false;
2829
2830   // If -tailcallopt is specified, make fastcc functions tail-callable.
2831   const MachineFunction &MF = DAG.getMachineFunction();
2832   const Function *CallerF = DAG.getMachineFunction().getFunction();
2833
2834   // If the function return type is x86_fp80 and the callee return type is not,
2835   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2836   // perform a tailcall optimization here.
2837   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2838     return false;
2839
2840   CallingConv::ID CallerCC = CallerF->getCallingConv();
2841   bool CCMatch = CallerCC == CalleeCC;
2842
2843   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2844     if (IsTailCallConvention(CalleeCC) && CCMatch)
2845       return true;
2846     return false;
2847   }
2848
2849   // Look for obvious safe cases to perform tail call optimization that do not
2850   // require ABI changes. This is what gcc calls sibcall.
2851
2852   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2853   // emit a special epilogue.
2854   if (RegInfo->needsStackRealignment(MF))
2855     return false;
2856
2857   // Also avoid sibcall optimization if either caller or callee uses struct
2858   // return semantics.
2859   if (isCalleeStructRet || isCallerStructRet)
2860     return false;
2861
2862   // An stdcall caller is expected to clean up its arguments; the callee
2863   // isn't going to do that.
2864   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2865     return false;
2866
2867   // Do not sibcall optimize vararg calls unless all arguments are passed via
2868   // registers.
2869   if (isVarArg && !Outs.empty()) {
2870
2871     // Optimizing for varargs on Win64 is unlikely to be safe without
2872     // additional testing.
2873     if (Subtarget->isTargetWin64())
2874       return false;
2875
2876     SmallVector<CCValAssign, 16> ArgLocs;
2877     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2878                    getTargetMachine(), ArgLocs, *DAG.getContext());
2879
2880     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2881     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2882       if (!ArgLocs[i].isRegLoc())
2883         return false;
2884   }
2885
2886   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2887   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2888   // this into a sibcall.
2889   bool Unused = false;
2890   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2891     if (!Ins[i].Used) {
2892       Unused = true;
2893       break;
2894     }
2895   }
2896   if (Unused) {
2897     SmallVector<CCValAssign, 16> RVLocs;
2898     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2899                    getTargetMachine(), RVLocs, *DAG.getContext());
2900     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2901     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2902       CCValAssign &VA = RVLocs[i];
2903       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2904         return false;
2905     }
2906   }
2907
2908   // If the calling conventions do not match, then we'd better make sure the
2909   // results are returned in the same way as what the caller expects.
2910   if (!CCMatch) {
2911     SmallVector<CCValAssign, 16> RVLocs1;
2912     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2913                     getTargetMachine(), RVLocs1, *DAG.getContext());
2914     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2915
2916     SmallVector<CCValAssign, 16> RVLocs2;
2917     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2918                     getTargetMachine(), RVLocs2, *DAG.getContext());
2919     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2920
2921     if (RVLocs1.size() != RVLocs2.size())
2922       return false;
2923     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2924       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2925         return false;
2926       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2927         return false;
2928       if (RVLocs1[i].isRegLoc()) {
2929         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2930           return false;
2931       } else {
2932         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2933           return false;
2934       }
2935     }
2936   }
2937
2938   // If the callee takes no arguments then go on to check the results of the
2939   // call.
2940   if (!Outs.empty()) {
2941     // Check if stack adjustment is needed. For now, do not do this if any
2942     // argument is passed on the stack.
2943     SmallVector<CCValAssign, 16> ArgLocs;
2944     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2945                    getTargetMachine(), ArgLocs, *DAG.getContext());
2946
2947     // Allocate shadow area for Win64
2948     if (Subtarget->isTargetWin64()) {
2949       CCInfo.AllocateStack(32, 8);
2950     }
2951
2952     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2953     if (CCInfo.getNextStackOffset()) {
2954       MachineFunction &MF = DAG.getMachineFunction();
2955       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2956         return false;
2957
2958       // Check if the arguments are already laid out in the right way as
2959       // the caller's fixed stack objects.
2960       MachineFrameInfo *MFI = MF.getFrameInfo();
2961       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2962       const X86InstrInfo *TII =
2963         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2964       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2965         CCValAssign &VA = ArgLocs[i];
2966         SDValue Arg = OutVals[i];
2967         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2968         if (VA.getLocInfo() == CCValAssign::Indirect)
2969           return false;
2970         if (!VA.isRegLoc()) {
2971           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2972                                    MFI, MRI, TII))
2973             return false;
2974         }
2975       }
2976     }
2977
2978     // If the tailcall address may be in a register, then make sure it's
2979     // possible to register allocate for it. In 32-bit, the call address can
2980     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2981     // callee-saved registers are restored. These happen to be the same
2982     // registers used to pass 'inreg' arguments so watch out for those.
2983     if (!Subtarget->is64Bit() &&
2984         ((!isa<GlobalAddressSDNode>(Callee) &&
2985           !isa<ExternalSymbolSDNode>(Callee)) ||
2986          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2987       unsigned NumInRegs = 0;
2988       // In PIC we need an extra register to formulate the address computation
2989       // for the callee.
2990       unsigned MaxInRegs =
2991           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
2992
2993       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2994         CCValAssign &VA = ArgLocs[i];
2995         if (!VA.isRegLoc())
2996           continue;
2997         unsigned Reg = VA.getLocReg();
2998         switch (Reg) {
2999         default: break;
3000         case X86::EAX: case X86::EDX: case X86::ECX:
3001           if (++NumInRegs == MaxInRegs)
3002             return false;
3003           break;
3004         }
3005       }
3006     }
3007   }
3008
3009   return true;
3010 }
3011
3012 FastISel *
3013 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3014                                   const TargetLibraryInfo *libInfo) const {
3015   return X86::createFastISel(funcInfo, libInfo);
3016 }
3017
3018 //===----------------------------------------------------------------------===//
3019 //                           Other Lowering Hooks
3020 //===----------------------------------------------------------------------===//
3021
3022 static bool MayFoldLoad(SDValue Op) {
3023   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3024 }
3025
3026 static bool MayFoldIntoStore(SDValue Op) {
3027   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3028 }
3029
3030 static bool isTargetShuffle(unsigned Opcode) {
3031   switch(Opcode) {
3032   default: return false;
3033   case X86ISD::PSHUFD:
3034   case X86ISD::PSHUFHW:
3035   case X86ISD::PSHUFLW:
3036   case X86ISD::SHUFP:
3037   case X86ISD::PALIGNR:
3038   case X86ISD::MOVLHPS:
3039   case X86ISD::MOVLHPD:
3040   case X86ISD::MOVHLPS:
3041   case X86ISD::MOVLPS:
3042   case X86ISD::MOVLPD:
3043   case X86ISD::MOVSHDUP:
3044   case X86ISD::MOVSLDUP:
3045   case X86ISD::MOVDDUP:
3046   case X86ISD::MOVSS:
3047   case X86ISD::MOVSD:
3048   case X86ISD::UNPCKL:
3049   case X86ISD::UNPCKH:
3050   case X86ISD::VPERMILP:
3051   case X86ISD::VPERM2X128:
3052   case X86ISD::VPERMI:
3053     return true;
3054   }
3055 }
3056
3057 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3058                                     SDValue V1, SelectionDAG &DAG) {
3059   switch(Opc) {
3060   default: llvm_unreachable("Unknown x86 shuffle node");
3061   case X86ISD::MOVSHDUP:
3062   case X86ISD::MOVSLDUP:
3063   case X86ISD::MOVDDUP:
3064     return DAG.getNode(Opc, dl, VT, V1);
3065   }
3066 }
3067
3068 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3069                                     SDValue V1, unsigned TargetMask,
3070                                     SelectionDAG &DAG) {
3071   switch(Opc) {
3072   default: llvm_unreachable("Unknown x86 shuffle node");
3073   case X86ISD::PSHUFD:
3074   case X86ISD::PSHUFHW:
3075   case X86ISD::PSHUFLW:
3076   case X86ISD::VPERMILP:
3077   case X86ISD::VPERMI:
3078     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3079   }
3080 }
3081
3082 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3083                                     SDValue V1, SDValue V2, unsigned TargetMask,
3084                                     SelectionDAG &DAG) {
3085   switch(Opc) {
3086   default: llvm_unreachable("Unknown x86 shuffle node");
3087   case X86ISD::PALIGNR:
3088   case X86ISD::SHUFP:
3089   case X86ISD::VPERM2X128:
3090     return DAG.getNode(Opc, dl, VT, V1, V2,
3091                        DAG.getConstant(TargetMask, MVT::i8));
3092   }
3093 }
3094
3095 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3096                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3097   switch(Opc) {
3098   default: llvm_unreachable("Unknown x86 shuffle node");
3099   case X86ISD::MOVLHPS:
3100   case X86ISD::MOVLHPD:
3101   case X86ISD::MOVHLPS:
3102   case X86ISD::MOVLPS:
3103   case X86ISD::MOVLPD:
3104   case X86ISD::MOVSS:
3105   case X86ISD::MOVSD:
3106   case X86ISD::UNPCKL:
3107   case X86ISD::UNPCKH:
3108     return DAG.getNode(Opc, dl, VT, V1, V2);
3109   }
3110 }
3111
3112 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3113   MachineFunction &MF = DAG.getMachineFunction();
3114   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3115   int ReturnAddrIndex = FuncInfo->getRAIndex();
3116
3117   if (ReturnAddrIndex == 0) {
3118     // Set up a frame object for the return address.
3119     unsigned SlotSize = RegInfo->getSlotSize();
3120     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3121                                                            false);
3122     FuncInfo->setRAIndex(ReturnAddrIndex);
3123   }
3124
3125   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3126 }
3127
3128 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3129                                        bool hasSymbolicDisplacement) {
3130   // Offset should fit into 32 bit immediate field.
3131   if (!isInt<32>(Offset))
3132     return false;
3133
3134   // If we don't have a symbolic displacement - we don't have any extra
3135   // restrictions.
3136   if (!hasSymbolicDisplacement)
3137     return true;
3138
3139   // FIXME: Some tweaks might be needed for medium code model.
3140   if (M != CodeModel::Small && M != CodeModel::Kernel)
3141     return false;
3142
3143   // For small code model we assume that latest object is 16MB before end of 31
3144   // bits boundary. We may also accept pretty large negative constants knowing
3145   // that all objects are in the positive half of address space.
3146   if (M == CodeModel::Small && Offset < 16*1024*1024)
3147     return true;
3148
3149   // For kernel code model we know that all object resist in the negative half
3150   // of 32bits address space. We may not accept negative offsets, since they may
3151   // be just off and we may accept pretty large positive ones.
3152   if (M == CodeModel::Kernel && Offset > 0)
3153     return true;
3154
3155   return false;
3156 }
3157
3158 /// isCalleePop - Determines whether the callee is required to pop its
3159 /// own arguments. Callee pop is necessary to support tail calls.
3160 bool X86::isCalleePop(CallingConv::ID CallingConv,
3161                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3162   if (IsVarArg)
3163     return false;
3164
3165   switch (CallingConv) {
3166   default:
3167     return false;
3168   case CallingConv::X86_StdCall:
3169     return !is64Bit;
3170   case CallingConv::X86_FastCall:
3171     return !is64Bit;
3172   case CallingConv::X86_ThisCall:
3173     return !is64Bit;
3174   case CallingConv::Fast:
3175     return TailCallOpt;
3176   case CallingConv::GHC:
3177     return TailCallOpt;
3178   case CallingConv::HiPE:
3179     return TailCallOpt;
3180   }
3181 }
3182
3183 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3184 /// specific condition code, returning the condition code and the LHS/RHS of the
3185 /// comparison to make.
3186 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3187                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3188   if (!isFP) {
3189     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3190       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3191         // X > -1   -> X == 0, jump !sign.
3192         RHS = DAG.getConstant(0, RHS.getValueType());
3193         return X86::COND_NS;
3194       }
3195       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3196         // X < 0   -> X == 0, jump on sign.
3197         return X86::COND_S;
3198       }
3199       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3200         // X < 1   -> X <= 0
3201         RHS = DAG.getConstant(0, RHS.getValueType());
3202         return X86::COND_LE;
3203       }
3204     }
3205
3206     switch (SetCCOpcode) {
3207     default: llvm_unreachable("Invalid integer condition!");
3208     case ISD::SETEQ:  return X86::COND_E;
3209     case ISD::SETGT:  return X86::COND_G;
3210     case ISD::SETGE:  return X86::COND_GE;
3211     case ISD::SETLT:  return X86::COND_L;
3212     case ISD::SETLE:  return X86::COND_LE;
3213     case ISD::SETNE:  return X86::COND_NE;
3214     case ISD::SETULT: return X86::COND_B;
3215     case ISD::SETUGT: return X86::COND_A;
3216     case ISD::SETULE: return X86::COND_BE;
3217     case ISD::SETUGE: return X86::COND_AE;
3218     }
3219   }
3220
3221   // First determine if it is required or is profitable to flip the operands.
3222
3223   // If LHS is a foldable load, but RHS is not, flip the condition.
3224   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3225       !ISD::isNON_EXTLoad(RHS.getNode())) {
3226     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3227     std::swap(LHS, RHS);
3228   }
3229
3230   switch (SetCCOpcode) {
3231   default: break;
3232   case ISD::SETOLT:
3233   case ISD::SETOLE:
3234   case ISD::SETUGT:
3235   case ISD::SETUGE:
3236     std::swap(LHS, RHS);
3237     break;
3238   }
3239
3240   // On a floating point condition, the flags are set as follows:
3241   // ZF  PF  CF   op
3242   //  0 | 0 | 0 | X > Y
3243   //  0 | 0 | 1 | X < Y
3244   //  1 | 0 | 0 | X == Y
3245   //  1 | 1 | 1 | unordered
3246   switch (SetCCOpcode) {
3247   default: llvm_unreachable("Condcode should be pre-legalized away");
3248   case ISD::SETUEQ:
3249   case ISD::SETEQ:   return X86::COND_E;
3250   case ISD::SETOLT:              // flipped
3251   case ISD::SETOGT:
3252   case ISD::SETGT:   return X86::COND_A;
3253   case ISD::SETOLE:              // flipped
3254   case ISD::SETOGE:
3255   case ISD::SETGE:   return X86::COND_AE;
3256   case ISD::SETUGT:              // flipped
3257   case ISD::SETULT:
3258   case ISD::SETLT:   return X86::COND_B;
3259   case ISD::SETUGE:              // flipped
3260   case ISD::SETULE:
3261   case ISD::SETLE:   return X86::COND_BE;
3262   case ISD::SETONE:
3263   case ISD::SETNE:   return X86::COND_NE;
3264   case ISD::SETUO:   return X86::COND_P;
3265   case ISD::SETO:    return X86::COND_NP;
3266   case ISD::SETOEQ:
3267   case ISD::SETUNE:  return X86::COND_INVALID;
3268   }
3269 }
3270
3271 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3272 /// code. Current x86 isa includes the following FP cmov instructions:
3273 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3274 static bool hasFPCMov(unsigned X86CC) {
3275   switch (X86CC) {
3276   default:
3277     return false;
3278   case X86::COND_B:
3279   case X86::COND_BE:
3280   case X86::COND_E:
3281   case X86::COND_P:
3282   case X86::COND_A:
3283   case X86::COND_AE:
3284   case X86::COND_NE:
3285   case X86::COND_NP:
3286     return true;
3287   }
3288 }
3289
3290 /// isFPImmLegal - Returns true if the target can instruction select the
3291 /// specified FP immediate natively. If false, the legalizer will
3292 /// materialize the FP immediate as a load from a constant pool.
3293 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3294   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3295     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3296       return true;
3297   }
3298   return false;
3299 }
3300
3301 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3302 /// the specified range (L, H].
3303 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3304   return (Val < 0) || (Val >= Low && Val < Hi);
3305 }
3306
3307 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3308 /// specified value.
3309 static bool isUndefOrEqual(int Val, int CmpVal) {
3310   return (Val < 0 || Val == CmpVal);
3311 }
3312
3313 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3314 /// from position Pos and ending in Pos+Size, falls within the specified
3315 /// sequential range (L, L+Pos]. or is undef.
3316 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3317                                        unsigned Pos, unsigned Size, int Low) {
3318   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3319     if (!isUndefOrEqual(Mask[i], Low))
3320       return false;
3321   return true;
3322 }
3323
3324 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3325 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3326 /// the second operand.
3327 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3328   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3329     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3330   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3331     return (Mask[0] < 2 && Mask[1] < 2);
3332   return false;
3333 }
3334
3335 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3336 /// is suitable for input to PSHUFHW.
3337 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3338   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3339     return false;
3340
3341   // Lower quadword copied in order or undef.
3342   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3343     return false;
3344
3345   // Upper quadword shuffled.
3346   for (unsigned i = 4; i != 8; ++i)
3347     if (!isUndefOrInRange(Mask[i], 4, 8))
3348       return false;
3349
3350   if (VT == MVT::v16i16) {
3351     // Lower quadword copied in order or undef.
3352     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3353       return false;
3354
3355     // Upper quadword shuffled.
3356     for (unsigned i = 12; i != 16; ++i)
3357       if (!isUndefOrInRange(Mask[i], 12, 16))
3358         return false;
3359   }
3360
3361   return true;
3362 }
3363
3364 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3365 /// is suitable for input to PSHUFLW.
3366 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3367   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3368     return false;
3369
3370   // Upper quadword copied in order.
3371   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3372     return false;
3373
3374   // Lower quadword shuffled.
3375   for (unsigned i = 0; i != 4; ++i)
3376     if (!isUndefOrInRange(Mask[i], 0, 4))
3377       return false;
3378
3379   if (VT == MVT::v16i16) {
3380     // Upper quadword copied in order.
3381     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3382       return false;
3383
3384     // Lower quadword shuffled.
3385     for (unsigned i = 8; i != 12; ++i)
3386       if (!isUndefOrInRange(Mask[i], 8, 12))
3387         return false;
3388   }
3389
3390   return true;
3391 }
3392
3393 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3394 /// is suitable for input to PALIGNR.
3395 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3396                           const X86Subtarget *Subtarget) {
3397   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3398       (VT.is256BitVector() && !Subtarget->hasInt256()))
3399     return false;
3400
3401   unsigned NumElts = VT.getVectorNumElements();
3402   unsigned NumLanes = VT.getSizeInBits()/128;
3403   unsigned NumLaneElts = NumElts/NumLanes;
3404
3405   // Do not handle 64-bit element shuffles with palignr.
3406   if (NumLaneElts == 2)
3407     return false;
3408
3409   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3410     unsigned i;
3411     for (i = 0; i != NumLaneElts; ++i) {
3412       if (Mask[i+l] >= 0)
3413         break;
3414     }
3415
3416     // Lane is all undef, go to next lane
3417     if (i == NumLaneElts)
3418       continue;
3419
3420     int Start = Mask[i+l];
3421
3422     // Make sure its in this lane in one of the sources
3423     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3424         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3425       return false;
3426
3427     // If not lane 0, then we must match lane 0
3428     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3429       return false;
3430
3431     // Correct second source to be contiguous with first source
3432     if (Start >= (int)NumElts)
3433       Start -= NumElts - NumLaneElts;
3434
3435     // Make sure we're shifting in the right direction.
3436     if (Start <= (int)(i+l))
3437       return false;
3438
3439     Start -= i;
3440
3441     // Check the rest of the elements to see if they are consecutive.
3442     for (++i; i != NumLaneElts; ++i) {
3443       int Idx = Mask[i+l];
3444
3445       // Make sure its in this lane
3446       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3447           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3448         return false;
3449
3450       // If not lane 0, then we must match lane 0
3451       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3452         return false;
3453
3454       if (Idx >= (int)NumElts)
3455         Idx -= NumElts - NumLaneElts;
3456
3457       if (!isUndefOrEqual(Idx, Start+i))
3458         return false;
3459
3460     }
3461   }
3462
3463   return true;
3464 }
3465
3466 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3467 /// the two vector operands have swapped position.
3468 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3469                                      unsigned NumElems) {
3470   for (unsigned i = 0; i != NumElems; ++i) {
3471     int idx = Mask[i];
3472     if (idx < 0)
3473       continue;
3474     else if (idx < (int)NumElems)
3475       Mask[i] = idx + NumElems;
3476     else
3477       Mask[i] = idx - NumElems;
3478   }
3479 }
3480
3481 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3482 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3483 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3484 /// reverse of what x86 shuffles want.
3485 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3486                         bool Commuted = false) {
3487   if (!HasFp256 && VT.is256BitVector())
3488     return false;
3489
3490   unsigned NumElems = VT.getVectorNumElements();
3491   unsigned NumLanes = VT.getSizeInBits()/128;
3492   unsigned NumLaneElems = NumElems/NumLanes;
3493
3494   if (NumLaneElems != 2 && NumLaneElems != 4)
3495     return false;
3496
3497   // VSHUFPSY divides the resulting vector into 4 chunks.
3498   // The sources are also splitted into 4 chunks, and each destination
3499   // chunk must come from a different source chunk.
3500   //
3501   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3502   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3503   //
3504   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3505   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3506   //
3507   // VSHUFPDY divides the resulting vector into 4 chunks.
3508   // The sources are also splitted into 4 chunks, and each destination
3509   // chunk must come from a different source chunk.
3510   //
3511   //  SRC1 =>      X3       X2       X1       X0
3512   //  SRC2 =>      Y3       Y2       Y1       Y0
3513   //
3514   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3515   //
3516   unsigned HalfLaneElems = NumLaneElems/2;
3517   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3518     for (unsigned i = 0; i != NumLaneElems; ++i) {
3519       int Idx = Mask[i+l];
3520       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3521       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3522         return false;
3523       // For VSHUFPSY, the mask of the second half must be the same as the
3524       // first but with the appropriate offsets. This works in the same way as
3525       // VPERMILPS works with masks.
3526       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3527         continue;
3528       if (!isUndefOrEqual(Idx, Mask[i]+l))
3529         return false;
3530     }
3531   }
3532
3533   return true;
3534 }
3535
3536 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3537 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3538 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3539   if (!VT.is128BitVector())
3540     return false;
3541
3542   unsigned NumElems = VT.getVectorNumElements();
3543
3544   if (NumElems != 4)
3545     return false;
3546
3547   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3548   return isUndefOrEqual(Mask[0], 6) &&
3549          isUndefOrEqual(Mask[1], 7) &&
3550          isUndefOrEqual(Mask[2], 2) &&
3551          isUndefOrEqual(Mask[3], 3);
3552 }
3553
3554 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3555 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3556 /// <2, 3, 2, 3>
3557 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3558   if (!VT.is128BitVector())
3559     return false;
3560
3561   unsigned NumElems = VT.getVectorNumElements();
3562
3563   if (NumElems != 4)
3564     return false;
3565
3566   return isUndefOrEqual(Mask[0], 2) &&
3567          isUndefOrEqual(Mask[1], 3) &&
3568          isUndefOrEqual(Mask[2], 2) &&
3569          isUndefOrEqual(Mask[3], 3);
3570 }
3571
3572 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3573 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3574 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3575   if (!VT.is128BitVector())
3576     return false;
3577
3578   unsigned NumElems = VT.getVectorNumElements();
3579
3580   if (NumElems != 2 && NumElems != 4)
3581     return false;
3582
3583   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3584     if (!isUndefOrEqual(Mask[i], i + NumElems))
3585       return false;
3586
3587   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3588     if (!isUndefOrEqual(Mask[i], i))
3589       return false;
3590
3591   return true;
3592 }
3593
3594 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3595 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3596 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3597   if (!VT.is128BitVector())
3598     return false;
3599
3600   unsigned NumElems = VT.getVectorNumElements();
3601
3602   if (NumElems != 2 && NumElems != 4)
3603     return false;
3604
3605   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3606     if (!isUndefOrEqual(Mask[i], i))
3607       return false;
3608
3609   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3610     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3611       return false;
3612
3613   return true;
3614 }
3615
3616 //
3617 // Some special combinations that can be optimized.
3618 //
3619 static
3620 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3621                                SelectionDAG &DAG) {
3622   MVT VT = SVOp->getValueType(0).getSimpleVT();
3623   DebugLoc dl = SVOp->getDebugLoc();
3624
3625   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3626     return SDValue();
3627
3628   ArrayRef<int> Mask = SVOp->getMask();
3629
3630   // These are the special masks that may be optimized.
3631   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3632   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3633   bool MatchEvenMask = true;
3634   bool MatchOddMask  = true;
3635   for (int i=0; i<8; ++i) {
3636     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3637       MatchEvenMask = false;
3638     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3639       MatchOddMask = false;
3640   }
3641
3642   if (!MatchEvenMask && !MatchOddMask)
3643     return SDValue();
3644
3645   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3646
3647   SDValue Op0 = SVOp->getOperand(0);
3648   SDValue Op1 = SVOp->getOperand(1);
3649
3650   if (MatchEvenMask) {
3651     // Shift the second operand right to 32 bits.
3652     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3653     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3654   } else {
3655     // Shift the first operand left to 32 bits.
3656     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3657     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3658   }
3659   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3660   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3661 }
3662
3663 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3664 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3665 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3666                          bool HasInt256, bool V2IsSplat = false) {
3667   unsigned NumElts = VT.getVectorNumElements();
3668
3669   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3670          "Unsupported vector type for unpckh");
3671
3672   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3673       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3674     return false;
3675
3676   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3677   // independently on 128-bit lanes.
3678   unsigned NumLanes = VT.getSizeInBits()/128;
3679   unsigned NumLaneElts = NumElts/NumLanes;
3680
3681   for (unsigned l = 0; l != NumLanes; ++l) {
3682     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3683          i != (l+1)*NumLaneElts;
3684          i += 2, ++j) {
3685       int BitI  = Mask[i];
3686       int BitI1 = Mask[i+1];
3687       if (!isUndefOrEqual(BitI, j))
3688         return false;
3689       if (V2IsSplat) {
3690         if (!isUndefOrEqual(BitI1, NumElts))
3691           return false;
3692       } else {
3693         if (!isUndefOrEqual(BitI1, j + NumElts))
3694           return false;
3695       }
3696     }
3697   }
3698
3699   return true;
3700 }
3701
3702 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3703 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3704 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3705                          bool HasInt256, bool V2IsSplat = false) {
3706   unsigned NumElts = VT.getVectorNumElements();
3707
3708   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3709          "Unsupported vector type for unpckh");
3710
3711   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3712       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3713     return false;
3714
3715   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3716   // independently on 128-bit lanes.
3717   unsigned NumLanes = VT.getSizeInBits()/128;
3718   unsigned NumLaneElts = NumElts/NumLanes;
3719
3720   for (unsigned l = 0; l != NumLanes; ++l) {
3721     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3722          i != (l+1)*NumLaneElts; i += 2, ++j) {
3723       int BitI  = Mask[i];
3724       int BitI1 = Mask[i+1];
3725       if (!isUndefOrEqual(BitI, j))
3726         return false;
3727       if (V2IsSplat) {
3728         if (isUndefOrEqual(BitI1, NumElts))
3729           return false;
3730       } else {
3731         if (!isUndefOrEqual(BitI1, j+NumElts))
3732           return false;
3733       }
3734     }
3735   }
3736   return true;
3737 }
3738
3739 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3740 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3741 /// <0, 0, 1, 1>
3742 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3743   unsigned NumElts = VT.getVectorNumElements();
3744   bool Is256BitVec = VT.is256BitVector();
3745
3746   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3747          "Unsupported vector type for unpckh");
3748
3749   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3750       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3751     return false;
3752
3753   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3754   // FIXME: Need a better way to get rid of this, there's no latency difference
3755   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3756   // the former later. We should also remove the "_undef" special mask.
3757   if (NumElts == 4 && Is256BitVec)
3758     return false;
3759
3760   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3761   // independently on 128-bit lanes.
3762   unsigned NumLanes = VT.getSizeInBits()/128;
3763   unsigned NumLaneElts = NumElts/NumLanes;
3764
3765   for (unsigned l = 0; l != NumLanes; ++l) {
3766     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3767          i != (l+1)*NumLaneElts;
3768          i += 2, ++j) {
3769       int BitI  = Mask[i];
3770       int BitI1 = Mask[i+1];
3771
3772       if (!isUndefOrEqual(BitI, j))
3773         return false;
3774       if (!isUndefOrEqual(BitI1, j))
3775         return false;
3776     }
3777   }
3778
3779   return true;
3780 }
3781
3782 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3783 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3784 /// <2, 2, 3, 3>
3785 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3786   unsigned NumElts = VT.getVectorNumElements();
3787
3788   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3789          "Unsupported vector type for unpckh");
3790
3791   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3792       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3793     return false;
3794
3795   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3796   // independently on 128-bit lanes.
3797   unsigned NumLanes = VT.getSizeInBits()/128;
3798   unsigned NumLaneElts = NumElts/NumLanes;
3799
3800   for (unsigned l = 0; l != NumLanes; ++l) {
3801     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3802          i != (l+1)*NumLaneElts; i += 2, ++j) {
3803       int BitI  = Mask[i];
3804       int BitI1 = Mask[i+1];
3805       if (!isUndefOrEqual(BitI, j))
3806         return false;
3807       if (!isUndefOrEqual(BitI1, j))
3808         return false;
3809     }
3810   }
3811   return true;
3812 }
3813
3814 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3815 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3816 /// MOVSD, and MOVD, i.e. setting the lowest element.
3817 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3818   if (VT.getVectorElementType().getSizeInBits() < 32)
3819     return false;
3820   if (!VT.is128BitVector())
3821     return false;
3822
3823   unsigned NumElts = VT.getVectorNumElements();
3824
3825   if (!isUndefOrEqual(Mask[0], NumElts))
3826     return false;
3827
3828   for (unsigned i = 1; i != NumElts; ++i)
3829     if (!isUndefOrEqual(Mask[i], i))
3830       return false;
3831
3832   return true;
3833 }
3834
3835 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3836 /// as permutations between 128-bit chunks or halves. As an example: this
3837 /// shuffle bellow:
3838 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3839 /// The first half comes from the second half of V1 and the second half from the
3840 /// the second half of V2.
3841 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3842   if (!HasFp256 || !VT.is256BitVector())
3843     return false;
3844
3845   // The shuffle result is divided into half A and half B. In total the two
3846   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3847   // B must come from C, D, E or F.
3848   unsigned HalfSize = VT.getVectorNumElements()/2;
3849   bool MatchA = false, MatchB = false;
3850
3851   // Check if A comes from one of C, D, E, F.
3852   for (unsigned Half = 0; Half != 4; ++Half) {
3853     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3854       MatchA = true;
3855       break;
3856     }
3857   }
3858
3859   // Check if B comes from one of C, D, E, F.
3860   for (unsigned Half = 0; Half != 4; ++Half) {
3861     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3862       MatchB = true;
3863       break;
3864     }
3865   }
3866
3867   return MatchA && MatchB;
3868 }
3869
3870 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3871 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3872 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3873   MVT VT = SVOp->getValueType(0).getSimpleVT();
3874
3875   unsigned HalfSize = VT.getVectorNumElements()/2;
3876
3877   unsigned FstHalf = 0, SndHalf = 0;
3878   for (unsigned i = 0; i < HalfSize; ++i) {
3879     if (SVOp->getMaskElt(i) > 0) {
3880       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3881       break;
3882     }
3883   }
3884   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3885     if (SVOp->getMaskElt(i) > 0) {
3886       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3887       break;
3888     }
3889   }
3890
3891   return (FstHalf | (SndHalf << 4));
3892 }
3893
3894 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3895 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3896 /// Note that VPERMIL mask matching is different depending whether theunderlying
3897 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3898 /// to the same elements of the low, but to the higher half of the source.
3899 /// In VPERMILPD the two lanes could be shuffled independently of each other
3900 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3901 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3902   if (!HasFp256)
3903     return false;
3904
3905   unsigned NumElts = VT.getVectorNumElements();
3906   // Only match 256-bit with 32/64-bit types
3907   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3908     return false;
3909
3910   unsigned NumLanes = VT.getSizeInBits()/128;
3911   unsigned LaneSize = NumElts/NumLanes;
3912   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3913     for (unsigned i = 0; i != LaneSize; ++i) {
3914       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3915         return false;
3916       if (NumElts != 8 || l == 0)
3917         continue;
3918       // VPERMILPS handling
3919       if (Mask[i] < 0)
3920         continue;
3921       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3922         return false;
3923     }
3924   }
3925
3926   return true;
3927 }
3928
3929 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3930 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3931 /// element of vector 2 and the other elements to come from vector 1 in order.
3932 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3933                                bool V2IsSplat = false, bool V2IsUndef = false) {
3934   if (!VT.is128BitVector())
3935     return false;
3936
3937   unsigned NumOps = VT.getVectorNumElements();
3938   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3939     return false;
3940
3941   if (!isUndefOrEqual(Mask[0], 0))
3942     return false;
3943
3944   for (unsigned i = 1; i != NumOps; ++i)
3945     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3946           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3947           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3948       return false;
3949
3950   return true;
3951 }
3952
3953 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3954 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3955 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3956 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3957                            const X86Subtarget *Subtarget) {
3958   if (!Subtarget->hasSSE3())
3959     return false;
3960
3961   unsigned NumElems = VT.getVectorNumElements();
3962
3963   if ((VT.is128BitVector() && NumElems != 4) ||
3964       (VT.is256BitVector() && NumElems != 8))
3965     return false;
3966
3967   // "i+1" is the value the indexed mask element must have
3968   for (unsigned i = 0; i != NumElems; i += 2)
3969     if (!isUndefOrEqual(Mask[i], i+1) ||
3970         !isUndefOrEqual(Mask[i+1], i+1))
3971       return false;
3972
3973   return true;
3974 }
3975
3976 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3977 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3978 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3979 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3980                            const X86Subtarget *Subtarget) {
3981   if (!Subtarget->hasSSE3())
3982     return false;
3983
3984   unsigned NumElems = VT.getVectorNumElements();
3985
3986   if ((VT.is128BitVector() && NumElems != 4) ||
3987       (VT.is256BitVector() && NumElems != 8))
3988     return false;
3989
3990   // "i" is the value the indexed mask element must have
3991   for (unsigned i = 0; i != NumElems; i += 2)
3992     if (!isUndefOrEqual(Mask[i], i) ||
3993         !isUndefOrEqual(Mask[i+1], i))
3994       return false;
3995
3996   return true;
3997 }
3998
3999 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4000 /// specifies a shuffle of elements that is suitable for input to 256-bit
4001 /// version of MOVDDUP.
4002 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4003   if (!HasFp256 || !VT.is256BitVector())
4004     return false;
4005
4006   unsigned NumElts = VT.getVectorNumElements();
4007   if (NumElts != 4)
4008     return false;
4009
4010   for (unsigned i = 0; i != NumElts/2; ++i)
4011     if (!isUndefOrEqual(Mask[i], 0))
4012       return false;
4013   for (unsigned i = NumElts/2; i != NumElts; ++i)
4014     if (!isUndefOrEqual(Mask[i], NumElts/2))
4015       return false;
4016   return true;
4017 }
4018
4019 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4020 /// specifies a shuffle of elements that is suitable for input to 128-bit
4021 /// version of MOVDDUP.
4022 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4023   if (!VT.is128BitVector())
4024     return false;
4025
4026   unsigned e = VT.getVectorNumElements() / 2;
4027   for (unsigned i = 0; i != e; ++i)
4028     if (!isUndefOrEqual(Mask[i], i))
4029       return false;
4030   for (unsigned i = 0; i != e; ++i)
4031     if (!isUndefOrEqual(Mask[e+i], i))
4032       return false;
4033   return true;
4034 }
4035
4036 /// isVEXTRACTF128Index - Return true if the specified
4037 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4038 /// suitable for input to VEXTRACTF128.
4039 bool X86::isVEXTRACTF128Index(SDNode *N) {
4040   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4041     return false;
4042
4043   // The index should be aligned on a 128-bit boundary.
4044   uint64_t Index =
4045     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4046
4047   MVT VT = N->getValueType(0).getSimpleVT();
4048   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4049   bool Result = (Index * ElSize) % 128 == 0;
4050
4051   return Result;
4052 }
4053
4054 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4055 /// operand specifies a subvector insert that is suitable for input to
4056 /// VINSERTF128.
4057 bool X86::isVINSERTF128Index(SDNode *N) {
4058   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4059     return false;
4060
4061   // The index should be aligned on a 128-bit boundary.
4062   uint64_t Index =
4063     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4064
4065   MVT VT = N->getValueType(0).getSimpleVT();
4066   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4067   bool Result = (Index * ElSize) % 128 == 0;
4068
4069   return Result;
4070 }
4071
4072 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4073 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4074 /// Handles 128-bit and 256-bit.
4075 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4076   MVT VT = N->getValueType(0).getSimpleVT();
4077
4078   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4079          "Unsupported vector type for PSHUF/SHUFP");
4080
4081   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4082   // independently on 128-bit lanes.
4083   unsigned NumElts = VT.getVectorNumElements();
4084   unsigned NumLanes = VT.getSizeInBits()/128;
4085   unsigned NumLaneElts = NumElts/NumLanes;
4086
4087   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4088          "Only supports 2 or 4 elements per lane");
4089
4090   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4091   unsigned Mask = 0;
4092   for (unsigned i = 0; i != NumElts; ++i) {
4093     int Elt = N->getMaskElt(i);
4094     if (Elt < 0) continue;
4095     Elt &= NumLaneElts - 1;
4096     unsigned ShAmt = (i << Shift) % 8;
4097     Mask |= Elt << ShAmt;
4098   }
4099
4100   return Mask;
4101 }
4102
4103 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4104 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4105 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4106   MVT VT = N->getValueType(0).getSimpleVT();
4107
4108   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4109          "Unsupported vector type for PSHUFHW");
4110
4111   unsigned NumElts = VT.getVectorNumElements();
4112
4113   unsigned Mask = 0;
4114   for (unsigned l = 0; l != NumElts; l += 8) {
4115     // 8 nodes per lane, but we only care about the last 4.
4116     for (unsigned i = 0; i < 4; ++i) {
4117       int Elt = N->getMaskElt(l+i+4);
4118       if (Elt < 0) continue;
4119       Elt &= 0x3; // only 2-bits.
4120       Mask |= Elt << (i * 2);
4121     }
4122   }
4123
4124   return Mask;
4125 }
4126
4127 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4128 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4129 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4130   MVT VT = N->getValueType(0).getSimpleVT();
4131
4132   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4133          "Unsupported vector type for PSHUFHW");
4134
4135   unsigned NumElts = VT.getVectorNumElements();
4136
4137   unsigned Mask = 0;
4138   for (unsigned l = 0; l != NumElts; l += 8) {
4139     // 8 nodes per lane, but we only care about the first 4.
4140     for (unsigned i = 0; i < 4; ++i) {
4141       int Elt = N->getMaskElt(l+i);
4142       if (Elt < 0) continue;
4143       Elt &= 0x3; // only 2-bits
4144       Mask |= Elt << (i * 2);
4145     }
4146   }
4147
4148   return Mask;
4149 }
4150
4151 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4152 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4153 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4154   MVT VT = SVOp->getValueType(0).getSimpleVT();
4155   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4156
4157   unsigned NumElts = VT.getVectorNumElements();
4158   unsigned NumLanes = VT.getSizeInBits()/128;
4159   unsigned NumLaneElts = NumElts/NumLanes;
4160
4161   int Val = 0;
4162   unsigned i;
4163   for (i = 0; i != NumElts; ++i) {
4164     Val = SVOp->getMaskElt(i);
4165     if (Val >= 0)
4166       break;
4167   }
4168   if (Val >= (int)NumElts)
4169     Val -= NumElts - NumLaneElts;
4170
4171   assert(Val - i > 0 && "PALIGNR imm should be positive");
4172   return (Val - i) * EltSize;
4173 }
4174
4175 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4176 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4177 /// instructions.
4178 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4179   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4180     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4181
4182   uint64_t Index =
4183     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4184
4185   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4186   MVT ElVT = VecVT.getVectorElementType();
4187
4188   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4189   return Index / NumElemsPerChunk;
4190 }
4191
4192 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4193 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4194 /// instructions.
4195 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4196   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4197     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4198
4199   uint64_t Index =
4200     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4201
4202   MVT VecVT = N->getValueType(0).getSimpleVT();
4203   MVT ElVT = VecVT.getVectorElementType();
4204
4205   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4206   return Index / NumElemsPerChunk;
4207 }
4208
4209 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4210 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4211 /// Handles 256-bit.
4212 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4213   MVT VT = N->getValueType(0).getSimpleVT();
4214
4215   unsigned NumElts = VT.getVectorNumElements();
4216
4217   assert((VT.is256BitVector() && NumElts == 4) &&
4218          "Unsupported vector type for VPERMQ/VPERMPD");
4219
4220   unsigned Mask = 0;
4221   for (unsigned i = 0; i != NumElts; ++i) {
4222     int Elt = N->getMaskElt(i);
4223     if (Elt < 0)
4224       continue;
4225     Mask |= Elt << (i*2);
4226   }
4227
4228   return Mask;
4229 }
4230 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4231 /// constant +0.0.
4232 bool X86::isZeroNode(SDValue Elt) {
4233   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4234     return CN->isNullValue();
4235   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4236     return CFP->getValueAPF().isPosZero();
4237   return false;
4238 }
4239
4240 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4241 /// their permute mask.
4242 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4243                                     SelectionDAG &DAG) {
4244   MVT VT = SVOp->getValueType(0).getSimpleVT();
4245   unsigned NumElems = VT.getVectorNumElements();
4246   SmallVector<int, 8> MaskVec;
4247
4248   for (unsigned i = 0; i != NumElems; ++i) {
4249     int Idx = SVOp->getMaskElt(i);
4250     if (Idx >= 0) {
4251       if (Idx < (int)NumElems)
4252         Idx += NumElems;
4253       else
4254         Idx -= NumElems;
4255     }
4256     MaskVec.push_back(Idx);
4257   }
4258   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4259                               SVOp->getOperand(0), &MaskVec[0]);
4260 }
4261
4262 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4263 /// match movhlps. The lower half elements should come from upper half of
4264 /// V1 (and in order), and the upper half elements should come from the upper
4265 /// half of V2 (and in order).
4266 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4267   if (!VT.is128BitVector())
4268     return false;
4269   if (VT.getVectorNumElements() != 4)
4270     return false;
4271   for (unsigned i = 0, e = 2; i != e; ++i)
4272     if (!isUndefOrEqual(Mask[i], i+2))
4273       return false;
4274   for (unsigned i = 2; i != 4; ++i)
4275     if (!isUndefOrEqual(Mask[i], i+4))
4276       return false;
4277   return true;
4278 }
4279
4280 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4281 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4282 /// required.
4283 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4284   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4285     return false;
4286   N = N->getOperand(0).getNode();
4287   if (!ISD::isNON_EXTLoad(N))
4288     return false;
4289   if (LD)
4290     *LD = cast<LoadSDNode>(N);
4291   return true;
4292 }
4293
4294 // Test whether the given value is a vector value which will be legalized
4295 // into a load.
4296 static bool WillBeConstantPoolLoad(SDNode *N) {
4297   if (N->getOpcode() != ISD::BUILD_VECTOR)
4298     return false;
4299
4300   // Check for any non-constant elements.
4301   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4302     switch (N->getOperand(i).getNode()->getOpcode()) {
4303     case ISD::UNDEF:
4304     case ISD::ConstantFP:
4305     case ISD::Constant:
4306       break;
4307     default:
4308       return false;
4309     }
4310
4311   // Vectors of all-zeros and all-ones are materialized with special
4312   // instructions rather than being loaded.
4313   return !ISD::isBuildVectorAllZeros(N) &&
4314          !ISD::isBuildVectorAllOnes(N);
4315 }
4316
4317 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4318 /// match movlp{s|d}. The lower half elements should come from lower half of
4319 /// V1 (and in order), and the upper half elements should come from the upper
4320 /// half of V2 (and in order). And since V1 will become the source of the
4321 /// MOVLP, it must be either a vector load or a scalar load to vector.
4322 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4323                                ArrayRef<int> Mask, EVT VT) {
4324   if (!VT.is128BitVector())
4325     return false;
4326
4327   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4328     return false;
4329   // Is V2 is a vector load, don't do this transformation. We will try to use
4330   // load folding shufps op.
4331   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4332     return false;
4333
4334   unsigned NumElems = VT.getVectorNumElements();
4335
4336   if (NumElems != 2 && NumElems != 4)
4337     return false;
4338   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4339     if (!isUndefOrEqual(Mask[i], i))
4340       return false;
4341   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4342     if (!isUndefOrEqual(Mask[i], i+NumElems))
4343       return false;
4344   return true;
4345 }
4346
4347 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4348 /// all the same.
4349 static bool isSplatVector(SDNode *N) {
4350   if (N->getOpcode() != ISD::BUILD_VECTOR)
4351     return false;
4352
4353   SDValue SplatValue = N->getOperand(0);
4354   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4355     if (N->getOperand(i) != SplatValue)
4356       return false;
4357   return true;
4358 }
4359
4360 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4361 /// to an zero vector.
4362 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4363 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4364   SDValue V1 = N->getOperand(0);
4365   SDValue V2 = N->getOperand(1);
4366   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4367   for (unsigned i = 0; i != NumElems; ++i) {
4368     int Idx = N->getMaskElt(i);
4369     if (Idx >= (int)NumElems) {
4370       unsigned Opc = V2.getOpcode();
4371       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4372         continue;
4373       if (Opc != ISD::BUILD_VECTOR ||
4374           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4375         return false;
4376     } else if (Idx >= 0) {
4377       unsigned Opc = V1.getOpcode();
4378       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4379         continue;
4380       if (Opc != ISD::BUILD_VECTOR ||
4381           !X86::isZeroNode(V1.getOperand(Idx)))
4382         return false;
4383     }
4384   }
4385   return true;
4386 }
4387
4388 /// getZeroVector - Returns a vector of specified type with all zero elements.
4389 ///
4390 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4391                              SelectionDAG &DAG, DebugLoc dl) {
4392   assert(VT.isVector() && "Expected a vector type");
4393
4394   // Always build SSE zero vectors as <4 x i32> bitcasted
4395   // to their dest type. This ensures they get CSE'd.
4396   SDValue Vec;
4397   if (VT.is128BitVector()) {  // SSE
4398     if (Subtarget->hasSSE2()) {  // SSE2
4399       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4400       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4401     } else { // SSE1
4402       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4403       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4404     }
4405   } else if (VT.is256BitVector()) { // AVX
4406     if (Subtarget->hasInt256()) { // AVX2
4407       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4408       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4409       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4410     } else {
4411       // 256-bit logic and arithmetic instructions in AVX are all
4412       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4413       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4414       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4415       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4416     }
4417   } else
4418     llvm_unreachable("Unexpected vector type");
4419
4420   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4421 }
4422
4423 /// getOnesVector - Returns a vector of specified type with all bits set.
4424 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4425 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4426 /// Then bitcast to their original type, ensuring they get CSE'd.
4427 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4428                              DebugLoc dl) {
4429   assert(VT.isVector() && "Expected a vector type");
4430
4431   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4432   SDValue Vec;
4433   if (VT.is256BitVector()) {
4434     if (HasInt256) { // AVX2
4435       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4436       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4437     } else { // AVX
4438       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4439       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4440     }
4441   } else if (VT.is128BitVector()) {
4442     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4443   } else
4444     llvm_unreachable("Unexpected vector type");
4445
4446   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4447 }
4448
4449 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4450 /// that point to V2 points to its first element.
4451 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4452   for (unsigned i = 0; i != NumElems; ++i) {
4453     if (Mask[i] > (int)NumElems) {
4454       Mask[i] = NumElems;
4455     }
4456   }
4457 }
4458
4459 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4460 /// operation of specified width.
4461 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4462                        SDValue V2) {
4463   unsigned NumElems = VT.getVectorNumElements();
4464   SmallVector<int, 8> Mask;
4465   Mask.push_back(NumElems);
4466   for (unsigned i = 1; i != NumElems; ++i)
4467     Mask.push_back(i);
4468   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4469 }
4470
4471 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4472 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4473                           SDValue V2) {
4474   unsigned NumElems = VT.getVectorNumElements();
4475   SmallVector<int, 8> Mask;
4476   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4477     Mask.push_back(i);
4478     Mask.push_back(i + NumElems);
4479   }
4480   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4481 }
4482
4483 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4484 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4485                           SDValue V2) {
4486   unsigned NumElems = VT.getVectorNumElements();
4487   SmallVector<int, 8> Mask;
4488   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4489     Mask.push_back(i + Half);
4490     Mask.push_back(i + NumElems + Half);
4491   }
4492   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4493 }
4494
4495 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4496 // a generic shuffle instruction because the target has no such instructions.
4497 // Generate shuffles which repeat i16 and i8 several times until they can be
4498 // represented by v4f32 and then be manipulated by target suported shuffles.
4499 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4500   EVT VT = V.getValueType();
4501   int NumElems = VT.getVectorNumElements();
4502   DebugLoc dl = V.getDebugLoc();
4503
4504   while (NumElems > 4) {
4505     if (EltNo < NumElems/2) {
4506       V = getUnpackl(DAG, dl, VT, V, V);
4507     } else {
4508       V = getUnpackh(DAG, dl, VT, V, V);
4509       EltNo -= NumElems/2;
4510     }
4511     NumElems >>= 1;
4512   }
4513   return V;
4514 }
4515
4516 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4517 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4518   EVT VT = V.getValueType();
4519   DebugLoc dl = V.getDebugLoc();
4520
4521   if (VT.is128BitVector()) {
4522     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4523     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4524     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4525                              &SplatMask[0]);
4526   } else if (VT.is256BitVector()) {
4527     // To use VPERMILPS to splat scalars, the second half of indicies must
4528     // refer to the higher part, which is a duplication of the lower one,
4529     // because VPERMILPS can only handle in-lane permutations.
4530     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4531                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4532
4533     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4534     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4535                              &SplatMask[0]);
4536   } else
4537     llvm_unreachable("Vector size not supported");
4538
4539   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4540 }
4541
4542 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4543 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4544   EVT SrcVT = SV->getValueType(0);
4545   SDValue V1 = SV->getOperand(0);
4546   DebugLoc dl = SV->getDebugLoc();
4547
4548   int EltNo = SV->getSplatIndex();
4549   int NumElems = SrcVT.getVectorNumElements();
4550   bool Is256BitVec = SrcVT.is256BitVector();
4551
4552   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4553          "Unknown how to promote splat for type");
4554
4555   // Extract the 128-bit part containing the splat element and update
4556   // the splat element index when it refers to the higher register.
4557   if (Is256BitVec) {
4558     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4559     if (EltNo >= NumElems/2)
4560       EltNo -= NumElems/2;
4561   }
4562
4563   // All i16 and i8 vector types can't be used directly by a generic shuffle
4564   // instruction because the target has no such instruction. Generate shuffles
4565   // which repeat i16 and i8 several times until they fit in i32, and then can
4566   // be manipulated by target suported shuffles.
4567   EVT EltVT = SrcVT.getVectorElementType();
4568   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4569     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4570
4571   // Recreate the 256-bit vector and place the same 128-bit vector
4572   // into the low and high part. This is necessary because we want
4573   // to use VPERM* to shuffle the vectors
4574   if (Is256BitVec) {
4575     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4576   }
4577
4578   return getLegalSplat(DAG, V1, EltNo);
4579 }
4580
4581 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4582 /// vector of zero or undef vector.  This produces a shuffle where the low
4583 /// element of V2 is swizzled into the zero/undef vector, landing at element
4584 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4585 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4586                                            bool IsZero,
4587                                            const X86Subtarget *Subtarget,
4588                                            SelectionDAG &DAG) {
4589   EVT VT = V2.getValueType();
4590   SDValue V1 = IsZero
4591     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4592   unsigned NumElems = VT.getVectorNumElements();
4593   SmallVector<int, 16> MaskVec;
4594   for (unsigned i = 0; i != NumElems; ++i)
4595     // If this is the insertion idx, put the low elt of V2 here.
4596     MaskVec.push_back(i == Idx ? NumElems : i);
4597   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4598 }
4599
4600 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4601 /// target specific opcode. Returns true if the Mask could be calculated.
4602 /// Sets IsUnary to true if only uses one source.
4603 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4604                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4605   unsigned NumElems = VT.getVectorNumElements();
4606   SDValue ImmN;
4607
4608   IsUnary = false;
4609   switch(N->getOpcode()) {
4610   case X86ISD::SHUFP:
4611     ImmN = N->getOperand(N->getNumOperands()-1);
4612     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4613     break;
4614   case X86ISD::UNPCKH:
4615     DecodeUNPCKHMask(VT, Mask);
4616     break;
4617   case X86ISD::UNPCKL:
4618     DecodeUNPCKLMask(VT, Mask);
4619     break;
4620   case X86ISD::MOVHLPS:
4621     DecodeMOVHLPSMask(NumElems, Mask);
4622     break;
4623   case X86ISD::MOVLHPS:
4624     DecodeMOVLHPSMask(NumElems, Mask);
4625     break;
4626   case X86ISD::PALIGNR:
4627     ImmN = N->getOperand(N->getNumOperands()-1);
4628     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4629     break;
4630   case X86ISD::PSHUFD:
4631   case X86ISD::VPERMILP:
4632     ImmN = N->getOperand(N->getNumOperands()-1);
4633     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4634     IsUnary = true;
4635     break;
4636   case X86ISD::PSHUFHW:
4637     ImmN = N->getOperand(N->getNumOperands()-1);
4638     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4639     IsUnary = true;
4640     break;
4641   case X86ISD::PSHUFLW:
4642     ImmN = N->getOperand(N->getNumOperands()-1);
4643     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4644     IsUnary = true;
4645     break;
4646   case X86ISD::VPERMI:
4647     ImmN = N->getOperand(N->getNumOperands()-1);
4648     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4649     IsUnary = true;
4650     break;
4651   case X86ISD::MOVSS:
4652   case X86ISD::MOVSD: {
4653     // The index 0 always comes from the first element of the second source,
4654     // this is why MOVSS and MOVSD are used in the first place. The other
4655     // elements come from the other positions of the first source vector
4656     Mask.push_back(NumElems);
4657     for (unsigned i = 1; i != NumElems; ++i) {
4658       Mask.push_back(i);
4659     }
4660     break;
4661   }
4662   case X86ISD::VPERM2X128:
4663     ImmN = N->getOperand(N->getNumOperands()-1);
4664     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4665     if (Mask.empty()) return false;
4666     break;
4667   case X86ISD::MOVDDUP:
4668   case X86ISD::MOVLHPD:
4669   case X86ISD::MOVLPD:
4670   case X86ISD::MOVLPS:
4671   case X86ISD::MOVSHDUP:
4672   case X86ISD::MOVSLDUP:
4673     // Not yet implemented
4674     return false;
4675   default: llvm_unreachable("unknown target shuffle node");
4676   }
4677
4678   return true;
4679 }
4680
4681 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4682 /// element of the result of the vector shuffle.
4683 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4684                                    unsigned Depth) {
4685   if (Depth == 6)
4686     return SDValue();  // Limit search depth.
4687
4688   SDValue V = SDValue(N, 0);
4689   EVT VT = V.getValueType();
4690   unsigned Opcode = V.getOpcode();
4691
4692   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4693   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4694     int Elt = SV->getMaskElt(Index);
4695
4696     if (Elt < 0)
4697       return DAG.getUNDEF(VT.getVectorElementType());
4698
4699     unsigned NumElems = VT.getVectorNumElements();
4700     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4701                                          : SV->getOperand(1);
4702     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4703   }
4704
4705   // Recurse into target specific vector shuffles to find scalars.
4706   if (isTargetShuffle(Opcode)) {
4707     MVT ShufVT = V.getValueType().getSimpleVT();
4708     unsigned NumElems = ShufVT.getVectorNumElements();
4709     SmallVector<int, 16> ShuffleMask;
4710     bool IsUnary;
4711
4712     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4713       return SDValue();
4714
4715     int Elt = ShuffleMask[Index];
4716     if (Elt < 0)
4717       return DAG.getUNDEF(ShufVT.getVectorElementType());
4718
4719     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4720                                          : N->getOperand(1);
4721     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4722                                Depth+1);
4723   }
4724
4725   // Actual nodes that may contain scalar elements
4726   if (Opcode == ISD::BITCAST) {
4727     V = V.getOperand(0);
4728     EVT SrcVT = V.getValueType();
4729     unsigned NumElems = VT.getVectorNumElements();
4730
4731     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4732       return SDValue();
4733   }
4734
4735   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4736     return (Index == 0) ? V.getOperand(0)
4737                         : DAG.getUNDEF(VT.getVectorElementType());
4738
4739   if (V.getOpcode() == ISD::BUILD_VECTOR)
4740     return V.getOperand(Index);
4741
4742   return SDValue();
4743 }
4744
4745 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4746 /// shuffle operation which come from a consecutively from a zero. The
4747 /// search can start in two different directions, from left or right.
4748 static
4749 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4750                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4751   unsigned i;
4752   for (i = 0; i != NumElems; ++i) {
4753     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4754     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4755     if (!(Elt.getNode() &&
4756          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4757       break;
4758   }
4759
4760   return i;
4761 }
4762
4763 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4764 /// correspond consecutively to elements from one of the vector operands,
4765 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4766 static
4767 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4768                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4769                               unsigned NumElems, unsigned &OpNum) {
4770   bool SeenV1 = false;
4771   bool SeenV2 = false;
4772
4773   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4774     int Idx = SVOp->getMaskElt(i);
4775     // Ignore undef indicies
4776     if (Idx < 0)
4777       continue;
4778
4779     if (Idx < (int)NumElems)
4780       SeenV1 = true;
4781     else
4782       SeenV2 = true;
4783
4784     // Only accept consecutive elements from the same vector
4785     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4786       return false;
4787   }
4788
4789   OpNum = SeenV1 ? 0 : 1;
4790   return true;
4791 }
4792
4793 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4794 /// logical left shift of a vector.
4795 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4796                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4797   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4798   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4799               false /* check zeros from right */, DAG);
4800   unsigned OpSrc;
4801
4802   if (!NumZeros)
4803     return false;
4804
4805   // Considering the elements in the mask that are not consecutive zeros,
4806   // check if they consecutively come from only one of the source vectors.
4807   //
4808   //               V1 = {X, A, B, C}     0
4809   //                         \  \  \    /
4810   //   vector_shuffle V1, V2 <1, 2, 3, X>
4811   //
4812   if (!isShuffleMaskConsecutive(SVOp,
4813             0,                   // Mask Start Index
4814             NumElems-NumZeros,   // Mask End Index(exclusive)
4815             NumZeros,            // Where to start looking in the src vector
4816             NumElems,            // Number of elements in vector
4817             OpSrc))              // Which source operand ?
4818     return false;
4819
4820   isLeft = false;
4821   ShAmt = NumZeros;
4822   ShVal = SVOp->getOperand(OpSrc);
4823   return true;
4824 }
4825
4826 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4827 /// logical left shift of a vector.
4828 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4829                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4830   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4831   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4832               true /* check zeros from left */, DAG);
4833   unsigned OpSrc;
4834
4835   if (!NumZeros)
4836     return false;
4837
4838   // Considering the elements in the mask that are not consecutive zeros,
4839   // check if they consecutively come from only one of the source vectors.
4840   //
4841   //                           0    { A, B, X, X } = V2
4842   //                          / \    /  /
4843   //   vector_shuffle V1, V2 <X, X, 4, 5>
4844   //
4845   if (!isShuffleMaskConsecutive(SVOp,
4846             NumZeros,     // Mask Start Index
4847             NumElems,     // Mask End Index(exclusive)
4848             0,            // Where to start looking in the src vector
4849             NumElems,     // Number of elements in vector
4850             OpSrc))       // Which source operand ?
4851     return false;
4852
4853   isLeft = true;
4854   ShAmt = NumZeros;
4855   ShVal = SVOp->getOperand(OpSrc);
4856   return true;
4857 }
4858
4859 /// isVectorShift - Returns true if the shuffle can be implemented as a
4860 /// logical left or right shift of a vector.
4861 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4862                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4863   // Although the logic below support any bitwidth size, there are no
4864   // shift instructions which handle more than 128-bit vectors.
4865   if (!SVOp->getValueType(0).is128BitVector())
4866     return false;
4867
4868   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4869       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4870     return true;
4871
4872   return false;
4873 }
4874
4875 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4876 ///
4877 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4878                                        unsigned NumNonZero, unsigned NumZero,
4879                                        SelectionDAG &DAG,
4880                                        const X86Subtarget* Subtarget,
4881                                        const TargetLowering &TLI) {
4882   if (NumNonZero > 8)
4883     return SDValue();
4884
4885   DebugLoc dl = Op.getDebugLoc();
4886   SDValue V(0, 0);
4887   bool First = true;
4888   for (unsigned i = 0; i < 16; ++i) {
4889     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4890     if (ThisIsNonZero && First) {
4891       if (NumZero)
4892         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4893       else
4894         V = DAG.getUNDEF(MVT::v8i16);
4895       First = false;
4896     }
4897
4898     if ((i & 1) != 0) {
4899       SDValue ThisElt(0, 0), LastElt(0, 0);
4900       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4901       if (LastIsNonZero) {
4902         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4903                               MVT::i16, Op.getOperand(i-1));
4904       }
4905       if (ThisIsNonZero) {
4906         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4907         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4908                               ThisElt, DAG.getConstant(8, MVT::i8));
4909         if (LastIsNonZero)
4910           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4911       } else
4912         ThisElt = LastElt;
4913
4914       if (ThisElt.getNode())
4915         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4916                         DAG.getIntPtrConstant(i/2));
4917     }
4918   }
4919
4920   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4921 }
4922
4923 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4924 ///
4925 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4926                                      unsigned NumNonZero, unsigned NumZero,
4927                                      SelectionDAG &DAG,
4928                                      const X86Subtarget* Subtarget,
4929                                      const TargetLowering &TLI) {
4930   if (NumNonZero > 4)
4931     return SDValue();
4932
4933   DebugLoc dl = Op.getDebugLoc();
4934   SDValue V(0, 0);
4935   bool First = true;
4936   for (unsigned i = 0; i < 8; ++i) {
4937     bool isNonZero = (NonZeros & (1 << i)) != 0;
4938     if (isNonZero) {
4939       if (First) {
4940         if (NumZero)
4941           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4942         else
4943           V = DAG.getUNDEF(MVT::v8i16);
4944         First = false;
4945       }
4946       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4947                       MVT::v8i16, V, Op.getOperand(i),
4948                       DAG.getIntPtrConstant(i));
4949     }
4950   }
4951
4952   return V;
4953 }
4954
4955 /// getVShift - Return a vector logical shift node.
4956 ///
4957 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4958                          unsigned NumBits, SelectionDAG &DAG,
4959                          const TargetLowering &TLI, DebugLoc dl) {
4960   assert(VT.is128BitVector() && "Unknown type for VShift");
4961   EVT ShVT = MVT::v2i64;
4962   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4963   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4964   return DAG.getNode(ISD::BITCAST, dl, VT,
4965                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4966                              DAG.getConstant(NumBits,
4967                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4968 }
4969
4970 SDValue
4971 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4972                                           SelectionDAG &DAG) const {
4973
4974   // Check if the scalar load can be widened into a vector load. And if
4975   // the address is "base + cst" see if the cst can be "absorbed" into
4976   // the shuffle mask.
4977   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4978     SDValue Ptr = LD->getBasePtr();
4979     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4980       return SDValue();
4981     EVT PVT = LD->getValueType(0);
4982     if (PVT != MVT::i32 && PVT != MVT::f32)
4983       return SDValue();
4984
4985     int FI = -1;
4986     int64_t Offset = 0;
4987     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4988       FI = FINode->getIndex();
4989       Offset = 0;
4990     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4991                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4992       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4993       Offset = Ptr.getConstantOperandVal(1);
4994       Ptr = Ptr.getOperand(0);
4995     } else {
4996       return SDValue();
4997     }
4998
4999     // FIXME: 256-bit vector instructions don't require a strict alignment,
5000     // improve this code to support it better.
5001     unsigned RequiredAlign = VT.getSizeInBits()/8;
5002     SDValue Chain = LD->getChain();
5003     // Make sure the stack object alignment is at least 16 or 32.
5004     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5005     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5006       if (MFI->isFixedObjectIndex(FI)) {
5007         // Can't change the alignment. FIXME: It's possible to compute
5008         // the exact stack offset and reference FI + adjust offset instead.
5009         // If someone *really* cares about this. That's the way to implement it.
5010         return SDValue();
5011       } else {
5012         MFI->setObjectAlignment(FI, RequiredAlign);
5013       }
5014     }
5015
5016     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5017     // Ptr + (Offset & ~15).
5018     if (Offset < 0)
5019       return SDValue();
5020     if ((Offset % RequiredAlign) & 3)
5021       return SDValue();
5022     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5023     if (StartOffset)
5024       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5025                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5026
5027     int EltNo = (Offset - StartOffset) >> 2;
5028     unsigned NumElems = VT.getVectorNumElements();
5029
5030     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5031     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5032                              LD->getPointerInfo().getWithOffset(StartOffset),
5033                              false, false, false, 0);
5034
5035     SmallVector<int, 8> Mask;
5036     for (unsigned i = 0; i != NumElems; ++i)
5037       Mask.push_back(EltNo);
5038
5039     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5040   }
5041
5042   return SDValue();
5043 }
5044
5045 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5046 /// vector of type 'VT', see if the elements can be replaced by a single large
5047 /// load which has the same value as a build_vector whose operands are 'elts'.
5048 ///
5049 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5050 ///
5051 /// FIXME: we'd also like to handle the case where the last elements are zero
5052 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5053 /// There's even a handy isZeroNode for that purpose.
5054 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5055                                         DebugLoc &DL, SelectionDAG &DAG) {
5056   EVT EltVT = VT.getVectorElementType();
5057   unsigned NumElems = Elts.size();
5058
5059   LoadSDNode *LDBase = NULL;
5060   unsigned LastLoadedElt = -1U;
5061
5062   // For each element in the initializer, see if we've found a load or an undef.
5063   // If we don't find an initial load element, or later load elements are
5064   // non-consecutive, bail out.
5065   for (unsigned i = 0; i < NumElems; ++i) {
5066     SDValue Elt = Elts[i];
5067
5068     if (!Elt.getNode() ||
5069         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5070       return SDValue();
5071     if (!LDBase) {
5072       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5073         return SDValue();
5074       LDBase = cast<LoadSDNode>(Elt.getNode());
5075       LastLoadedElt = i;
5076       continue;
5077     }
5078     if (Elt.getOpcode() == ISD::UNDEF)
5079       continue;
5080
5081     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5082     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5083       return SDValue();
5084     LastLoadedElt = i;
5085   }
5086
5087   // If we have found an entire vector of loads and undefs, then return a large
5088   // load of the entire vector width starting at the base pointer.  If we found
5089   // consecutive loads for the low half, generate a vzext_load node.
5090   if (LastLoadedElt == NumElems - 1) {
5091     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5092       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5093                          LDBase->getPointerInfo(),
5094                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5095                          LDBase->isInvariant(), 0);
5096     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5097                        LDBase->getPointerInfo(),
5098                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5099                        LDBase->isInvariant(), LDBase->getAlignment());
5100   }
5101   if (NumElems == 4 && LastLoadedElt == 1 &&
5102       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5103     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5104     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5105     SDValue ResNode =
5106         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5107                                 LDBase->getPointerInfo(),
5108                                 LDBase->getAlignment(),
5109                                 false/*isVolatile*/, true/*ReadMem*/,
5110                                 false/*WriteMem*/);
5111
5112     // Make sure the newly-created LOAD is in the same position as LDBase in
5113     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5114     // update uses of LDBase's output chain to use the TokenFactor.
5115     if (LDBase->hasAnyUseOfValue(1)) {
5116       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5117                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5118       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5119       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5120                              SDValue(ResNode.getNode(), 1));
5121     }
5122
5123     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5124   }
5125   return SDValue();
5126 }
5127
5128 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5129 /// to generate a splat value for the following cases:
5130 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5131 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5132 /// a scalar load, or a constant.
5133 /// The VBROADCAST node is returned when a pattern is found,
5134 /// or SDValue() otherwise.
5135 SDValue
5136 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5137   if (!Subtarget->hasFp256())
5138     return SDValue();
5139
5140   MVT VT = Op.getValueType().getSimpleVT();
5141   DebugLoc dl = Op.getDebugLoc();
5142
5143   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5144          "Unsupported vector type for broadcast.");
5145
5146   SDValue Ld;
5147   bool ConstSplatVal;
5148
5149   switch (Op.getOpcode()) {
5150     default:
5151       // Unknown pattern found.
5152       return SDValue();
5153
5154     case ISD::BUILD_VECTOR: {
5155       // The BUILD_VECTOR node must be a splat.
5156       if (!isSplatVector(Op.getNode()))
5157         return SDValue();
5158
5159       Ld = Op.getOperand(0);
5160       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5161                      Ld.getOpcode() == ISD::ConstantFP);
5162
5163       // The suspected load node has several users. Make sure that all
5164       // of its users are from the BUILD_VECTOR node.
5165       // Constants may have multiple users.
5166       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5167         return SDValue();
5168       break;
5169     }
5170
5171     case ISD::VECTOR_SHUFFLE: {
5172       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5173
5174       // Shuffles must have a splat mask where the first element is
5175       // broadcasted.
5176       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5177         return SDValue();
5178
5179       SDValue Sc = Op.getOperand(0);
5180       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5181           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5182
5183         if (!Subtarget->hasInt256())
5184           return SDValue();
5185
5186         // Use the register form of the broadcast instruction available on AVX2.
5187         if (VT.is256BitVector())
5188           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5189         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5190       }
5191
5192       Ld = Sc.getOperand(0);
5193       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5194                        Ld.getOpcode() == ISD::ConstantFP);
5195
5196       // The scalar_to_vector node and the suspected
5197       // load node must have exactly one user.
5198       // Constants may have multiple users.
5199       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5200         return SDValue();
5201       break;
5202     }
5203   }
5204
5205   bool Is256 = VT.is256BitVector();
5206
5207   // Handle the broadcasting a single constant scalar from the constant pool
5208   // into a vector. On Sandybridge it is still better to load a constant vector
5209   // from the constant pool and not to broadcast it from a scalar.
5210   if (ConstSplatVal && Subtarget->hasInt256()) {
5211     EVT CVT = Ld.getValueType();
5212     assert(!CVT.isVector() && "Must not broadcast a vector type");
5213     unsigned ScalarSize = CVT.getSizeInBits();
5214
5215     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5216       const Constant *C = 0;
5217       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5218         C = CI->getConstantIntValue();
5219       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5220         C = CF->getConstantFPValue();
5221
5222       assert(C && "Invalid constant type");
5223
5224       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5225       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5226       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5227                        MachinePointerInfo::getConstantPool(),
5228                        false, false, false, Alignment);
5229
5230       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5231     }
5232   }
5233
5234   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5235   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5236
5237   // Handle AVX2 in-register broadcasts.
5238   if (!IsLoad && Subtarget->hasInt256() &&
5239       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5240     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5241
5242   // The scalar source must be a normal load.
5243   if (!IsLoad)
5244     return SDValue();
5245
5246   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5247     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5248
5249   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5250   // double since there is no vbroadcastsd xmm
5251   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5252     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5253       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5254   }
5255
5256   // Unsupported broadcast.
5257   return SDValue();
5258 }
5259
5260 SDValue
5261 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5262   EVT VT = Op.getValueType();
5263
5264   // Skip if insert_vec_elt is not supported.
5265   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5266     return SDValue();
5267
5268   DebugLoc DL = Op.getDebugLoc();
5269   unsigned NumElems = Op.getNumOperands();
5270
5271   SDValue VecIn1;
5272   SDValue VecIn2;
5273   SmallVector<unsigned, 4> InsertIndices;
5274   SmallVector<int, 8> Mask(NumElems, -1);
5275
5276   for (unsigned i = 0; i != NumElems; ++i) {
5277     unsigned Opc = Op.getOperand(i).getOpcode();
5278
5279     if (Opc == ISD::UNDEF)
5280       continue;
5281
5282     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5283       // Quit if more than 1 elements need inserting.
5284       if (InsertIndices.size() > 1)
5285         return SDValue();
5286
5287       InsertIndices.push_back(i);
5288       continue;
5289     }
5290
5291     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5292     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5293
5294     // Quit if extracted from vector of different type.
5295     if (ExtractedFromVec.getValueType() != VT)
5296       return SDValue();
5297
5298     // Quit if non-constant index.
5299     if (!isa<ConstantSDNode>(ExtIdx))
5300       return SDValue();
5301
5302     if (VecIn1.getNode() == 0)
5303       VecIn1 = ExtractedFromVec;
5304     else if (VecIn1 != ExtractedFromVec) {
5305       if (VecIn2.getNode() == 0)
5306         VecIn2 = ExtractedFromVec;
5307       else if (VecIn2 != ExtractedFromVec)
5308         // Quit if more than 2 vectors to shuffle
5309         return SDValue();
5310     }
5311
5312     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5313
5314     if (ExtractedFromVec == VecIn1)
5315       Mask[i] = Idx;
5316     else if (ExtractedFromVec == VecIn2)
5317       Mask[i] = Idx + NumElems;
5318   }
5319
5320   if (VecIn1.getNode() == 0)
5321     return SDValue();
5322
5323   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5324   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5325   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5326     unsigned Idx = InsertIndices[i];
5327     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5328                      DAG.getIntPtrConstant(Idx));
5329   }
5330
5331   return NV;
5332 }
5333
5334 SDValue
5335 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5336   DebugLoc dl = Op.getDebugLoc();
5337
5338   MVT VT = Op.getValueType().getSimpleVT();
5339   MVT ExtVT = VT.getVectorElementType();
5340   unsigned NumElems = Op.getNumOperands();
5341
5342   // Vectors containing all zeros can be matched by pxor and xorps later
5343   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5344     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5345     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5346     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5347       return Op;
5348
5349     return getZeroVector(VT, Subtarget, DAG, dl);
5350   }
5351
5352   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5353   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5354   // vpcmpeqd on 256-bit vectors.
5355   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5356     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5357       return Op;
5358
5359     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5360   }
5361
5362   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5363   if (Broadcast.getNode())
5364     return Broadcast;
5365
5366   unsigned EVTBits = ExtVT.getSizeInBits();
5367
5368   unsigned NumZero  = 0;
5369   unsigned NumNonZero = 0;
5370   unsigned NonZeros = 0;
5371   bool IsAllConstants = true;
5372   SmallSet<SDValue, 8> Values;
5373   for (unsigned i = 0; i < NumElems; ++i) {
5374     SDValue Elt = Op.getOperand(i);
5375     if (Elt.getOpcode() == ISD::UNDEF)
5376       continue;
5377     Values.insert(Elt);
5378     if (Elt.getOpcode() != ISD::Constant &&
5379         Elt.getOpcode() != ISD::ConstantFP)
5380       IsAllConstants = false;
5381     if (X86::isZeroNode(Elt))
5382       NumZero++;
5383     else {
5384       NonZeros |= (1 << i);
5385       NumNonZero++;
5386     }
5387   }
5388
5389   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5390   if (NumNonZero == 0)
5391     return DAG.getUNDEF(VT);
5392
5393   // Special case for single non-zero, non-undef, element.
5394   if (NumNonZero == 1) {
5395     unsigned Idx = CountTrailingZeros_32(NonZeros);
5396     SDValue Item = Op.getOperand(Idx);
5397
5398     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5399     // the value are obviously zero, truncate the value to i32 and do the
5400     // insertion that way.  Only do this if the value is non-constant or if the
5401     // value is a constant being inserted into element 0.  It is cheaper to do
5402     // a constant pool load than it is to do a movd + shuffle.
5403     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5404         (!IsAllConstants || Idx == 0)) {
5405       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5406         // Handle SSE only.
5407         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5408         EVT VecVT = MVT::v4i32;
5409         unsigned VecElts = 4;
5410
5411         // Truncate the value (which may itself be a constant) to i32, and
5412         // convert it to a vector with movd (S2V+shuffle to zero extend).
5413         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5414         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5415         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5416
5417         // Now we have our 32-bit value zero extended in the low element of
5418         // a vector.  If Idx != 0, swizzle it into place.
5419         if (Idx != 0) {
5420           SmallVector<int, 4> Mask;
5421           Mask.push_back(Idx);
5422           for (unsigned i = 1; i != VecElts; ++i)
5423             Mask.push_back(i);
5424           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5425                                       &Mask[0]);
5426         }
5427         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5428       }
5429     }
5430
5431     // If we have a constant or non-constant insertion into the low element of
5432     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5433     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5434     // depending on what the source datatype is.
5435     if (Idx == 0) {
5436       if (NumZero == 0)
5437         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5438
5439       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5440           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5441         if (VT.is256BitVector()) {
5442           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5443           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5444                              Item, DAG.getIntPtrConstant(0));
5445         }
5446         assert(VT.is128BitVector() && "Expected an SSE value type!");
5447         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5448         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5449         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5450       }
5451
5452       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5453         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5454         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5455         if (VT.is256BitVector()) {
5456           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5457           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5458         } else {
5459           assert(VT.is128BitVector() && "Expected an SSE value type!");
5460           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5461         }
5462         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5463       }
5464     }
5465
5466     // Is it a vector logical left shift?
5467     if (NumElems == 2 && Idx == 1 &&
5468         X86::isZeroNode(Op.getOperand(0)) &&
5469         !X86::isZeroNode(Op.getOperand(1))) {
5470       unsigned NumBits = VT.getSizeInBits();
5471       return getVShift(true, VT,
5472                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5473                                    VT, Op.getOperand(1)),
5474                        NumBits/2, DAG, *this, dl);
5475     }
5476
5477     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5478       return SDValue();
5479
5480     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5481     // is a non-constant being inserted into an element other than the low one,
5482     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5483     // movd/movss) to move this into the low element, then shuffle it into
5484     // place.
5485     if (EVTBits == 32) {
5486       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5487
5488       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5489       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5490       SmallVector<int, 8> MaskVec;
5491       for (unsigned i = 0; i != NumElems; ++i)
5492         MaskVec.push_back(i == Idx ? 0 : 1);
5493       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5494     }
5495   }
5496
5497   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5498   if (Values.size() == 1) {
5499     if (EVTBits == 32) {
5500       // Instead of a shuffle like this:
5501       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5502       // Check if it's possible to issue this instead.
5503       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5504       unsigned Idx = CountTrailingZeros_32(NonZeros);
5505       SDValue Item = Op.getOperand(Idx);
5506       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5507         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5508     }
5509     return SDValue();
5510   }
5511
5512   // A vector full of immediates; various special cases are already
5513   // handled, so this is best done with a single constant-pool load.
5514   if (IsAllConstants)
5515     return SDValue();
5516
5517   // For AVX-length vectors, build the individual 128-bit pieces and use
5518   // shuffles to put them in place.
5519   if (VT.is256BitVector()) {
5520     SmallVector<SDValue, 32> V;
5521     for (unsigned i = 0; i != NumElems; ++i)
5522       V.push_back(Op.getOperand(i));
5523
5524     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5525
5526     // Build both the lower and upper subvector.
5527     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5528     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5529                                 NumElems/2);
5530
5531     // Recreate the wider vector with the lower and upper part.
5532     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5533   }
5534
5535   // Let legalizer expand 2-wide build_vectors.
5536   if (EVTBits == 64) {
5537     if (NumNonZero == 1) {
5538       // One half is zero or undef.
5539       unsigned Idx = CountTrailingZeros_32(NonZeros);
5540       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5541                                  Op.getOperand(Idx));
5542       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5543     }
5544     return SDValue();
5545   }
5546
5547   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5548   if (EVTBits == 8 && NumElems == 16) {
5549     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5550                                         Subtarget, *this);
5551     if (V.getNode()) return V;
5552   }
5553
5554   if (EVTBits == 16 && NumElems == 8) {
5555     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5556                                       Subtarget, *this);
5557     if (V.getNode()) return V;
5558   }
5559
5560   // If element VT is == 32 bits, turn it into a number of shuffles.
5561   SmallVector<SDValue, 8> V(NumElems);
5562   if (NumElems == 4 && NumZero > 0) {
5563     for (unsigned i = 0; i < 4; ++i) {
5564       bool isZero = !(NonZeros & (1 << i));
5565       if (isZero)
5566         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5567       else
5568         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5569     }
5570
5571     for (unsigned i = 0; i < 2; ++i) {
5572       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5573         default: break;
5574         case 0:
5575           V[i] = V[i*2];  // Must be a zero vector.
5576           break;
5577         case 1:
5578           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5579           break;
5580         case 2:
5581           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5582           break;
5583         case 3:
5584           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5585           break;
5586       }
5587     }
5588
5589     bool Reverse1 = (NonZeros & 0x3) == 2;
5590     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5591     int MaskVec[] = {
5592       Reverse1 ? 1 : 0,
5593       Reverse1 ? 0 : 1,
5594       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5595       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5596     };
5597     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5598   }
5599
5600   if (Values.size() > 1 && VT.is128BitVector()) {
5601     // Check for a build vector of consecutive loads.
5602     for (unsigned i = 0; i < NumElems; ++i)
5603       V[i] = Op.getOperand(i);
5604
5605     // Check for elements which are consecutive loads.
5606     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5607     if (LD.getNode())
5608       return LD;
5609
5610     // Check for a build vector from mostly shuffle plus few inserting.
5611     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5612     if (Sh.getNode())
5613       return Sh;
5614
5615     // For SSE 4.1, use insertps to put the high elements into the low element.
5616     if (getSubtarget()->hasSSE41()) {
5617       SDValue Result;
5618       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5619         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5620       else
5621         Result = DAG.getUNDEF(VT);
5622
5623       for (unsigned i = 1; i < NumElems; ++i) {
5624         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5625         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5626                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5627       }
5628       return Result;
5629     }
5630
5631     // Otherwise, expand into a number of unpckl*, start by extending each of
5632     // our (non-undef) elements to the full vector width with the element in the
5633     // bottom slot of the vector (which generates no code for SSE).
5634     for (unsigned i = 0; i < NumElems; ++i) {
5635       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5636         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5637       else
5638         V[i] = DAG.getUNDEF(VT);
5639     }
5640
5641     // Next, we iteratively mix elements, e.g. for v4f32:
5642     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5643     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5644     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5645     unsigned EltStride = NumElems >> 1;
5646     while (EltStride != 0) {
5647       for (unsigned i = 0; i < EltStride; ++i) {
5648         // If V[i+EltStride] is undef and this is the first round of mixing,
5649         // then it is safe to just drop this shuffle: V[i] is already in the
5650         // right place, the one element (since it's the first round) being
5651         // inserted as undef can be dropped.  This isn't safe for successive
5652         // rounds because they will permute elements within both vectors.
5653         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5654             EltStride == NumElems/2)
5655           continue;
5656
5657         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5658       }
5659       EltStride >>= 1;
5660     }
5661     return V[0];
5662   }
5663   return SDValue();
5664 }
5665
5666 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5667 // to create 256-bit vectors from two other 128-bit ones.
5668 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5669   DebugLoc dl = Op.getDebugLoc();
5670   MVT ResVT = Op.getValueType().getSimpleVT();
5671
5672   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5673
5674   SDValue V1 = Op.getOperand(0);
5675   SDValue V2 = Op.getOperand(1);
5676   unsigned NumElems = ResVT.getVectorNumElements();
5677
5678   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5679 }
5680
5681 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5682   assert(Op.getNumOperands() == 2);
5683
5684   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5685   // from two other 128-bit ones.
5686   return LowerAVXCONCAT_VECTORS(Op, DAG);
5687 }
5688
5689 // Try to lower a shuffle node into a simple blend instruction.
5690 static SDValue
5691 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5692                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5693   SDValue V1 = SVOp->getOperand(0);
5694   SDValue V2 = SVOp->getOperand(1);
5695   DebugLoc dl = SVOp->getDebugLoc();
5696   MVT VT = SVOp->getValueType(0).getSimpleVT();
5697   MVT EltVT = VT.getVectorElementType();
5698   unsigned NumElems = VT.getVectorNumElements();
5699
5700   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5701     return SDValue();
5702   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5703     return SDValue();
5704
5705   // Check the mask for BLEND and build the value.
5706   unsigned MaskValue = 0;
5707   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5708   unsigned NumLanes = (NumElems-1)/8 + 1;
5709   unsigned NumElemsInLane = NumElems / NumLanes;
5710
5711   // Blend for v16i16 should be symetric for the both lanes.
5712   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5713
5714     int SndLaneEltIdx = (NumLanes == 2) ?
5715       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5716     int EltIdx = SVOp->getMaskElt(i);
5717
5718     if ((EltIdx < 0 || EltIdx == (int)i) &&
5719         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5720       continue;
5721
5722     if (((unsigned)EltIdx == (i + NumElems)) &&
5723         (SndLaneEltIdx < 0 ||
5724          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5725       MaskValue |= (1<<i);
5726     else
5727       return SDValue();
5728   }
5729
5730   // Convert i32 vectors to floating point if it is not AVX2.
5731   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5732   MVT BlendVT = VT;
5733   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5734     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5735                                NumElems);
5736     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5737     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5738   }
5739
5740   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5741                             DAG.getConstant(MaskValue, MVT::i32));
5742   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5743 }
5744
5745 // v8i16 shuffles - Prefer shuffles in the following order:
5746 // 1. [all]   pshuflw, pshufhw, optional move
5747 // 2. [ssse3] 1 x pshufb
5748 // 3. [ssse3] 2 x pshufb + 1 x por
5749 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5750 static SDValue
5751 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5752                          SelectionDAG &DAG) {
5753   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5754   SDValue V1 = SVOp->getOperand(0);
5755   SDValue V2 = SVOp->getOperand(1);
5756   DebugLoc dl = SVOp->getDebugLoc();
5757   SmallVector<int, 8> MaskVals;
5758
5759   // Determine if more than 1 of the words in each of the low and high quadwords
5760   // of the result come from the same quadword of one of the two inputs.  Undef
5761   // mask values count as coming from any quadword, for better codegen.
5762   unsigned LoQuad[] = { 0, 0, 0, 0 };
5763   unsigned HiQuad[] = { 0, 0, 0, 0 };
5764   std::bitset<4> InputQuads;
5765   for (unsigned i = 0; i < 8; ++i) {
5766     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5767     int EltIdx = SVOp->getMaskElt(i);
5768     MaskVals.push_back(EltIdx);
5769     if (EltIdx < 0) {
5770       ++Quad[0];
5771       ++Quad[1];
5772       ++Quad[2];
5773       ++Quad[3];
5774       continue;
5775     }
5776     ++Quad[EltIdx / 4];
5777     InputQuads.set(EltIdx / 4);
5778   }
5779
5780   int BestLoQuad = -1;
5781   unsigned MaxQuad = 1;
5782   for (unsigned i = 0; i < 4; ++i) {
5783     if (LoQuad[i] > MaxQuad) {
5784       BestLoQuad = i;
5785       MaxQuad = LoQuad[i];
5786     }
5787   }
5788
5789   int BestHiQuad = -1;
5790   MaxQuad = 1;
5791   for (unsigned i = 0; i < 4; ++i) {
5792     if (HiQuad[i] > MaxQuad) {
5793       BestHiQuad = i;
5794       MaxQuad = HiQuad[i];
5795     }
5796   }
5797
5798   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5799   // of the two input vectors, shuffle them into one input vector so only a
5800   // single pshufb instruction is necessary. If There are more than 2 input
5801   // quads, disable the next transformation since it does not help SSSE3.
5802   bool V1Used = InputQuads[0] || InputQuads[1];
5803   bool V2Used = InputQuads[2] || InputQuads[3];
5804   if (Subtarget->hasSSSE3()) {
5805     if (InputQuads.count() == 2 && V1Used && V2Used) {
5806       BestLoQuad = InputQuads[0] ? 0 : 1;
5807       BestHiQuad = InputQuads[2] ? 2 : 3;
5808     }
5809     if (InputQuads.count() > 2) {
5810       BestLoQuad = -1;
5811       BestHiQuad = -1;
5812     }
5813   }
5814
5815   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5816   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5817   // words from all 4 input quadwords.
5818   SDValue NewV;
5819   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5820     int MaskV[] = {
5821       BestLoQuad < 0 ? 0 : BestLoQuad,
5822       BestHiQuad < 0 ? 1 : BestHiQuad
5823     };
5824     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5825                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5826                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5827     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5828
5829     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5830     // source words for the shuffle, to aid later transformations.
5831     bool AllWordsInNewV = true;
5832     bool InOrder[2] = { true, true };
5833     for (unsigned i = 0; i != 8; ++i) {
5834       int idx = MaskVals[i];
5835       if (idx != (int)i)
5836         InOrder[i/4] = false;
5837       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5838         continue;
5839       AllWordsInNewV = false;
5840       break;
5841     }
5842
5843     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5844     if (AllWordsInNewV) {
5845       for (int i = 0; i != 8; ++i) {
5846         int idx = MaskVals[i];
5847         if (idx < 0)
5848           continue;
5849         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5850         if ((idx != i) && idx < 4)
5851           pshufhw = false;
5852         if ((idx != i) && idx > 3)
5853           pshuflw = false;
5854       }
5855       V1 = NewV;
5856       V2Used = false;
5857       BestLoQuad = 0;
5858       BestHiQuad = 1;
5859     }
5860
5861     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5862     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5863     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5864       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5865       unsigned TargetMask = 0;
5866       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5867                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5868       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5869       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5870                              getShufflePSHUFLWImmediate(SVOp);
5871       V1 = NewV.getOperand(0);
5872       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5873     }
5874   }
5875
5876   // Promote splats to a larger type which usually leads to more efficient code.
5877   // FIXME: Is this true if pshufb is available?
5878   if (SVOp->isSplat())
5879     return PromoteSplat(SVOp, DAG);
5880
5881   // If we have SSSE3, and all words of the result are from 1 input vector,
5882   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5883   // is present, fall back to case 4.
5884   if (Subtarget->hasSSSE3()) {
5885     SmallVector<SDValue,16> pshufbMask;
5886
5887     // If we have elements from both input vectors, set the high bit of the
5888     // shuffle mask element to zero out elements that come from V2 in the V1
5889     // mask, and elements that come from V1 in the V2 mask, so that the two
5890     // results can be OR'd together.
5891     bool TwoInputs = V1Used && V2Used;
5892     for (unsigned i = 0; i != 8; ++i) {
5893       int EltIdx = MaskVals[i] * 2;
5894       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5895       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5896       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5897       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5898     }
5899     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5900     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5901                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5902                                  MVT::v16i8, &pshufbMask[0], 16));
5903     if (!TwoInputs)
5904       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5905
5906     // Calculate the shuffle mask for the second input, shuffle it, and
5907     // OR it with the first shuffled input.
5908     pshufbMask.clear();
5909     for (unsigned i = 0; i != 8; ++i) {
5910       int EltIdx = MaskVals[i] * 2;
5911       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5912       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5913       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5914       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5915     }
5916     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5917     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5918                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5919                                  MVT::v16i8, &pshufbMask[0], 16));
5920     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5921     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5922   }
5923
5924   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5925   // and update MaskVals with new element order.
5926   std::bitset<8> InOrder;
5927   if (BestLoQuad >= 0) {
5928     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5929     for (int i = 0; i != 4; ++i) {
5930       int idx = MaskVals[i];
5931       if (idx < 0) {
5932         InOrder.set(i);
5933       } else if ((idx / 4) == BestLoQuad) {
5934         MaskV[i] = idx & 3;
5935         InOrder.set(i);
5936       }
5937     }
5938     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5939                                 &MaskV[0]);
5940
5941     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5942       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5943       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5944                                   NewV.getOperand(0),
5945                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5946     }
5947   }
5948
5949   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5950   // and update MaskVals with the new element order.
5951   if (BestHiQuad >= 0) {
5952     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5953     for (unsigned i = 4; i != 8; ++i) {
5954       int idx = MaskVals[i];
5955       if (idx < 0) {
5956         InOrder.set(i);
5957       } else if ((idx / 4) == BestHiQuad) {
5958         MaskV[i] = (idx & 3) + 4;
5959         InOrder.set(i);
5960       }
5961     }
5962     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5963                                 &MaskV[0]);
5964
5965     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5966       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5967       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5968                                   NewV.getOperand(0),
5969                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5970     }
5971   }
5972
5973   // In case BestHi & BestLo were both -1, which means each quadword has a word
5974   // from each of the four input quadwords, calculate the InOrder bitvector now
5975   // before falling through to the insert/extract cleanup.
5976   if (BestLoQuad == -1 && BestHiQuad == -1) {
5977     NewV = V1;
5978     for (int i = 0; i != 8; ++i)
5979       if (MaskVals[i] < 0 || MaskVals[i] == i)
5980         InOrder.set(i);
5981   }
5982
5983   // The other elements are put in the right place using pextrw and pinsrw.
5984   for (unsigned i = 0; i != 8; ++i) {
5985     if (InOrder[i])
5986       continue;
5987     int EltIdx = MaskVals[i];
5988     if (EltIdx < 0)
5989       continue;
5990     SDValue ExtOp = (EltIdx < 8) ?
5991       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5992                   DAG.getIntPtrConstant(EltIdx)) :
5993       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5994                   DAG.getIntPtrConstant(EltIdx - 8));
5995     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5996                        DAG.getIntPtrConstant(i));
5997   }
5998   return NewV;
5999 }
6000
6001 // v16i8 shuffles - Prefer shuffles in the following order:
6002 // 1. [ssse3] 1 x pshufb
6003 // 2. [ssse3] 2 x pshufb + 1 x por
6004 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6005 static
6006 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6007                                  SelectionDAG &DAG,
6008                                  const X86TargetLowering &TLI) {
6009   SDValue V1 = SVOp->getOperand(0);
6010   SDValue V2 = SVOp->getOperand(1);
6011   DebugLoc dl = SVOp->getDebugLoc();
6012   ArrayRef<int> MaskVals = SVOp->getMask();
6013
6014   // Promote splats to a larger type which usually leads to more efficient code.
6015   // FIXME: Is this true if pshufb is available?
6016   if (SVOp->isSplat())
6017     return PromoteSplat(SVOp, DAG);
6018
6019   // If we have SSSE3, case 1 is generated when all result bytes come from
6020   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6021   // present, fall back to case 3.
6022
6023   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6024   if (TLI.getSubtarget()->hasSSSE3()) {
6025     SmallVector<SDValue,16> pshufbMask;
6026
6027     // If all result elements are from one input vector, then only translate
6028     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6029     //
6030     // Otherwise, we have elements from both input vectors, and must zero out
6031     // elements that come from V2 in the first mask, and V1 in the second mask
6032     // so that we can OR them together.
6033     for (unsigned i = 0; i != 16; ++i) {
6034       int EltIdx = MaskVals[i];
6035       if (EltIdx < 0 || EltIdx >= 16)
6036         EltIdx = 0x80;
6037       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6038     }
6039     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6040                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6041                                  MVT::v16i8, &pshufbMask[0], 16));
6042
6043     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6044     // the 2nd operand if it's undefined or zero.
6045     if (V2.getOpcode() == ISD::UNDEF ||
6046         ISD::isBuildVectorAllZeros(V2.getNode()))
6047       return V1;
6048
6049     // Calculate the shuffle mask for the second input, shuffle it, and
6050     // OR it with the first shuffled input.
6051     pshufbMask.clear();
6052     for (unsigned i = 0; i != 16; ++i) {
6053       int EltIdx = MaskVals[i];
6054       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6055       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6056     }
6057     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6058                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6059                                  MVT::v16i8, &pshufbMask[0], 16));
6060     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6061   }
6062
6063   // No SSSE3 - Calculate in place words and then fix all out of place words
6064   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6065   // the 16 different words that comprise the two doublequadword input vectors.
6066   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6067   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6068   SDValue NewV = V1;
6069   for (int i = 0; i != 8; ++i) {
6070     int Elt0 = MaskVals[i*2];
6071     int Elt1 = MaskVals[i*2+1];
6072
6073     // This word of the result is all undef, skip it.
6074     if (Elt0 < 0 && Elt1 < 0)
6075       continue;
6076
6077     // This word of the result is already in the correct place, skip it.
6078     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6079       continue;
6080
6081     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6082     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6083     SDValue InsElt;
6084
6085     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6086     // using a single extract together, load it and store it.
6087     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6088       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6089                            DAG.getIntPtrConstant(Elt1 / 2));
6090       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6091                         DAG.getIntPtrConstant(i));
6092       continue;
6093     }
6094
6095     // If Elt1 is defined, extract it from the appropriate source.  If the
6096     // source byte is not also odd, shift the extracted word left 8 bits
6097     // otherwise clear the bottom 8 bits if we need to do an or.
6098     if (Elt1 >= 0) {
6099       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6100                            DAG.getIntPtrConstant(Elt1 / 2));
6101       if ((Elt1 & 1) == 0)
6102         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6103                              DAG.getConstant(8,
6104                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6105       else if (Elt0 >= 0)
6106         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6107                              DAG.getConstant(0xFF00, MVT::i16));
6108     }
6109     // If Elt0 is defined, extract it from the appropriate source.  If the
6110     // source byte is not also even, shift the extracted word right 8 bits. If
6111     // Elt1 was also defined, OR the extracted values together before
6112     // inserting them in the result.
6113     if (Elt0 >= 0) {
6114       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6115                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6116       if ((Elt0 & 1) != 0)
6117         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6118                               DAG.getConstant(8,
6119                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6120       else if (Elt1 >= 0)
6121         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6122                              DAG.getConstant(0x00FF, MVT::i16));
6123       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6124                          : InsElt0;
6125     }
6126     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6127                        DAG.getIntPtrConstant(i));
6128   }
6129   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6130 }
6131
6132 // v32i8 shuffles - Translate to VPSHUFB if possible.
6133 static
6134 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6135                                  const X86Subtarget *Subtarget,
6136                                  SelectionDAG &DAG) {
6137   MVT VT = SVOp->getValueType(0).getSimpleVT();
6138   SDValue V1 = SVOp->getOperand(0);
6139   SDValue V2 = SVOp->getOperand(1);
6140   DebugLoc dl = SVOp->getDebugLoc();
6141   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6142
6143   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6144   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6145   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6146
6147   // VPSHUFB may be generated if
6148   // (1) one of input vector is undefined or zeroinitializer.
6149   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6150   // And (2) the mask indexes don't cross the 128-bit lane.
6151   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6152       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6153     return SDValue();
6154
6155   if (V1IsAllZero && !V2IsAllZero) {
6156     CommuteVectorShuffleMask(MaskVals, 32);
6157     V1 = V2;
6158   }
6159   SmallVector<SDValue, 32> pshufbMask;
6160   for (unsigned i = 0; i != 32; i++) {
6161     int EltIdx = MaskVals[i];
6162     if (EltIdx < 0 || EltIdx >= 32)
6163       EltIdx = 0x80;
6164     else {
6165       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6166         // Cross lane is not allowed.
6167         return SDValue();
6168       EltIdx &= 0xf;
6169     }
6170     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6171   }
6172   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6173                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6174                                   MVT::v32i8, &pshufbMask[0], 32));
6175 }
6176
6177 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6178 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6179 /// done when every pair / quad of shuffle mask elements point to elements in
6180 /// the right sequence. e.g.
6181 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6182 static
6183 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6184                                  SelectionDAG &DAG) {
6185   MVT VT = SVOp->getValueType(0).getSimpleVT();
6186   DebugLoc dl = SVOp->getDebugLoc();
6187   unsigned NumElems = VT.getVectorNumElements();
6188   MVT NewVT;
6189   unsigned Scale;
6190   switch (VT.SimpleTy) {
6191   default: llvm_unreachable("Unexpected!");
6192   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6193   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6194   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6195   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6196   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6197   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6198   }
6199
6200   SmallVector<int, 8> MaskVec;
6201   for (unsigned i = 0; i != NumElems; i += Scale) {
6202     int StartIdx = -1;
6203     for (unsigned j = 0; j != Scale; ++j) {
6204       int EltIdx = SVOp->getMaskElt(i+j);
6205       if (EltIdx < 0)
6206         continue;
6207       if (StartIdx < 0)
6208         StartIdx = (EltIdx / Scale);
6209       if (EltIdx != (int)(StartIdx*Scale + j))
6210         return SDValue();
6211     }
6212     MaskVec.push_back(StartIdx);
6213   }
6214
6215   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6216   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6217   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6218 }
6219
6220 /// getVZextMovL - Return a zero-extending vector move low node.
6221 ///
6222 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6223                             SDValue SrcOp, SelectionDAG &DAG,
6224                             const X86Subtarget *Subtarget, DebugLoc dl) {
6225   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6226     LoadSDNode *LD = NULL;
6227     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6228       LD = dyn_cast<LoadSDNode>(SrcOp);
6229     if (!LD) {
6230       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6231       // instead.
6232       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6233       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6234           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6235           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6236           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6237         // PR2108
6238         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6239         return DAG.getNode(ISD::BITCAST, dl, VT,
6240                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6241                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6242                                                    OpVT,
6243                                                    SrcOp.getOperand(0)
6244                                                           .getOperand(0))));
6245       }
6246     }
6247   }
6248
6249   return DAG.getNode(ISD::BITCAST, dl, VT,
6250                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6251                                  DAG.getNode(ISD::BITCAST, dl,
6252                                              OpVT, SrcOp)));
6253 }
6254
6255 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6256 /// which could not be matched by any known target speficic shuffle
6257 static SDValue
6258 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6259
6260   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6261   if (NewOp.getNode())
6262     return NewOp;
6263
6264   MVT VT = SVOp->getValueType(0).getSimpleVT();
6265
6266   unsigned NumElems = VT.getVectorNumElements();
6267   unsigned NumLaneElems = NumElems / 2;
6268
6269   DebugLoc dl = SVOp->getDebugLoc();
6270   MVT EltVT = VT.getVectorElementType();
6271   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6272   SDValue Output[2];
6273
6274   SmallVector<int, 16> Mask;
6275   for (unsigned l = 0; l < 2; ++l) {
6276     // Build a shuffle mask for the output, discovering on the fly which
6277     // input vectors to use as shuffle operands (recorded in InputUsed).
6278     // If building a suitable shuffle vector proves too hard, then bail
6279     // out with UseBuildVector set.
6280     bool UseBuildVector = false;
6281     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6282     unsigned LaneStart = l * NumLaneElems;
6283     for (unsigned i = 0; i != NumLaneElems; ++i) {
6284       // The mask element.  This indexes into the input.
6285       int Idx = SVOp->getMaskElt(i+LaneStart);
6286       if (Idx < 0) {
6287         // the mask element does not index into any input vector.
6288         Mask.push_back(-1);
6289         continue;
6290       }
6291
6292       // The input vector this mask element indexes into.
6293       int Input = Idx / NumLaneElems;
6294
6295       // Turn the index into an offset from the start of the input vector.
6296       Idx -= Input * NumLaneElems;
6297
6298       // Find or create a shuffle vector operand to hold this input.
6299       unsigned OpNo;
6300       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6301         if (InputUsed[OpNo] == Input)
6302           // This input vector is already an operand.
6303           break;
6304         if (InputUsed[OpNo] < 0) {
6305           // Create a new operand for this input vector.
6306           InputUsed[OpNo] = Input;
6307           break;
6308         }
6309       }
6310
6311       if (OpNo >= array_lengthof(InputUsed)) {
6312         // More than two input vectors used!  Give up on trying to create a
6313         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6314         UseBuildVector = true;
6315         break;
6316       }
6317
6318       // Add the mask index for the new shuffle vector.
6319       Mask.push_back(Idx + OpNo * NumLaneElems);
6320     }
6321
6322     if (UseBuildVector) {
6323       SmallVector<SDValue, 16> SVOps;
6324       for (unsigned i = 0; i != NumLaneElems; ++i) {
6325         // The mask element.  This indexes into the input.
6326         int Idx = SVOp->getMaskElt(i+LaneStart);
6327         if (Idx < 0) {
6328           SVOps.push_back(DAG.getUNDEF(EltVT));
6329           continue;
6330         }
6331
6332         // The input vector this mask element indexes into.
6333         int Input = Idx / NumElems;
6334
6335         // Turn the index into an offset from the start of the input vector.
6336         Idx -= Input * NumElems;
6337
6338         // Extract the vector element by hand.
6339         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6340                                     SVOp->getOperand(Input),
6341                                     DAG.getIntPtrConstant(Idx)));
6342       }
6343
6344       // Construct the output using a BUILD_VECTOR.
6345       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6346                               SVOps.size());
6347     } else if (InputUsed[0] < 0) {
6348       // No input vectors were used! The result is undefined.
6349       Output[l] = DAG.getUNDEF(NVT);
6350     } else {
6351       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6352                                         (InputUsed[0] % 2) * NumLaneElems,
6353                                         DAG, dl);
6354       // If only one input was used, use an undefined vector for the other.
6355       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6356         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6357                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6358       // At least one input vector was used. Create a new shuffle vector.
6359       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6360     }
6361
6362     Mask.clear();
6363   }
6364
6365   // Concatenate the result back
6366   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6367 }
6368
6369 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6370 /// 4 elements, and match them with several different shuffle types.
6371 static SDValue
6372 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6373   SDValue V1 = SVOp->getOperand(0);
6374   SDValue V2 = SVOp->getOperand(1);
6375   DebugLoc dl = SVOp->getDebugLoc();
6376   MVT VT = SVOp->getValueType(0).getSimpleVT();
6377
6378   assert(VT.is128BitVector() && "Unsupported vector size");
6379
6380   std::pair<int, int> Locs[4];
6381   int Mask1[] = { -1, -1, -1, -1 };
6382   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6383
6384   unsigned NumHi = 0;
6385   unsigned NumLo = 0;
6386   for (unsigned i = 0; i != 4; ++i) {
6387     int Idx = PermMask[i];
6388     if (Idx < 0) {
6389       Locs[i] = std::make_pair(-1, -1);
6390     } else {
6391       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6392       if (Idx < 4) {
6393         Locs[i] = std::make_pair(0, NumLo);
6394         Mask1[NumLo] = Idx;
6395         NumLo++;
6396       } else {
6397         Locs[i] = std::make_pair(1, NumHi);
6398         if (2+NumHi < 4)
6399           Mask1[2+NumHi] = Idx;
6400         NumHi++;
6401       }
6402     }
6403   }
6404
6405   if (NumLo <= 2 && NumHi <= 2) {
6406     // If no more than two elements come from either vector. This can be
6407     // implemented with two shuffles. First shuffle gather the elements.
6408     // The second shuffle, which takes the first shuffle as both of its
6409     // vector operands, put the elements into the right order.
6410     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6411
6412     int Mask2[] = { -1, -1, -1, -1 };
6413
6414     for (unsigned i = 0; i != 4; ++i)
6415       if (Locs[i].first != -1) {
6416         unsigned Idx = (i < 2) ? 0 : 4;
6417         Idx += Locs[i].first * 2 + Locs[i].second;
6418         Mask2[i] = Idx;
6419       }
6420
6421     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6422   }
6423
6424   if (NumLo == 3 || NumHi == 3) {
6425     // Otherwise, we must have three elements from one vector, call it X, and
6426     // one element from the other, call it Y.  First, use a shufps to build an
6427     // intermediate vector with the one element from Y and the element from X
6428     // that will be in the same half in the final destination (the indexes don't
6429     // matter). Then, use a shufps to build the final vector, taking the half
6430     // containing the element from Y from the intermediate, and the other half
6431     // from X.
6432     if (NumHi == 3) {
6433       // Normalize it so the 3 elements come from V1.
6434       CommuteVectorShuffleMask(PermMask, 4);
6435       std::swap(V1, V2);
6436     }
6437
6438     // Find the element from V2.
6439     unsigned HiIndex;
6440     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6441       int Val = PermMask[HiIndex];
6442       if (Val < 0)
6443         continue;
6444       if (Val >= 4)
6445         break;
6446     }
6447
6448     Mask1[0] = PermMask[HiIndex];
6449     Mask1[1] = -1;
6450     Mask1[2] = PermMask[HiIndex^1];
6451     Mask1[3] = -1;
6452     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6453
6454     if (HiIndex >= 2) {
6455       Mask1[0] = PermMask[0];
6456       Mask1[1] = PermMask[1];
6457       Mask1[2] = HiIndex & 1 ? 6 : 4;
6458       Mask1[3] = HiIndex & 1 ? 4 : 6;
6459       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6460     }
6461
6462     Mask1[0] = HiIndex & 1 ? 2 : 0;
6463     Mask1[1] = HiIndex & 1 ? 0 : 2;
6464     Mask1[2] = PermMask[2];
6465     Mask1[3] = PermMask[3];
6466     if (Mask1[2] >= 0)
6467       Mask1[2] += 4;
6468     if (Mask1[3] >= 0)
6469       Mask1[3] += 4;
6470     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6471   }
6472
6473   // Break it into (shuffle shuffle_hi, shuffle_lo).
6474   int LoMask[] = { -1, -1, -1, -1 };
6475   int HiMask[] = { -1, -1, -1, -1 };
6476
6477   int *MaskPtr = LoMask;
6478   unsigned MaskIdx = 0;
6479   unsigned LoIdx = 0;
6480   unsigned HiIdx = 2;
6481   for (unsigned i = 0; i != 4; ++i) {
6482     if (i == 2) {
6483       MaskPtr = HiMask;
6484       MaskIdx = 1;
6485       LoIdx = 0;
6486       HiIdx = 2;
6487     }
6488     int Idx = PermMask[i];
6489     if (Idx < 0) {
6490       Locs[i] = std::make_pair(-1, -1);
6491     } else if (Idx < 4) {
6492       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6493       MaskPtr[LoIdx] = Idx;
6494       LoIdx++;
6495     } else {
6496       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6497       MaskPtr[HiIdx] = Idx;
6498       HiIdx++;
6499     }
6500   }
6501
6502   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6503   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6504   int MaskOps[] = { -1, -1, -1, -1 };
6505   for (unsigned i = 0; i != 4; ++i)
6506     if (Locs[i].first != -1)
6507       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6508   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6509 }
6510
6511 static bool MayFoldVectorLoad(SDValue V) {
6512   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6513     V = V.getOperand(0);
6514
6515   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6516     V = V.getOperand(0);
6517   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6518       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6519     // BUILD_VECTOR (load), undef
6520     V = V.getOperand(0);
6521
6522   return MayFoldLoad(V);
6523 }
6524
6525 static
6526 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6527   EVT VT = Op.getValueType();
6528
6529   // Canonizalize to v2f64.
6530   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6531   return DAG.getNode(ISD::BITCAST, dl, VT,
6532                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6533                                           V1, DAG));
6534 }
6535
6536 static
6537 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6538                         bool HasSSE2) {
6539   SDValue V1 = Op.getOperand(0);
6540   SDValue V2 = Op.getOperand(1);
6541   EVT VT = Op.getValueType();
6542
6543   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6544
6545   if (HasSSE2 && VT == MVT::v2f64)
6546     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6547
6548   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6549   return DAG.getNode(ISD::BITCAST, dl, VT,
6550                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6551                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6552                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6553 }
6554
6555 static
6556 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6557   SDValue V1 = Op.getOperand(0);
6558   SDValue V2 = Op.getOperand(1);
6559   EVT VT = Op.getValueType();
6560
6561   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6562          "unsupported shuffle type");
6563
6564   if (V2.getOpcode() == ISD::UNDEF)
6565     V2 = V1;
6566
6567   // v4i32 or v4f32
6568   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6569 }
6570
6571 static
6572 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6573   SDValue V1 = Op.getOperand(0);
6574   SDValue V2 = Op.getOperand(1);
6575   EVT VT = Op.getValueType();
6576   unsigned NumElems = VT.getVectorNumElements();
6577
6578   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6579   // operand of these instructions is only memory, so check if there's a
6580   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6581   // same masks.
6582   bool CanFoldLoad = false;
6583
6584   // Trivial case, when V2 comes from a load.
6585   if (MayFoldVectorLoad(V2))
6586     CanFoldLoad = true;
6587
6588   // When V1 is a load, it can be folded later into a store in isel, example:
6589   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6590   //    turns into:
6591   //  (MOVLPSmr addr:$src1, VR128:$src2)
6592   // So, recognize this potential and also use MOVLPS or MOVLPD
6593   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6594     CanFoldLoad = true;
6595
6596   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6597   if (CanFoldLoad) {
6598     if (HasSSE2 && NumElems == 2)
6599       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6600
6601     if (NumElems == 4)
6602       // If we don't care about the second element, proceed to use movss.
6603       if (SVOp->getMaskElt(1) != -1)
6604         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6605   }
6606
6607   // movl and movlp will both match v2i64, but v2i64 is never matched by
6608   // movl earlier because we make it strict to avoid messing with the movlp load
6609   // folding logic (see the code above getMOVLP call). Match it here then,
6610   // this is horrible, but will stay like this until we move all shuffle
6611   // matching to x86 specific nodes. Note that for the 1st condition all
6612   // types are matched with movsd.
6613   if (HasSSE2) {
6614     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6615     // as to remove this logic from here, as much as possible
6616     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6617       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6618     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6619   }
6620
6621   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6622
6623   // Invert the operand order and use SHUFPS to match it.
6624   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6625                               getShuffleSHUFImmediate(SVOp), DAG);
6626 }
6627
6628 // Reduce a vector shuffle to zext.
6629 SDValue
6630 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6631   // PMOVZX is only available from SSE41.
6632   if (!Subtarget->hasSSE41())
6633     return SDValue();
6634
6635   EVT VT = Op.getValueType();
6636
6637   // Only AVX2 support 256-bit vector integer extending.
6638   if (!Subtarget->hasInt256() && VT.is256BitVector())
6639     return SDValue();
6640
6641   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6642   DebugLoc DL = Op.getDebugLoc();
6643   SDValue V1 = Op.getOperand(0);
6644   SDValue V2 = Op.getOperand(1);
6645   unsigned NumElems = VT.getVectorNumElements();
6646
6647   // Extending is an unary operation and the element type of the source vector
6648   // won't be equal to or larger than i64.
6649   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6650       VT.getVectorElementType() == MVT::i64)
6651     return SDValue();
6652
6653   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6654   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6655   while ((1U << Shift) < NumElems) {
6656     if (SVOp->getMaskElt(1U << Shift) == 1)
6657       break;
6658     Shift += 1;
6659     // The maximal ratio is 8, i.e. from i8 to i64.
6660     if (Shift > 3)
6661       return SDValue();
6662   }
6663
6664   // Check the shuffle mask.
6665   unsigned Mask = (1U << Shift) - 1;
6666   for (unsigned i = 0; i != NumElems; ++i) {
6667     int EltIdx = SVOp->getMaskElt(i);
6668     if ((i & Mask) != 0 && EltIdx != -1)
6669       return SDValue();
6670     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6671       return SDValue();
6672   }
6673
6674   LLVMContext *Context = DAG.getContext();
6675   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6676   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6677   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6678
6679   if (!isTypeLegal(NVT))
6680     return SDValue();
6681
6682   // Simplify the operand as it's prepared to be fed into shuffle.
6683   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6684   if (V1.getOpcode() == ISD::BITCAST &&
6685       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6686       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6687       V1.getOperand(0)
6688         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6689     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6690     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6691     ConstantSDNode *CIdx =
6692       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6693     // If it's foldable, i.e. normal load with single use, we will let code
6694     // selection to fold it. Otherwise, we will short the conversion sequence.
6695     if (CIdx && CIdx->getZExtValue() == 0 &&
6696         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6697       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6698         // The "ext_vec_elt" node is wider than the result node.
6699         // In this case we should extract subvector from V.
6700         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6701         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6702         EVT FullVT = V.getValueType();
6703         EVT SubVecVT = EVT::getVectorVT(*Context, 
6704                                         FullVT.getVectorElementType(),
6705                                         FullVT.getVectorNumElements()/Ratio);
6706         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V, 
6707                         DAG.getIntPtrConstant(0));
6708       }
6709       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6710     }
6711   }
6712
6713   return DAG.getNode(ISD::BITCAST, DL, VT,
6714                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6715 }
6716
6717 SDValue
6718 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6719   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6720   MVT VT = Op.getValueType().getSimpleVT();
6721   DebugLoc dl = Op.getDebugLoc();
6722   SDValue V1 = Op.getOperand(0);
6723   SDValue V2 = Op.getOperand(1);
6724
6725   if (isZeroShuffle(SVOp))
6726     return getZeroVector(VT, Subtarget, DAG, dl);
6727
6728   // Handle splat operations
6729   if (SVOp->isSplat()) {
6730     // Use vbroadcast whenever the splat comes from a foldable load
6731     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6732     if (Broadcast.getNode())
6733       return Broadcast;
6734   }
6735
6736   // Check integer expanding shuffles.
6737   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6738   if (NewOp.getNode())
6739     return NewOp;
6740
6741   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6742   // do it!
6743   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6744       VT == MVT::v16i16 || VT == MVT::v32i8) {
6745     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6746     if (NewOp.getNode())
6747       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6748   } else if ((VT == MVT::v4i32 ||
6749              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6750     // FIXME: Figure out a cleaner way to do this.
6751     // Try to make use of movq to zero out the top part.
6752     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6753       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6754       if (NewOp.getNode()) {
6755         MVT NewVT = NewOp.getValueType().getSimpleVT();
6756         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6757                                NewVT, true, false))
6758           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6759                               DAG, Subtarget, dl);
6760       }
6761     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6762       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6763       if (NewOp.getNode()) {
6764         MVT NewVT = NewOp.getValueType().getSimpleVT();
6765         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6766           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6767                               DAG, Subtarget, dl);
6768       }
6769     }
6770   }
6771   return SDValue();
6772 }
6773
6774 SDValue
6775 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6776   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6777   SDValue V1 = Op.getOperand(0);
6778   SDValue V2 = Op.getOperand(1);
6779   MVT VT = Op.getValueType().getSimpleVT();
6780   DebugLoc dl = Op.getDebugLoc();
6781   unsigned NumElems = VT.getVectorNumElements();
6782   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6783   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6784   bool V1IsSplat = false;
6785   bool V2IsSplat = false;
6786   bool HasSSE2 = Subtarget->hasSSE2();
6787   bool HasFp256    = Subtarget->hasFp256();
6788   bool HasInt256   = Subtarget->hasInt256();
6789   MachineFunction &MF = DAG.getMachineFunction();
6790   bool OptForSize = MF.getFunction()->getAttributes().
6791     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6792
6793   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6794
6795   if (V1IsUndef && V2IsUndef)
6796     return DAG.getUNDEF(VT);
6797
6798   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6799
6800   // Vector shuffle lowering takes 3 steps:
6801   //
6802   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6803   //    narrowing and commutation of operands should be handled.
6804   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6805   //    shuffle nodes.
6806   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6807   //    so the shuffle can be broken into other shuffles and the legalizer can
6808   //    try the lowering again.
6809   //
6810   // The general idea is that no vector_shuffle operation should be left to
6811   // be matched during isel, all of them must be converted to a target specific
6812   // node here.
6813
6814   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6815   // narrowing and commutation of operands should be handled. The actual code
6816   // doesn't include all of those, work in progress...
6817   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6818   if (NewOp.getNode())
6819     return NewOp;
6820
6821   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6822
6823   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6824   // unpckh_undef). Only use pshufd if speed is more important than size.
6825   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6826     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6827   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6828     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6829
6830   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6831       V2IsUndef && MayFoldVectorLoad(V1))
6832     return getMOVDDup(Op, dl, V1, DAG);
6833
6834   if (isMOVHLPS_v_undef_Mask(M, VT))
6835     return getMOVHighToLow(Op, dl, DAG);
6836
6837   // Use to match splats
6838   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6839       (VT == MVT::v2f64 || VT == MVT::v2i64))
6840     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6841
6842   if (isPSHUFDMask(M, VT)) {
6843     // The actual implementation will match the mask in the if above and then
6844     // during isel it can match several different instructions, not only pshufd
6845     // as its name says, sad but true, emulate the behavior for now...
6846     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6847       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6848
6849     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6850
6851     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6852       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6853
6854     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6855       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6856                                   DAG);
6857
6858     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6859                                 TargetMask, DAG);
6860   }
6861
6862   // Check if this can be converted into a logical shift.
6863   bool isLeft = false;
6864   unsigned ShAmt = 0;
6865   SDValue ShVal;
6866   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6867   if (isShift && ShVal.hasOneUse()) {
6868     // If the shifted value has multiple uses, it may be cheaper to use
6869     // v_set0 + movlhps or movhlps, etc.
6870     MVT EltVT = VT.getVectorElementType();
6871     ShAmt *= EltVT.getSizeInBits();
6872     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6873   }
6874
6875   if (isMOVLMask(M, VT)) {
6876     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6877       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6878     if (!isMOVLPMask(M, VT)) {
6879       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6880         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6881
6882       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6883         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6884     }
6885   }
6886
6887   // FIXME: fold these into legal mask.
6888   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6889     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6890
6891   if (isMOVHLPSMask(M, VT))
6892     return getMOVHighToLow(Op, dl, DAG);
6893
6894   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6895     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6896
6897   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6898     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6899
6900   if (isMOVLPMask(M, VT))
6901     return getMOVLP(Op, dl, DAG, HasSSE2);
6902
6903   if (ShouldXformToMOVHLPS(M, VT) ||
6904       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6905     return CommuteVectorShuffle(SVOp, DAG);
6906
6907   if (isShift) {
6908     // No better options. Use a vshldq / vsrldq.
6909     MVT EltVT = VT.getVectorElementType();
6910     ShAmt *= EltVT.getSizeInBits();
6911     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6912   }
6913
6914   bool Commuted = false;
6915   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6916   // 1,1,1,1 -> v8i16 though.
6917   V1IsSplat = isSplatVector(V1.getNode());
6918   V2IsSplat = isSplatVector(V2.getNode());
6919
6920   // Canonicalize the splat or undef, if present, to be on the RHS.
6921   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6922     CommuteVectorShuffleMask(M, NumElems);
6923     std::swap(V1, V2);
6924     std::swap(V1IsSplat, V2IsSplat);
6925     Commuted = true;
6926   }
6927
6928   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6929     // Shuffling low element of v1 into undef, just return v1.
6930     if (V2IsUndef)
6931       return V1;
6932     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6933     // the instruction selector will not match, so get a canonical MOVL with
6934     // swapped operands to undo the commute.
6935     return getMOVL(DAG, dl, VT, V2, V1);
6936   }
6937
6938   if (isUNPCKLMask(M, VT, HasInt256))
6939     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6940
6941   if (isUNPCKHMask(M, VT, HasInt256))
6942     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6943
6944   if (V2IsSplat) {
6945     // Normalize mask so all entries that point to V2 points to its first
6946     // element then try to match unpck{h|l} again. If match, return a
6947     // new vector_shuffle with the corrected mask.p
6948     SmallVector<int, 8> NewMask(M.begin(), M.end());
6949     NormalizeMask(NewMask, NumElems);
6950     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6951       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6952     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6953       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6954   }
6955
6956   if (Commuted) {
6957     // Commute is back and try unpck* again.
6958     // FIXME: this seems wrong.
6959     CommuteVectorShuffleMask(M, NumElems);
6960     std::swap(V1, V2);
6961     std::swap(V1IsSplat, V2IsSplat);
6962     Commuted = false;
6963
6964     if (isUNPCKLMask(M, VT, HasInt256))
6965       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6966
6967     if (isUNPCKHMask(M, VT, HasInt256))
6968       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6969   }
6970
6971   // Normalize the node to match x86 shuffle ops if needed
6972   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6973     return CommuteVectorShuffle(SVOp, DAG);
6974
6975   // The checks below are all present in isShuffleMaskLegal, but they are
6976   // inlined here right now to enable us to directly emit target specific
6977   // nodes, and remove one by one until they don't return Op anymore.
6978
6979   if (isPALIGNRMask(M, VT, Subtarget))
6980     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6981                                 getShufflePALIGNRImmediate(SVOp),
6982                                 DAG);
6983
6984   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6985       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6986     if (VT == MVT::v2f64 || VT == MVT::v2i64)
6987       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6988   }
6989
6990   if (isPSHUFHWMask(M, VT, HasInt256))
6991     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6992                                 getShufflePSHUFHWImmediate(SVOp),
6993                                 DAG);
6994
6995   if (isPSHUFLWMask(M, VT, HasInt256))
6996     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6997                                 getShufflePSHUFLWImmediate(SVOp),
6998                                 DAG);
6999
7000   if (isSHUFPMask(M, VT, HasFp256))
7001     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7002                                 getShuffleSHUFImmediate(SVOp), DAG);
7003
7004   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7005     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7006   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7007     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7008
7009   //===--------------------------------------------------------------------===//
7010   // Generate target specific nodes for 128 or 256-bit shuffles only
7011   // supported in the AVX instruction set.
7012   //
7013
7014   // Handle VMOVDDUPY permutations
7015   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7016     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7017
7018   // Handle VPERMILPS/D* permutations
7019   if (isVPERMILPMask(M, VT, HasFp256)) {
7020     if (HasInt256 && VT == MVT::v8i32)
7021       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7022                                   getShuffleSHUFImmediate(SVOp), DAG);
7023     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7024                                 getShuffleSHUFImmediate(SVOp), DAG);
7025   }
7026
7027   // Handle VPERM2F128/VPERM2I128 permutations
7028   if (isVPERM2X128Mask(M, VT, HasFp256))
7029     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7030                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7031
7032   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7033   if (BlendOp.getNode())
7034     return BlendOp;
7035
7036   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7037     SmallVector<SDValue, 8> permclMask;
7038     for (unsigned i = 0; i != 8; ++i) {
7039       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7040     }
7041     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7042                                &permclMask[0], 8);
7043     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7044     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7045                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7046   }
7047
7048   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7049     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7050                                 getShuffleCLImmediate(SVOp), DAG);
7051
7052   //===--------------------------------------------------------------------===//
7053   // Since no target specific shuffle was selected for this generic one,
7054   // lower it into other known shuffles. FIXME: this isn't true yet, but
7055   // this is the plan.
7056   //
7057
7058   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7059   if (VT == MVT::v8i16) {
7060     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7061     if (NewOp.getNode())
7062       return NewOp;
7063   }
7064
7065   if (VT == MVT::v16i8) {
7066     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7067     if (NewOp.getNode())
7068       return NewOp;
7069   }
7070
7071   if (VT == MVT::v32i8) {
7072     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7073     if (NewOp.getNode())
7074       return NewOp;
7075   }
7076
7077   // Handle all 128-bit wide vectors with 4 elements, and match them with
7078   // several different shuffle types.
7079   if (NumElems == 4 && VT.is128BitVector())
7080     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7081
7082   // Handle general 256-bit shuffles
7083   if (VT.is256BitVector())
7084     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7085
7086   return SDValue();
7087 }
7088
7089 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7090   MVT VT = Op.getValueType().getSimpleVT();
7091   DebugLoc dl = Op.getDebugLoc();
7092
7093   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7094     return SDValue();
7095
7096   if (VT.getSizeInBits() == 8) {
7097     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7098                                   Op.getOperand(0), Op.getOperand(1));
7099     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7100                                   DAG.getValueType(VT));
7101     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7102   }
7103
7104   if (VT.getSizeInBits() == 16) {
7105     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7106     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7107     if (Idx == 0)
7108       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7109                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7110                                      DAG.getNode(ISD::BITCAST, dl,
7111                                                  MVT::v4i32,
7112                                                  Op.getOperand(0)),
7113                                      Op.getOperand(1)));
7114     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7115                                   Op.getOperand(0), Op.getOperand(1));
7116     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7117                                   DAG.getValueType(VT));
7118     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7119   }
7120
7121   if (VT == MVT::f32) {
7122     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7123     // the result back to FR32 register. It's only worth matching if the
7124     // result has a single use which is a store or a bitcast to i32.  And in
7125     // the case of a store, it's not worth it if the index is a constant 0,
7126     // because a MOVSSmr can be used instead, which is smaller and faster.
7127     if (!Op.hasOneUse())
7128       return SDValue();
7129     SDNode *User = *Op.getNode()->use_begin();
7130     if ((User->getOpcode() != ISD::STORE ||
7131          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7132           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7133         (User->getOpcode() != ISD::BITCAST ||
7134          User->getValueType(0) != MVT::i32))
7135       return SDValue();
7136     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7137                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7138                                               Op.getOperand(0)),
7139                                               Op.getOperand(1));
7140     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7141   }
7142
7143   if (VT == MVT::i32 || VT == MVT::i64) {
7144     // ExtractPS/pextrq works with constant index.
7145     if (isa<ConstantSDNode>(Op.getOperand(1)))
7146       return Op;
7147   }
7148   return SDValue();
7149 }
7150
7151 SDValue
7152 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7153                                            SelectionDAG &DAG) const {
7154   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7155     return SDValue();
7156
7157   SDValue Vec = Op.getOperand(0);
7158   MVT VecVT = Vec.getValueType().getSimpleVT();
7159
7160   // If this is a 256-bit vector result, first extract the 128-bit vector and
7161   // then extract the element from the 128-bit vector.
7162   if (VecVT.is256BitVector()) {
7163     DebugLoc dl = Op.getNode()->getDebugLoc();
7164     unsigned NumElems = VecVT.getVectorNumElements();
7165     SDValue Idx = Op.getOperand(1);
7166     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7167
7168     // Get the 128-bit vector.
7169     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7170
7171     if (IdxVal >= NumElems/2)
7172       IdxVal -= NumElems/2;
7173     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7174                        DAG.getConstant(IdxVal, MVT::i32));
7175   }
7176
7177   assert(VecVT.is128BitVector() && "Unexpected vector length");
7178
7179   if (Subtarget->hasSSE41()) {
7180     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7181     if (Res.getNode())
7182       return Res;
7183   }
7184
7185   MVT VT = Op.getValueType().getSimpleVT();
7186   DebugLoc dl = Op.getDebugLoc();
7187   // TODO: handle v16i8.
7188   if (VT.getSizeInBits() == 16) {
7189     SDValue Vec = Op.getOperand(0);
7190     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7191     if (Idx == 0)
7192       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7193                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7194                                      DAG.getNode(ISD::BITCAST, dl,
7195                                                  MVT::v4i32, Vec),
7196                                      Op.getOperand(1)));
7197     // Transform it so it match pextrw which produces a 32-bit result.
7198     MVT EltVT = MVT::i32;
7199     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7200                                   Op.getOperand(0), Op.getOperand(1));
7201     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7202                                   DAG.getValueType(VT));
7203     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7204   }
7205
7206   if (VT.getSizeInBits() == 32) {
7207     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7208     if (Idx == 0)
7209       return Op;
7210
7211     // SHUFPS the element to the lowest double word, then movss.
7212     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7213     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7214     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7215                                        DAG.getUNDEF(VVT), Mask);
7216     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7217                        DAG.getIntPtrConstant(0));
7218   }
7219
7220   if (VT.getSizeInBits() == 64) {
7221     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7222     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7223     //        to match extract_elt for f64.
7224     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7225     if (Idx == 0)
7226       return Op;
7227
7228     // UNPCKHPD the element to the lowest double word, then movsd.
7229     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7230     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7231     int Mask[2] = { 1, -1 };
7232     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7233     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7234                                        DAG.getUNDEF(VVT), Mask);
7235     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7236                        DAG.getIntPtrConstant(0));
7237   }
7238
7239   return SDValue();
7240 }
7241
7242 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7243   MVT VT = Op.getValueType().getSimpleVT();
7244   MVT EltVT = VT.getVectorElementType();
7245   DebugLoc dl = Op.getDebugLoc();
7246
7247   SDValue N0 = Op.getOperand(0);
7248   SDValue N1 = Op.getOperand(1);
7249   SDValue N2 = Op.getOperand(2);
7250
7251   if (!VT.is128BitVector())
7252     return SDValue();
7253
7254   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7255       isa<ConstantSDNode>(N2)) {
7256     unsigned Opc;
7257     if (VT == MVT::v8i16)
7258       Opc = X86ISD::PINSRW;
7259     else if (VT == MVT::v16i8)
7260       Opc = X86ISD::PINSRB;
7261     else
7262       Opc = X86ISD::PINSRB;
7263
7264     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7265     // argument.
7266     if (N1.getValueType() != MVT::i32)
7267       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7268     if (N2.getValueType() != MVT::i32)
7269       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7270     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7271   }
7272
7273   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7274     // Bits [7:6] of the constant are the source select.  This will always be
7275     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7276     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7277     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7278     // Bits [5:4] of the constant are the destination select.  This is the
7279     //  value of the incoming immediate.
7280     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7281     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7282     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7283     // Create this as a scalar to vector..
7284     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7285     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7286   }
7287
7288   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7289     // PINSR* works with constant index.
7290     return Op;
7291   }
7292   return SDValue();
7293 }
7294
7295 SDValue
7296 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7297   MVT VT = Op.getValueType().getSimpleVT();
7298   MVT EltVT = VT.getVectorElementType();
7299
7300   DebugLoc dl = Op.getDebugLoc();
7301   SDValue N0 = Op.getOperand(0);
7302   SDValue N1 = Op.getOperand(1);
7303   SDValue N2 = Op.getOperand(2);
7304
7305   // If this is a 256-bit vector result, first extract the 128-bit vector,
7306   // insert the element into the extracted half and then place it back.
7307   if (VT.is256BitVector()) {
7308     if (!isa<ConstantSDNode>(N2))
7309       return SDValue();
7310
7311     // Get the desired 128-bit vector half.
7312     unsigned NumElems = VT.getVectorNumElements();
7313     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7314     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7315
7316     // Insert the element into the desired half.
7317     bool Upper = IdxVal >= NumElems/2;
7318     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7319                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7320
7321     // Insert the changed part back to the 256-bit vector
7322     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7323   }
7324
7325   if (Subtarget->hasSSE41())
7326     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7327
7328   if (EltVT == MVT::i8)
7329     return SDValue();
7330
7331   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7332     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7333     // as its second argument.
7334     if (N1.getValueType() != MVT::i32)
7335       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7336     if (N2.getValueType() != MVT::i32)
7337       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7338     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7339   }
7340   return SDValue();
7341 }
7342
7343 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7344   LLVMContext *Context = DAG.getContext();
7345   DebugLoc dl = Op.getDebugLoc();
7346   MVT OpVT = Op.getValueType().getSimpleVT();
7347
7348   // If this is a 256-bit vector result, first insert into a 128-bit
7349   // vector and then insert into the 256-bit vector.
7350   if (!OpVT.is128BitVector()) {
7351     // Insert into a 128-bit vector.
7352     EVT VT128 = EVT::getVectorVT(*Context,
7353                                  OpVT.getVectorElementType(),
7354                                  OpVT.getVectorNumElements() / 2);
7355
7356     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7357
7358     // Insert the 128-bit vector.
7359     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7360   }
7361
7362   if (OpVT == MVT::v1i64 &&
7363       Op.getOperand(0).getValueType() == MVT::i64)
7364     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7365
7366   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7367   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7368   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7369                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7370 }
7371
7372 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7373 // a simple subregister reference or explicit instructions to grab
7374 // upper bits of a vector.
7375 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7376                                       SelectionDAG &DAG) {
7377   if (Subtarget->hasFp256()) {
7378     DebugLoc dl = Op.getNode()->getDebugLoc();
7379     SDValue Vec = Op.getNode()->getOperand(0);
7380     SDValue Idx = Op.getNode()->getOperand(1);
7381
7382     if (Op.getNode()->getValueType(0).is128BitVector() &&
7383         Vec.getNode()->getValueType(0).is256BitVector() &&
7384         isa<ConstantSDNode>(Idx)) {
7385       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7386       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7387     }
7388   }
7389   return SDValue();
7390 }
7391
7392 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7393 // simple superregister reference or explicit instructions to insert
7394 // the upper bits of a vector.
7395 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7396                                      SelectionDAG &DAG) {
7397   if (Subtarget->hasFp256()) {
7398     DebugLoc dl = Op.getNode()->getDebugLoc();
7399     SDValue Vec = Op.getNode()->getOperand(0);
7400     SDValue SubVec = Op.getNode()->getOperand(1);
7401     SDValue Idx = Op.getNode()->getOperand(2);
7402
7403     if (Op.getNode()->getValueType(0).is256BitVector() &&
7404         SubVec.getNode()->getValueType(0).is128BitVector() &&
7405         isa<ConstantSDNode>(Idx)) {
7406       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7407       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7408     }
7409   }
7410   return SDValue();
7411 }
7412
7413 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7414 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7415 // one of the above mentioned nodes. It has to be wrapped because otherwise
7416 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7417 // be used to form addressing mode. These wrapped nodes will be selected
7418 // into MOV32ri.
7419 SDValue
7420 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7421   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7422
7423   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7424   // global base reg.
7425   unsigned char OpFlag = 0;
7426   unsigned WrapperKind = X86ISD::Wrapper;
7427   CodeModel::Model M = getTargetMachine().getCodeModel();
7428
7429   if (Subtarget->isPICStyleRIPRel() &&
7430       (M == CodeModel::Small || M == CodeModel::Kernel))
7431     WrapperKind = X86ISD::WrapperRIP;
7432   else if (Subtarget->isPICStyleGOT())
7433     OpFlag = X86II::MO_GOTOFF;
7434   else if (Subtarget->isPICStyleStubPIC())
7435     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7436
7437   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7438                                              CP->getAlignment(),
7439                                              CP->getOffset(), OpFlag);
7440   DebugLoc DL = CP->getDebugLoc();
7441   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7442   // With PIC, the address is actually $g + Offset.
7443   if (OpFlag) {
7444     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7445                          DAG.getNode(X86ISD::GlobalBaseReg,
7446                                      DebugLoc(), getPointerTy()),
7447                          Result);
7448   }
7449
7450   return Result;
7451 }
7452
7453 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7454   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7455
7456   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7457   // global base reg.
7458   unsigned char OpFlag = 0;
7459   unsigned WrapperKind = X86ISD::Wrapper;
7460   CodeModel::Model M = getTargetMachine().getCodeModel();
7461
7462   if (Subtarget->isPICStyleRIPRel() &&
7463       (M == CodeModel::Small || M == CodeModel::Kernel))
7464     WrapperKind = X86ISD::WrapperRIP;
7465   else if (Subtarget->isPICStyleGOT())
7466     OpFlag = X86II::MO_GOTOFF;
7467   else if (Subtarget->isPICStyleStubPIC())
7468     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7469
7470   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7471                                           OpFlag);
7472   DebugLoc DL = JT->getDebugLoc();
7473   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7474
7475   // With PIC, the address is actually $g + Offset.
7476   if (OpFlag)
7477     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7478                          DAG.getNode(X86ISD::GlobalBaseReg,
7479                                      DebugLoc(), getPointerTy()),
7480                          Result);
7481
7482   return Result;
7483 }
7484
7485 SDValue
7486 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7487   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7488
7489   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7490   // global base reg.
7491   unsigned char OpFlag = 0;
7492   unsigned WrapperKind = X86ISD::Wrapper;
7493   CodeModel::Model M = getTargetMachine().getCodeModel();
7494
7495   if (Subtarget->isPICStyleRIPRel() &&
7496       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7497     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7498       OpFlag = X86II::MO_GOTPCREL;
7499     WrapperKind = X86ISD::WrapperRIP;
7500   } else if (Subtarget->isPICStyleGOT()) {
7501     OpFlag = X86II::MO_GOT;
7502   } else if (Subtarget->isPICStyleStubPIC()) {
7503     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7504   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7505     OpFlag = X86II::MO_DARWIN_NONLAZY;
7506   }
7507
7508   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7509
7510   DebugLoc DL = Op.getDebugLoc();
7511   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7512
7513   // With PIC, the address is actually $g + Offset.
7514   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7515       !Subtarget->is64Bit()) {
7516     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7517                          DAG.getNode(X86ISD::GlobalBaseReg,
7518                                      DebugLoc(), getPointerTy()),
7519                          Result);
7520   }
7521
7522   // For symbols that require a load from a stub to get the address, emit the
7523   // load.
7524   if (isGlobalStubReference(OpFlag))
7525     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7526                          MachinePointerInfo::getGOT(), false, false, false, 0);
7527
7528   return Result;
7529 }
7530
7531 SDValue
7532 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7533   // Create the TargetBlockAddressAddress node.
7534   unsigned char OpFlags =
7535     Subtarget->ClassifyBlockAddressReference();
7536   CodeModel::Model M = getTargetMachine().getCodeModel();
7537   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7538   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7539   DebugLoc dl = Op.getDebugLoc();
7540   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7541                                              OpFlags);
7542
7543   if (Subtarget->isPICStyleRIPRel() &&
7544       (M == CodeModel::Small || M == CodeModel::Kernel))
7545     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7546   else
7547     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7548
7549   // With PIC, the address is actually $g + Offset.
7550   if (isGlobalRelativeToPICBase(OpFlags)) {
7551     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7552                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7553                          Result);
7554   }
7555
7556   return Result;
7557 }
7558
7559 SDValue
7560 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7561                                       int64_t Offset, SelectionDAG &DAG) const {
7562   // Create the TargetGlobalAddress node, folding in the constant
7563   // offset if it is legal.
7564   unsigned char OpFlags =
7565     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7566   CodeModel::Model M = getTargetMachine().getCodeModel();
7567   SDValue Result;
7568   if (OpFlags == X86II::MO_NO_FLAG &&
7569       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7570     // A direct static reference to a global.
7571     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7572     Offset = 0;
7573   } else {
7574     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7575   }
7576
7577   if (Subtarget->isPICStyleRIPRel() &&
7578       (M == CodeModel::Small || M == CodeModel::Kernel))
7579     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7580   else
7581     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7582
7583   // With PIC, the address is actually $g + Offset.
7584   if (isGlobalRelativeToPICBase(OpFlags)) {
7585     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7586                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7587                          Result);
7588   }
7589
7590   // For globals that require a load from a stub to get the address, emit the
7591   // load.
7592   if (isGlobalStubReference(OpFlags))
7593     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7594                          MachinePointerInfo::getGOT(), false, false, false, 0);
7595
7596   // If there was a non-zero offset that we didn't fold, create an explicit
7597   // addition for it.
7598   if (Offset != 0)
7599     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7600                          DAG.getConstant(Offset, getPointerTy()));
7601
7602   return Result;
7603 }
7604
7605 SDValue
7606 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7607   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7608   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7609   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7610 }
7611
7612 static SDValue
7613 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7614            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7615            unsigned char OperandFlags, bool LocalDynamic = false) {
7616   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7617   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7618   DebugLoc dl = GA->getDebugLoc();
7619   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7620                                            GA->getValueType(0),
7621                                            GA->getOffset(),
7622                                            OperandFlags);
7623
7624   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7625                                            : X86ISD::TLSADDR;
7626
7627   if (InFlag) {
7628     SDValue Ops[] = { Chain,  TGA, *InFlag };
7629     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7630   } else {
7631     SDValue Ops[]  = { Chain, TGA };
7632     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7633   }
7634
7635   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7636   MFI->setAdjustsStack(true);
7637
7638   SDValue Flag = Chain.getValue(1);
7639   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7640 }
7641
7642 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7643 static SDValue
7644 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7645                                 const EVT PtrVT) {
7646   SDValue InFlag;
7647   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7648   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7649                                    DAG.getNode(X86ISD::GlobalBaseReg,
7650                                                DebugLoc(), PtrVT), InFlag);
7651   InFlag = Chain.getValue(1);
7652
7653   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7654 }
7655
7656 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7657 static SDValue
7658 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7659                                 const EVT PtrVT) {
7660   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7661                     X86::RAX, X86II::MO_TLSGD);
7662 }
7663
7664 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7665                                            SelectionDAG &DAG,
7666                                            const EVT PtrVT,
7667                                            bool is64Bit) {
7668   DebugLoc dl = GA->getDebugLoc();
7669
7670   // Get the start address of the TLS block for this module.
7671   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7672       .getInfo<X86MachineFunctionInfo>();
7673   MFI->incNumLocalDynamicTLSAccesses();
7674
7675   SDValue Base;
7676   if (is64Bit) {
7677     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7678                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7679   } else {
7680     SDValue InFlag;
7681     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7682         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7683     InFlag = Chain.getValue(1);
7684     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7685                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7686   }
7687
7688   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7689   // of Base.
7690
7691   // Build x@dtpoff.
7692   unsigned char OperandFlags = X86II::MO_DTPOFF;
7693   unsigned WrapperKind = X86ISD::Wrapper;
7694   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7695                                            GA->getValueType(0),
7696                                            GA->getOffset(), OperandFlags);
7697   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7698
7699   // Add x@dtpoff with the base.
7700   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7701 }
7702
7703 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7704 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7705                                    const EVT PtrVT, TLSModel::Model model,
7706                                    bool is64Bit, bool isPIC) {
7707   DebugLoc dl = GA->getDebugLoc();
7708
7709   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7710   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7711                                                          is64Bit ? 257 : 256));
7712
7713   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7714                                       DAG.getIntPtrConstant(0),
7715                                       MachinePointerInfo(Ptr),
7716                                       false, false, false, 0);
7717
7718   unsigned char OperandFlags = 0;
7719   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7720   // initialexec.
7721   unsigned WrapperKind = X86ISD::Wrapper;
7722   if (model == TLSModel::LocalExec) {
7723     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7724   } else if (model == TLSModel::InitialExec) {
7725     if (is64Bit) {
7726       OperandFlags = X86II::MO_GOTTPOFF;
7727       WrapperKind = X86ISD::WrapperRIP;
7728     } else {
7729       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7730     }
7731   } else {
7732     llvm_unreachable("Unexpected model");
7733   }
7734
7735   // emit "addl x@ntpoff,%eax" (local exec)
7736   // or "addl x@indntpoff,%eax" (initial exec)
7737   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7738   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7739                                            GA->getValueType(0),
7740                                            GA->getOffset(), OperandFlags);
7741   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7742
7743   if (model == TLSModel::InitialExec) {
7744     if (isPIC && !is64Bit) {
7745       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7746                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7747                            Offset);
7748     }
7749
7750     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7751                          MachinePointerInfo::getGOT(), false, false, false,
7752                          0);
7753   }
7754
7755   // The address of the thread local variable is the add of the thread
7756   // pointer with the offset of the variable.
7757   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7758 }
7759
7760 SDValue
7761 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7762
7763   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7764   const GlobalValue *GV = GA->getGlobal();
7765
7766   if (Subtarget->isTargetELF()) {
7767     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7768
7769     switch (model) {
7770       case TLSModel::GeneralDynamic:
7771         if (Subtarget->is64Bit())
7772           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7773         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7774       case TLSModel::LocalDynamic:
7775         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7776                                            Subtarget->is64Bit());
7777       case TLSModel::InitialExec:
7778       case TLSModel::LocalExec:
7779         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7780                                    Subtarget->is64Bit(),
7781                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7782     }
7783     llvm_unreachable("Unknown TLS model.");
7784   }
7785
7786   if (Subtarget->isTargetDarwin()) {
7787     // Darwin only has one model of TLS.  Lower to that.
7788     unsigned char OpFlag = 0;
7789     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7790                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7791
7792     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7793     // global base reg.
7794     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7795                   !Subtarget->is64Bit();
7796     if (PIC32)
7797       OpFlag = X86II::MO_TLVP_PIC_BASE;
7798     else
7799       OpFlag = X86II::MO_TLVP;
7800     DebugLoc DL = Op.getDebugLoc();
7801     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7802                                                 GA->getValueType(0),
7803                                                 GA->getOffset(), OpFlag);
7804     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7805
7806     // With PIC32, the address is actually $g + Offset.
7807     if (PIC32)
7808       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7809                            DAG.getNode(X86ISD::GlobalBaseReg,
7810                                        DebugLoc(), getPointerTy()),
7811                            Offset);
7812
7813     // Lowering the machine isd will make sure everything is in the right
7814     // location.
7815     SDValue Chain = DAG.getEntryNode();
7816     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7817     SDValue Args[] = { Chain, Offset };
7818     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7819
7820     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7821     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7822     MFI->setAdjustsStack(true);
7823
7824     // And our return value (tls address) is in the standard call return value
7825     // location.
7826     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7827     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7828                               Chain.getValue(1));
7829   }
7830
7831   if (Subtarget->isTargetWindows()) {
7832     // Just use the implicit TLS architecture
7833     // Need to generate someting similar to:
7834     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7835     //                                  ; from TEB
7836     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7837     //   mov     rcx, qword [rdx+rcx*8]
7838     //   mov     eax, .tls$:tlsvar
7839     //   [rax+rcx] contains the address
7840     // Windows 64bit: gs:0x58
7841     // Windows 32bit: fs:__tls_array
7842
7843     // If GV is an alias then use the aliasee for determining
7844     // thread-localness.
7845     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7846       GV = GA->resolveAliasedGlobal(false);
7847     DebugLoc dl = GA->getDebugLoc();
7848     SDValue Chain = DAG.getEntryNode();
7849
7850     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7851     // %gs:0x58 (64-bit).
7852     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7853                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7854                                                              256)
7855                                         : Type::getInt32PtrTy(*DAG.getContext(),
7856                                                               257));
7857
7858     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain,
7859                                         Subtarget->is64Bit()
7860                                         ? DAG.getIntPtrConstant(0x58)
7861                                         : DAG.getExternalSymbol("_tls_array",
7862                                                                 getPointerTy()),
7863                                         MachinePointerInfo(Ptr),
7864                                         false, false, false, 0);
7865
7866     // Load the _tls_index variable
7867     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7868     if (Subtarget->is64Bit())
7869       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7870                            IDX, MachinePointerInfo(), MVT::i32,
7871                            false, false, 0);
7872     else
7873       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7874                         false, false, false, 0);
7875
7876     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7877                                     getPointerTy());
7878     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7879
7880     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7881     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7882                       false, false, false, 0);
7883
7884     // Get the offset of start of .tls section
7885     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7886                                              GA->getValueType(0),
7887                                              GA->getOffset(), X86II::MO_SECREL);
7888     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7889
7890     // The address of the thread local variable is the add of the thread
7891     // pointer with the offset of the variable.
7892     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7893   }
7894
7895   llvm_unreachable("TLS not implemented for this target.");
7896 }
7897
7898 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7899 /// and take a 2 x i32 value to shift plus a shift amount.
7900 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7901   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7902   EVT VT = Op.getValueType();
7903   unsigned VTBits = VT.getSizeInBits();
7904   DebugLoc dl = Op.getDebugLoc();
7905   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7906   SDValue ShOpLo = Op.getOperand(0);
7907   SDValue ShOpHi = Op.getOperand(1);
7908   SDValue ShAmt  = Op.getOperand(2);
7909   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7910                                      DAG.getConstant(VTBits - 1, MVT::i8))
7911                        : DAG.getConstant(0, VT);
7912
7913   SDValue Tmp2, Tmp3;
7914   if (Op.getOpcode() == ISD::SHL_PARTS) {
7915     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7916     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7917   } else {
7918     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7919     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7920   }
7921
7922   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7923                                 DAG.getConstant(VTBits, MVT::i8));
7924   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7925                              AndNode, DAG.getConstant(0, MVT::i8));
7926
7927   SDValue Hi, Lo;
7928   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7929   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7930   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7931
7932   if (Op.getOpcode() == ISD::SHL_PARTS) {
7933     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7934     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7935   } else {
7936     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7937     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7938   }
7939
7940   SDValue Ops[2] = { Lo, Hi };
7941   return DAG.getMergeValues(Ops, 2, dl);
7942 }
7943
7944 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7945                                            SelectionDAG &DAG) const {
7946   EVT SrcVT = Op.getOperand(0).getValueType();
7947
7948   if (SrcVT.isVector())
7949     return SDValue();
7950
7951   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7952          "Unknown SINT_TO_FP to lower!");
7953
7954   // These are really Legal; return the operand so the caller accepts it as
7955   // Legal.
7956   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7957     return Op;
7958   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7959       Subtarget->is64Bit()) {
7960     return Op;
7961   }
7962
7963   DebugLoc dl = Op.getDebugLoc();
7964   unsigned Size = SrcVT.getSizeInBits()/8;
7965   MachineFunction &MF = DAG.getMachineFunction();
7966   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7967   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7968   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7969                                StackSlot,
7970                                MachinePointerInfo::getFixedStack(SSFI),
7971                                false, false, 0);
7972   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7973 }
7974
7975 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7976                                      SDValue StackSlot,
7977                                      SelectionDAG &DAG) const {
7978   // Build the FILD
7979   DebugLoc DL = Op.getDebugLoc();
7980   SDVTList Tys;
7981   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7982   if (useSSE)
7983     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7984   else
7985     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7986
7987   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7988
7989   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7990   MachineMemOperand *MMO;
7991   if (FI) {
7992     int SSFI = FI->getIndex();
7993     MMO =
7994       DAG.getMachineFunction()
7995       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7996                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7997   } else {
7998     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7999     StackSlot = StackSlot.getOperand(1);
8000   }
8001   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8002   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8003                                            X86ISD::FILD, DL,
8004                                            Tys, Ops, array_lengthof(Ops),
8005                                            SrcVT, MMO);
8006
8007   if (useSSE) {
8008     Chain = Result.getValue(1);
8009     SDValue InFlag = Result.getValue(2);
8010
8011     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8012     // shouldn't be necessary except that RFP cannot be live across
8013     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8014     MachineFunction &MF = DAG.getMachineFunction();
8015     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8016     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8017     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8018     Tys = DAG.getVTList(MVT::Other);
8019     SDValue Ops[] = {
8020       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8021     };
8022     MachineMemOperand *MMO =
8023       DAG.getMachineFunction()
8024       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8025                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8026
8027     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8028                                     Ops, array_lengthof(Ops),
8029                                     Op.getValueType(), MMO);
8030     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8031                          MachinePointerInfo::getFixedStack(SSFI),
8032                          false, false, false, 0);
8033   }
8034
8035   return Result;
8036 }
8037
8038 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8039 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8040                                                SelectionDAG &DAG) const {
8041   // This algorithm is not obvious. Here it is what we're trying to output:
8042   /*
8043      movq       %rax,  %xmm0
8044      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8045      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8046      #ifdef __SSE3__
8047        haddpd   %xmm0, %xmm0
8048      #else
8049        pshufd   $0x4e, %xmm0, %xmm1
8050        addpd    %xmm1, %xmm0
8051      #endif
8052   */
8053
8054   DebugLoc dl = Op.getDebugLoc();
8055   LLVMContext *Context = DAG.getContext();
8056
8057   // Build some magic constants.
8058   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8059   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8060   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8061
8062   SmallVector<Constant*,2> CV1;
8063   CV1.push_back(
8064     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8065                                       APInt(64, 0x4330000000000000ULL))));
8066   CV1.push_back(
8067     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8068                                       APInt(64, 0x4530000000000000ULL))));
8069   Constant *C1 = ConstantVector::get(CV1);
8070   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8071
8072   // Load the 64-bit value into an XMM register.
8073   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8074                             Op.getOperand(0));
8075   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8076                               MachinePointerInfo::getConstantPool(),
8077                               false, false, false, 16);
8078   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8079                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8080                               CLod0);
8081
8082   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8083                               MachinePointerInfo::getConstantPool(),
8084                               false, false, false, 16);
8085   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8086   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8087   SDValue Result;
8088
8089   if (Subtarget->hasSSE3()) {
8090     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8091     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8092   } else {
8093     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8094     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8095                                            S2F, 0x4E, DAG);
8096     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8097                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8098                          Sub);
8099   }
8100
8101   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8102                      DAG.getIntPtrConstant(0));
8103 }
8104
8105 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8106 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8107                                                SelectionDAG &DAG) const {
8108   DebugLoc dl = Op.getDebugLoc();
8109   // FP constant to bias correct the final result.
8110   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8111                                    MVT::f64);
8112
8113   // Load the 32-bit value into an XMM register.
8114   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8115                              Op.getOperand(0));
8116
8117   // Zero out the upper parts of the register.
8118   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8119
8120   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8121                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8122                      DAG.getIntPtrConstant(0));
8123
8124   // Or the load with the bias.
8125   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8126                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8127                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8128                                                    MVT::v2f64, Load)),
8129                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8130                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8131                                                    MVT::v2f64, Bias)));
8132   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8133                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8134                    DAG.getIntPtrConstant(0));
8135
8136   // Subtract the bias.
8137   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8138
8139   // Handle final rounding.
8140   EVT DestVT = Op.getValueType();
8141
8142   if (DestVT.bitsLT(MVT::f64))
8143     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8144                        DAG.getIntPtrConstant(0));
8145   if (DestVT.bitsGT(MVT::f64))
8146     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8147
8148   // Handle final rounding.
8149   return Sub;
8150 }
8151
8152 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8153                                                SelectionDAG &DAG) const {
8154   SDValue N0 = Op.getOperand(0);
8155   EVT SVT = N0.getValueType();
8156   DebugLoc dl = Op.getDebugLoc();
8157
8158   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8159           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8160          "Custom UINT_TO_FP is not supported!");
8161
8162   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8163                              SVT.getVectorNumElements());
8164   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8165                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8166 }
8167
8168 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8169                                            SelectionDAG &DAG) const {
8170   SDValue N0 = Op.getOperand(0);
8171   DebugLoc dl = Op.getDebugLoc();
8172
8173   if (Op.getValueType().isVector())
8174     return lowerUINT_TO_FP_vec(Op, DAG);
8175
8176   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8177   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8178   // the optimization here.
8179   if (DAG.SignBitIsZero(N0))
8180     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8181
8182   EVT SrcVT = N0.getValueType();
8183   EVT DstVT = Op.getValueType();
8184   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8185     return LowerUINT_TO_FP_i64(Op, DAG);
8186   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8187     return LowerUINT_TO_FP_i32(Op, DAG);
8188   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8189     return SDValue();
8190
8191   // Make a 64-bit buffer, and use it to build an FILD.
8192   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8193   if (SrcVT == MVT::i32) {
8194     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8195     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8196                                      getPointerTy(), StackSlot, WordOff);
8197     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8198                                   StackSlot, MachinePointerInfo(),
8199                                   false, false, 0);
8200     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8201                                   OffsetSlot, MachinePointerInfo(),
8202                                   false, false, 0);
8203     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8204     return Fild;
8205   }
8206
8207   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8208   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8209                                StackSlot, MachinePointerInfo(),
8210                                false, false, 0);
8211   // For i64 source, we need to add the appropriate power of 2 if the input
8212   // was negative.  This is the same as the optimization in
8213   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8214   // we must be careful to do the computation in x87 extended precision, not
8215   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8216   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8217   MachineMemOperand *MMO =
8218     DAG.getMachineFunction()
8219     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8220                           MachineMemOperand::MOLoad, 8, 8);
8221
8222   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8223   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8224   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8225                                          MVT::i64, MMO);
8226
8227   APInt FF(32, 0x5F800000ULL);
8228
8229   // Check whether the sign bit is set.
8230   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8231                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8232                                  ISD::SETLT);
8233
8234   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8235   SDValue FudgePtr = DAG.getConstantPool(
8236                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8237                                          getPointerTy());
8238
8239   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8240   SDValue Zero = DAG.getIntPtrConstant(0);
8241   SDValue Four = DAG.getIntPtrConstant(4);
8242   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8243                                Zero, Four);
8244   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8245
8246   // Load the value out, extending it from f32 to f80.
8247   // FIXME: Avoid the extend by constructing the right constant pool?
8248   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8249                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8250                                  MVT::f32, false, false, 4);
8251   // Extend everything to 80 bits to force it to be done on x87.
8252   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8253   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8254 }
8255
8256 std::pair<SDValue,SDValue>
8257 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8258                                     bool IsSigned, bool IsReplace) const {
8259   DebugLoc DL = Op.getDebugLoc();
8260
8261   EVT DstTy = Op.getValueType();
8262
8263   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8264     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8265     DstTy = MVT::i64;
8266   }
8267
8268   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8269          DstTy.getSimpleVT() >= MVT::i16 &&
8270          "Unknown FP_TO_INT to lower!");
8271
8272   // These are really Legal.
8273   if (DstTy == MVT::i32 &&
8274       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8275     return std::make_pair(SDValue(), SDValue());
8276   if (Subtarget->is64Bit() &&
8277       DstTy == MVT::i64 &&
8278       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8279     return std::make_pair(SDValue(), SDValue());
8280
8281   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8282   // stack slot, or into the FTOL runtime function.
8283   MachineFunction &MF = DAG.getMachineFunction();
8284   unsigned MemSize = DstTy.getSizeInBits()/8;
8285   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8286   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8287
8288   unsigned Opc;
8289   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8290     Opc = X86ISD::WIN_FTOL;
8291   else
8292     switch (DstTy.getSimpleVT().SimpleTy) {
8293     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8294     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8295     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8296     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8297     }
8298
8299   SDValue Chain = DAG.getEntryNode();
8300   SDValue Value = Op.getOperand(0);
8301   EVT TheVT = Op.getOperand(0).getValueType();
8302   // FIXME This causes a redundant load/store if the SSE-class value is already
8303   // in memory, such as if it is on the callstack.
8304   if (isScalarFPTypeInSSEReg(TheVT)) {
8305     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8306     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8307                          MachinePointerInfo::getFixedStack(SSFI),
8308                          false, false, 0);
8309     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8310     SDValue Ops[] = {
8311       Chain, StackSlot, DAG.getValueType(TheVT)
8312     };
8313
8314     MachineMemOperand *MMO =
8315       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8316                               MachineMemOperand::MOLoad, MemSize, MemSize);
8317     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8318                                     DstTy, MMO);
8319     Chain = Value.getValue(1);
8320     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8321     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8322   }
8323
8324   MachineMemOperand *MMO =
8325     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8326                             MachineMemOperand::MOStore, MemSize, MemSize);
8327
8328   if (Opc != X86ISD::WIN_FTOL) {
8329     // Build the FP_TO_INT*_IN_MEM
8330     SDValue Ops[] = { Chain, Value, StackSlot };
8331     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8332                                            Ops, 3, DstTy, MMO);
8333     return std::make_pair(FIST, StackSlot);
8334   } else {
8335     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8336       DAG.getVTList(MVT::Other, MVT::Glue),
8337       Chain, Value);
8338     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8339       MVT::i32, ftol.getValue(1));
8340     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8341       MVT::i32, eax.getValue(2));
8342     SDValue Ops[] = { eax, edx };
8343     SDValue pair = IsReplace
8344       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8345       : DAG.getMergeValues(Ops, 2, DL);
8346     return std::make_pair(pair, SDValue());
8347   }
8348 }
8349
8350 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8351                               const X86Subtarget *Subtarget) {
8352   MVT VT = Op->getValueType(0).getSimpleVT();
8353   SDValue In = Op->getOperand(0);
8354   MVT InVT = In.getValueType().getSimpleVT();
8355   DebugLoc dl = Op->getDebugLoc();
8356
8357   // Optimize vectors in AVX mode:
8358   //
8359   //   v8i16 -> v8i32
8360   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8361   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8362   //   Concat upper and lower parts.
8363   //
8364   //   v4i32 -> v4i64
8365   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8366   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8367   //   Concat upper and lower parts.
8368   //
8369
8370   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8371       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8372     return SDValue();
8373
8374   if (Subtarget->hasInt256())
8375     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8376
8377   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8378   SDValue Undef = DAG.getUNDEF(InVT);
8379   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8380   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8381   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8382
8383   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8384                              VT.getVectorNumElements()/2);
8385
8386   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8387   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8388
8389   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8390 }
8391
8392 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8393                                            SelectionDAG &DAG) const {
8394   if (Subtarget->hasFp256()) {
8395     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8396     if (Res.getNode())
8397       return Res;
8398   }
8399
8400   return SDValue();
8401 }
8402 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8403                                             SelectionDAG &DAG) const {
8404   DebugLoc DL = Op.getDebugLoc();
8405   MVT VT = Op.getValueType().getSimpleVT();
8406   SDValue In = Op.getOperand(0);
8407   MVT SVT = In.getValueType().getSimpleVT();
8408
8409   if (Subtarget->hasFp256()) {
8410     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8411     if (Res.getNode())
8412       return Res;
8413   }
8414
8415   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8416       VT.getVectorNumElements() != SVT.getVectorNumElements())
8417     return SDValue();
8418
8419   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8420
8421   // AVX2 has better support of integer extending.
8422   if (Subtarget->hasInt256())
8423     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8424
8425   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8426   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8427   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8428                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8429                                                 DAG.getUNDEF(MVT::v8i16),
8430                                                 &Mask[0]));
8431
8432   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8433 }
8434
8435 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8436   DebugLoc DL = Op.getDebugLoc();
8437   MVT VT = Op.getValueType().getSimpleVT();
8438   SDValue In = Op.getOperand(0);
8439   MVT SVT = In.getValueType().getSimpleVT();
8440
8441   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8442     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8443     if (Subtarget->hasInt256()) {
8444       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8445       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8446       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8447                                 ShufMask);
8448       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8449                          DAG.getIntPtrConstant(0));
8450     }
8451
8452     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8453     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8454                                DAG.getIntPtrConstant(0));
8455     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8456                                DAG.getIntPtrConstant(2));
8457
8458     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8459     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8460
8461     // The PSHUFD mask:
8462     static const int ShufMask1[] = {0, 2, 0, 0};
8463     SDValue Undef = DAG.getUNDEF(VT);
8464     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8465     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8466
8467     // The MOVLHPS mask:
8468     static const int ShufMask2[] = {0, 1, 4, 5};
8469     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8470   }
8471
8472   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8473     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8474     if (Subtarget->hasInt256()) {
8475       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8476
8477       SmallVector<SDValue,32> pshufbMask;
8478       for (unsigned i = 0; i < 2; ++i) {
8479         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8480         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8481         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8482         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8483         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8484         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8485         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8486         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8487         for (unsigned j = 0; j < 8; ++j)
8488           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8489       }
8490       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8491                                &pshufbMask[0], 32);
8492       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8493       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8494
8495       static const int ShufMask[] = {0,  2,  -1,  -1};
8496       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8497                                 &ShufMask[0]);
8498       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8499                        DAG.getIntPtrConstant(0));
8500       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8501     }
8502
8503     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8504                                DAG.getIntPtrConstant(0));
8505
8506     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8507                                DAG.getIntPtrConstant(4));
8508
8509     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8510     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8511
8512     // The PSHUFB mask:
8513     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8514                                    -1, -1, -1, -1, -1, -1, -1, -1};
8515
8516     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8517     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8518     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8519
8520     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8521     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8522
8523     // The MOVLHPS Mask:
8524     static const int ShufMask2[] = {0, 1, 4, 5};
8525     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8526     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8527   }
8528
8529   // Handle truncation of V256 to V128 using shuffles.
8530   if (!VT.is128BitVector() || !SVT.is256BitVector())
8531     return SDValue();
8532
8533   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8534          "Invalid op");
8535   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8536
8537   unsigned NumElems = VT.getVectorNumElements();
8538   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8539                              NumElems * 2);
8540
8541   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8542   // Prepare truncation shuffle mask
8543   for (unsigned i = 0; i != NumElems; ++i)
8544     MaskVec[i] = i * 2;
8545   SDValue V = DAG.getVectorShuffle(NVT, DL,
8546                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8547                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8548   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8549                      DAG.getIntPtrConstant(0));
8550 }
8551
8552 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8553                                            SelectionDAG &DAG) const {
8554   MVT VT = Op.getValueType().getSimpleVT();
8555   if (VT.isVector()) {
8556     if (VT == MVT::v8i16)
8557       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8558                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8559                                      MVT::v8i32, Op.getOperand(0)));
8560     return SDValue();
8561   }
8562
8563   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8564     /*IsSigned=*/ true, /*IsReplace=*/ false);
8565   SDValue FIST = Vals.first, StackSlot = Vals.second;
8566   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8567   if (FIST.getNode() == 0) return Op;
8568
8569   if (StackSlot.getNode())
8570     // Load the result.
8571     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8572                        FIST, StackSlot, MachinePointerInfo(),
8573                        false, false, false, 0);
8574
8575   // The node is the result.
8576   return FIST;
8577 }
8578
8579 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8580                                            SelectionDAG &DAG) const {
8581   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8582     /*IsSigned=*/ false, /*IsReplace=*/ false);
8583   SDValue FIST = Vals.first, StackSlot = Vals.second;
8584   assert(FIST.getNode() && "Unexpected failure");
8585
8586   if (StackSlot.getNode())
8587     // Load the result.
8588     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8589                        FIST, StackSlot, MachinePointerInfo(),
8590                        false, false, false, 0);
8591
8592   // The node is the result.
8593   return FIST;
8594 }
8595
8596 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8597   DebugLoc DL = Op.getDebugLoc();
8598   MVT VT = Op.getValueType().getSimpleVT();
8599   SDValue In = Op.getOperand(0);
8600   MVT SVT = In.getValueType().getSimpleVT();
8601
8602   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8603
8604   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8605                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8606                                  In, DAG.getUNDEF(SVT)));
8607 }
8608
8609 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8610   LLVMContext *Context = DAG.getContext();
8611   DebugLoc dl = Op.getDebugLoc();
8612   MVT VT = Op.getValueType().getSimpleVT();
8613   MVT EltVT = VT;
8614   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8615   if (VT.isVector()) {
8616     EltVT = VT.getVectorElementType();
8617     NumElts = VT.getVectorNumElements();
8618   }
8619   Constant *C;
8620   if (EltVT == MVT::f64)
8621     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8622                                           APInt(64, ~(1ULL << 63))));
8623   else
8624     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8625                                           APInt(32, ~(1U << 31))));
8626   C = ConstantVector::getSplat(NumElts, C);
8627   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8628   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8629   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8630                              MachinePointerInfo::getConstantPool(),
8631                              false, false, false, Alignment);
8632   if (VT.isVector()) {
8633     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8634     return DAG.getNode(ISD::BITCAST, dl, VT,
8635                        DAG.getNode(ISD::AND, dl, ANDVT,
8636                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8637                                                Op.getOperand(0)),
8638                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8639   }
8640   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8641 }
8642
8643 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8644   LLVMContext *Context = DAG.getContext();
8645   DebugLoc dl = Op.getDebugLoc();
8646   MVT VT = Op.getValueType().getSimpleVT();
8647   MVT EltVT = VT;
8648   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8649   if (VT.isVector()) {
8650     EltVT = VT.getVectorElementType();
8651     NumElts = VT.getVectorNumElements();
8652   }
8653   Constant *C;
8654   if (EltVT == MVT::f64)
8655     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8656                                           APInt(64, 1ULL << 63)));
8657   else
8658     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8659                                           APInt(32, 1U << 31)));
8660   C = ConstantVector::getSplat(NumElts, C);
8661   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8662   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8663   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8664                              MachinePointerInfo::getConstantPool(),
8665                              false, false, false, Alignment);
8666   if (VT.isVector()) {
8667     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8668     return DAG.getNode(ISD::BITCAST, dl, VT,
8669                        DAG.getNode(ISD::XOR, dl, XORVT,
8670                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8671                                                Op.getOperand(0)),
8672                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8673   }
8674
8675   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8676 }
8677
8678 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8679   LLVMContext *Context = DAG.getContext();
8680   SDValue Op0 = Op.getOperand(0);
8681   SDValue Op1 = Op.getOperand(1);
8682   DebugLoc dl = Op.getDebugLoc();
8683   MVT VT = Op.getValueType().getSimpleVT();
8684   MVT SrcVT = Op1.getValueType().getSimpleVT();
8685
8686   // If second operand is smaller, extend it first.
8687   if (SrcVT.bitsLT(VT)) {
8688     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8689     SrcVT = VT;
8690   }
8691   // And if it is bigger, shrink it first.
8692   if (SrcVT.bitsGT(VT)) {
8693     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8694     SrcVT = VT;
8695   }
8696
8697   // At this point the operands and the result should have the same
8698   // type, and that won't be f80 since that is not custom lowered.
8699
8700   // First get the sign bit of second operand.
8701   SmallVector<Constant*,4> CV;
8702   if (SrcVT == MVT::f64) {
8703     const fltSemantics &Sem = APFloat::IEEEdouble;
8704     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8705     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8706   } else {
8707     const fltSemantics &Sem = APFloat::IEEEsingle;
8708     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8709     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8710     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8711     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8712   }
8713   Constant *C = ConstantVector::get(CV);
8714   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8715   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8716                               MachinePointerInfo::getConstantPool(),
8717                               false, false, false, 16);
8718   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8719
8720   // Shift sign bit right or left if the two operands have different types.
8721   if (SrcVT.bitsGT(VT)) {
8722     // Op0 is MVT::f32, Op1 is MVT::f64.
8723     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8724     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8725                           DAG.getConstant(32, MVT::i32));
8726     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8727     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8728                           DAG.getIntPtrConstant(0));
8729   }
8730
8731   // Clear first operand sign bit.
8732   CV.clear();
8733   if (VT == MVT::f64) {
8734     const fltSemantics &Sem = APFloat::IEEEdouble;
8735     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8736                                                    APInt(64, ~(1ULL << 63)))));
8737     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8738   } else {
8739     const fltSemantics &Sem = APFloat::IEEEsingle;
8740     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8741                                                    APInt(32, ~(1U << 31)))));
8742     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8743     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8744     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8745   }
8746   C = ConstantVector::get(CV);
8747   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8748   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8749                               MachinePointerInfo::getConstantPool(),
8750                               false, false, false, 16);
8751   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8752
8753   // Or the value with the sign bit.
8754   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8755 }
8756
8757 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8758   SDValue N0 = Op.getOperand(0);
8759   DebugLoc dl = Op.getDebugLoc();
8760   MVT VT = Op.getValueType().getSimpleVT();
8761
8762   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8763   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8764                                   DAG.getConstant(1, VT));
8765   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8766 }
8767
8768 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8769 //
8770 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8771                                                   SelectionDAG &DAG) const {
8772   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8773
8774   if (!Subtarget->hasSSE41())
8775     return SDValue();
8776
8777   if (!Op->hasOneUse())
8778     return SDValue();
8779
8780   SDNode *N = Op.getNode();
8781   DebugLoc DL = N->getDebugLoc();
8782
8783   SmallVector<SDValue, 8> Opnds;
8784   DenseMap<SDValue, unsigned> VecInMap;
8785   EVT VT = MVT::Other;
8786
8787   // Recognize a special case where a vector is casted into wide integer to
8788   // test all 0s.
8789   Opnds.push_back(N->getOperand(0));
8790   Opnds.push_back(N->getOperand(1));
8791
8792   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8793     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8794     // BFS traverse all OR'd operands.
8795     if (I->getOpcode() == ISD::OR) {
8796       Opnds.push_back(I->getOperand(0));
8797       Opnds.push_back(I->getOperand(1));
8798       // Re-evaluate the number of nodes to be traversed.
8799       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8800       continue;
8801     }
8802
8803     // Quit if a non-EXTRACT_VECTOR_ELT
8804     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8805       return SDValue();
8806
8807     // Quit if without a constant index.
8808     SDValue Idx = I->getOperand(1);
8809     if (!isa<ConstantSDNode>(Idx))
8810       return SDValue();
8811
8812     SDValue ExtractedFromVec = I->getOperand(0);
8813     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8814     if (M == VecInMap.end()) {
8815       VT = ExtractedFromVec.getValueType();
8816       // Quit if not 128/256-bit vector.
8817       if (!VT.is128BitVector() && !VT.is256BitVector())
8818         return SDValue();
8819       // Quit if not the same type.
8820       if (VecInMap.begin() != VecInMap.end() &&
8821           VT != VecInMap.begin()->first.getValueType())
8822         return SDValue();
8823       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8824     }
8825     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8826   }
8827
8828   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8829          "Not extracted from 128-/256-bit vector.");
8830
8831   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8832   SmallVector<SDValue, 8> VecIns;
8833
8834   for (DenseMap<SDValue, unsigned>::const_iterator
8835         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8836     // Quit if not all elements are used.
8837     if (I->second != FullMask)
8838       return SDValue();
8839     VecIns.push_back(I->first);
8840   }
8841
8842   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8843
8844   // Cast all vectors into TestVT for PTEST.
8845   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8846     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8847
8848   // If more than one full vectors are evaluated, OR them first before PTEST.
8849   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8850     // Each iteration will OR 2 nodes and append the result until there is only
8851     // 1 node left, i.e. the final OR'd value of all vectors.
8852     SDValue LHS = VecIns[Slot];
8853     SDValue RHS = VecIns[Slot + 1];
8854     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8855   }
8856
8857   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8858                      VecIns.back(), VecIns.back());
8859 }
8860
8861 /// Emit nodes that will be selected as "test Op0,Op0", or something
8862 /// equivalent.
8863 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8864                                     SelectionDAG &DAG) const {
8865   DebugLoc dl = Op.getDebugLoc();
8866
8867   // CF and OF aren't always set the way we want. Determine which
8868   // of these we need.
8869   bool NeedCF = false;
8870   bool NeedOF = false;
8871   switch (X86CC) {
8872   default: break;
8873   case X86::COND_A: case X86::COND_AE:
8874   case X86::COND_B: case X86::COND_BE:
8875     NeedCF = true;
8876     break;
8877   case X86::COND_G: case X86::COND_GE:
8878   case X86::COND_L: case X86::COND_LE:
8879   case X86::COND_O: case X86::COND_NO:
8880     NeedOF = true;
8881     break;
8882   }
8883
8884   // See if we can use the EFLAGS value from the operand instead of
8885   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8886   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8887   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8888     // Emit a CMP with 0, which is the TEST pattern.
8889     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8890                        DAG.getConstant(0, Op.getValueType()));
8891
8892   unsigned Opcode = 0;
8893   unsigned NumOperands = 0;
8894
8895   // Truncate operations may prevent the merge of the SETCC instruction
8896   // and the arithmetic intruction before it. Attempt to truncate the operands
8897   // of the arithmetic instruction and use a reduced bit-width instruction.
8898   bool NeedTruncation = false;
8899   SDValue ArithOp = Op;
8900   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8901     SDValue Arith = Op->getOperand(0);
8902     // Both the trunc and the arithmetic op need to have one user each.
8903     if (Arith->hasOneUse())
8904       switch (Arith.getOpcode()) {
8905         default: break;
8906         case ISD::ADD:
8907         case ISD::SUB:
8908         case ISD::AND:
8909         case ISD::OR:
8910         case ISD::XOR: {
8911           NeedTruncation = true;
8912           ArithOp = Arith;
8913         }
8914       }
8915   }
8916
8917   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8918   // which may be the result of a CAST.  We use the variable 'Op', which is the
8919   // non-casted variable when we check for possible users.
8920   switch (ArithOp.getOpcode()) {
8921   case ISD::ADD:
8922     // Due to an isel shortcoming, be conservative if this add is likely to be
8923     // selected as part of a load-modify-store instruction. When the root node
8924     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8925     // uses of other nodes in the match, such as the ADD in this case. This
8926     // leads to the ADD being left around and reselected, with the result being
8927     // two adds in the output.  Alas, even if none our users are stores, that
8928     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8929     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8930     // climbing the DAG back to the root, and it doesn't seem to be worth the
8931     // effort.
8932     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8933          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8934       if (UI->getOpcode() != ISD::CopyToReg &&
8935           UI->getOpcode() != ISD::SETCC &&
8936           UI->getOpcode() != ISD::STORE)
8937         goto default_case;
8938
8939     if (ConstantSDNode *C =
8940         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8941       // An add of one will be selected as an INC.
8942       if (C->getAPIntValue() == 1) {
8943         Opcode = X86ISD::INC;
8944         NumOperands = 1;
8945         break;
8946       }
8947
8948       // An add of negative one (subtract of one) will be selected as a DEC.
8949       if (C->getAPIntValue().isAllOnesValue()) {
8950         Opcode = X86ISD::DEC;
8951         NumOperands = 1;
8952         break;
8953       }
8954     }
8955
8956     // Otherwise use a regular EFLAGS-setting add.
8957     Opcode = X86ISD::ADD;
8958     NumOperands = 2;
8959     break;
8960   case ISD::AND: {
8961     // If the primary and result isn't used, don't bother using X86ISD::AND,
8962     // because a TEST instruction will be better.
8963     bool NonFlagUse = false;
8964     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8965            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8966       SDNode *User = *UI;
8967       unsigned UOpNo = UI.getOperandNo();
8968       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8969         // Look pass truncate.
8970         UOpNo = User->use_begin().getOperandNo();
8971         User = *User->use_begin();
8972       }
8973
8974       if (User->getOpcode() != ISD::BRCOND &&
8975           User->getOpcode() != ISD::SETCC &&
8976           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8977         NonFlagUse = true;
8978         break;
8979       }
8980     }
8981
8982     if (!NonFlagUse)
8983       break;
8984   }
8985     // FALL THROUGH
8986   case ISD::SUB:
8987   case ISD::OR:
8988   case ISD::XOR:
8989     // Due to the ISEL shortcoming noted above, be conservative if this op is
8990     // likely to be selected as part of a load-modify-store instruction.
8991     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8992            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8993       if (UI->getOpcode() == ISD::STORE)
8994         goto default_case;
8995
8996     // Otherwise use a regular EFLAGS-setting instruction.
8997     switch (ArithOp.getOpcode()) {
8998     default: llvm_unreachable("unexpected operator!");
8999     case ISD::SUB: Opcode = X86ISD::SUB; break;
9000     case ISD::XOR: Opcode = X86ISD::XOR; break;
9001     case ISD::AND: Opcode = X86ISD::AND; break;
9002     case ISD::OR: {
9003       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9004         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9005         if (EFLAGS.getNode())
9006           return EFLAGS;
9007       }
9008       Opcode = X86ISD::OR;
9009       break;
9010     }
9011     }
9012
9013     NumOperands = 2;
9014     break;
9015   case X86ISD::ADD:
9016   case X86ISD::SUB:
9017   case X86ISD::INC:
9018   case X86ISD::DEC:
9019   case X86ISD::OR:
9020   case X86ISD::XOR:
9021   case X86ISD::AND:
9022     return SDValue(Op.getNode(), 1);
9023   default:
9024   default_case:
9025     break;
9026   }
9027
9028   // If we found that truncation is beneficial, perform the truncation and
9029   // update 'Op'.
9030   if (NeedTruncation) {
9031     EVT VT = Op.getValueType();
9032     SDValue WideVal = Op->getOperand(0);
9033     EVT WideVT = WideVal.getValueType();
9034     unsigned ConvertedOp = 0;
9035     // Use a target machine opcode to prevent further DAGCombine
9036     // optimizations that may separate the arithmetic operations
9037     // from the setcc node.
9038     switch (WideVal.getOpcode()) {
9039       default: break;
9040       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9041       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9042       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9043       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9044       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9045     }
9046
9047     if (ConvertedOp) {
9048       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9049       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9050         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9051         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9052         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9053       }
9054     }
9055   }
9056
9057   if (Opcode == 0)
9058     // Emit a CMP with 0, which is the TEST pattern.
9059     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9060                        DAG.getConstant(0, Op.getValueType()));
9061
9062   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9063   SmallVector<SDValue, 4> Ops;
9064   for (unsigned i = 0; i != NumOperands; ++i)
9065     Ops.push_back(Op.getOperand(i));
9066
9067   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9068   DAG.ReplaceAllUsesWith(Op, New);
9069   return SDValue(New.getNode(), 1);
9070 }
9071
9072 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9073 /// equivalent.
9074 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9075                                    SelectionDAG &DAG) const {
9076   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9077     if (C->getAPIntValue() == 0)
9078       return EmitTest(Op0, X86CC, DAG);
9079
9080   DebugLoc dl = Op0.getDebugLoc();
9081   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9082        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9083     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9084     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9085     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9086                               Op0, Op1);
9087     return SDValue(Sub.getNode(), 1);
9088   }
9089   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9090 }
9091
9092 /// Convert a comparison if required by the subtarget.
9093 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9094                                                  SelectionDAG &DAG) const {
9095   // If the subtarget does not support the FUCOMI instruction, floating-point
9096   // comparisons have to be converted.
9097   if (Subtarget->hasCMov() ||
9098       Cmp.getOpcode() != X86ISD::CMP ||
9099       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9100       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9101     return Cmp;
9102
9103   // The instruction selector will select an FUCOM instruction instead of
9104   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9105   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9106   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9107   DebugLoc dl = Cmp.getDebugLoc();
9108   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9109   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9110   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9111                             DAG.getConstant(8, MVT::i8));
9112   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9113   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9114 }
9115
9116 static bool isAllOnes(SDValue V) {
9117   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9118   return C && C->isAllOnesValue();
9119 }
9120
9121 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9122 /// if it's possible.
9123 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9124                                      DebugLoc dl, SelectionDAG &DAG) const {
9125   SDValue Op0 = And.getOperand(0);
9126   SDValue Op1 = And.getOperand(1);
9127   if (Op0.getOpcode() == ISD::TRUNCATE)
9128     Op0 = Op0.getOperand(0);
9129   if (Op1.getOpcode() == ISD::TRUNCATE)
9130     Op1 = Op1.getOperand(0);
9131
9132   SDValue LHS, RHS;
9133   if (Op1.getOpcode() == ISD::SHL)
9134     std::swap(Op0, Op1);
9135   if (Op0.getOpcode() == ISD::SHL) {
9136     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9137       if (And00C->getZExtValue() == 1) {
9138         // If we looked past a truncate, check that it's only truncating away
9139         // known zeros.
9140         unsigned BitWidth = Op0.getValueSizeInBits();
9141         unsigned AndBitWidth = And.getValueSizeInBits();
9142         if (BitWidth > AndBitWidth) {
9143           APInt Zeros, Ones;
9144           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9145           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9146             return SDValue();
9147         }
9148         LHS = Op1;
9149         RHS = Op0.getOperand(1);
9150       }
9151   } else if (Op1.getOpcode() == ISD::Constant) {
9152     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9153     uint64_t AndRHSVal = AndRHS->getZExtValue();
9154     SDValue AndLHS = Op0;
9155
9156     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9157       LHS = AndLHS.getOperand(0);
9158       RHS = AndLHS.getOperand(1);
9159     }
9160
9161     // Use BT if the immediate can't be encoded in a TEST instruction.
9162     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9163       LHS = AndLHS;
9164       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9165     }
9166   }
9167
9168   if (LHS.getNode()) {
9169     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9170     // the condition code later.
9171     bool Invert = false;
9172     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9173       Invert = true;
9174       LHS = LHS.getOperand(0);
9175     }
9176
9177     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9178     // instruction.  Since the shift amount is in-range-or-undefined, we know
9179     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9180     // the encoding for the i16 version is larger than the i32 version.
9181     // Also promote i16 to i32 for performance / code size reason.
9182     if (LHS.getValueType() == MVT::i8 ||
9183         LHS.getValueType() == MVT::i16)
9184       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9185
9186     // If the operand types disagree, extend the shift amount to match.  Since
9187     // BT ignores high bits (like shifts) we can use anyextend.
9188     if (LHS.getValueType() != RHS.getValueType())
9189       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9190
9191     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9192     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9193     // Flip the condition if the LHS was a not instruction
9194     if (Invert)
9195       Cond = X86::GetOppositeBranchCondition(Cond);
9196     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9197                        DAG.getConstant(Cond, MVT::i8), BT);
9198   }
9199
9200   return SDValue();
9201 }
9202
9203 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9204 // ones, and then concatenate the result back.
9205 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9206   MVT VT = Op.getValueType().getSimpleVT();
9207
9208   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9209          "Unsupported value type for operation");
9210
9211   unsigned NumElems = VT.getVectorNumElements();
9212   DebugLoc dl = Op.getDebugLoc();
9213   SDValue CC = Op.getOperand(2);
9214
9215   // Extract the LHS vectors
9216   SDValue LHS = Op.getOperand(0);
9217   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9218   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9219
9220   // Extract the RHS vectors
9221   SDValue RHS = Op.getOperand(1);
9222   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9223   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9224
9225   // Issue the operation on the smaller types and concatenate the result back
9226   MVT EltVT = VT.getVectorElementType();
9227   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9228   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9229                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9230                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9231 }
9232
9233 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9234                            SelectionDAG &DAG) {
9235   SDValue Cond;
9236   SDValue Op0 = Op.getOperand(0);
9237   SDValue Op1 = Op.getOperand(1);
9238   SDValue CC = Op.getOperand(2);
9239   MVT VT = Op.getValueType().getSimpleVT();
9240   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9241   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9242   DebugLoc dl = Op.getDebugLoc();
9243
9244   if (isFP) {
9245 #ifndef NDEBUG
9246     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9247     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9248 #endif
9249
9250     unsigned SSECC;
9251     bool Swap = false;
9252
9253     // SSE Condition code mapping:
9254     //  0 - EQ
9255     //  1 - LT
9256     //  2 - LE
9257     //  3 - UNORD
9258     //  4 - NEQ
9259     //  5 - NLT
9260     //  6 - NLE
9261     //  7 - ORD
9262     switch (SetCCOpcode) {
9263     default: llvm_unreachable("Unexpected SETCC condition");
9264     case ISD::SETOEQ:
9265     case ISD::SETEQ:  SSECC = 0; break;
9266     case ISD::SETOGT:
9267     case ISD::SETGT: Swap = true; // Fallthrough
9268     case ISD::SETLT:
9269     case ISD::SETOLT: SSECC = 1; break;
9270     case ISD::SETOGE:
9271     case ISD::SETGE: Swap = true; // Fallthrough
9272     case ISD::SETLE:
9273     case ISD::SETOLE: SSECC = 2; break;
9274     case ISD::SETUO:  SSECC = 3; break;
9275     case ISD::SETUNE:
9276     case ISD::SETNE:  SSECC = 4; break;
9277     case ISD::SETULE: Swap = true; // Fallthrough
9278     case ISD::SETUGE: SSECC = 5; break;
9279     case ISD::SETULT: Swap = true; // Fallthrough
9280     case ISD::SETUGT: SSECC = 6; break;
9281     case ISD::SETO:   SSECC = 7; break;
9282     case ISD::SETUEQ:
9283     case ISD::SETONE: SSECC = 8; break;
9284     }
9285     if (Swap)
9286       std::swap(Op0, Op1);
9287
9288     // In the two special cases we can't handle, emit two comparisons.
9289     if (SSECC == 8) {
9290       unsigned CC0, CC1;
9291       unsigned CombineOpc;
9292       if (SetCCOpcode == ISD::SETUEQ) {
9293         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9294       } else {
9295         assert(SetCCOpcode == ISD::SETONE);
9296         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9297       }
9298
9299       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9300                                  DAG.getConstant(CC0, MVT::i8));
9301       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9302                                  DAG.getConstant(CC1, MVT::i8));
9303       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9304     }
9305     // Handle all other FP comparisons here.
9306     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9307                        DAG.getConstant(SSECC, MVT::i8));
9308   }
9309
9310   // Break 256-bit integer vector compare into smaller ones.
9311   if (VT.is256BitVector() && !Subtarget->hasInt256())
9312     return Lower256IntVSETCC(Op, DAG);
9313
9314   // We are handling one of the integer comparisons here.  Since SSE only has
9315   // GT and EQ comparisons for integer, swapping operands and multiple
9316   // operations may be required for some comparisons.
9317   unsigned Opc;
9318   bool Swap = false, Invert = false, FlipSigns = false;
9319
9320   switch (SetCCOpcode) {
9321   default: llvm_unreachable("Unexpected SETCC condition");
9322   case ISD::SETNE:  Invert = true;
9323   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9324   case ISD::SETLT:  Swap = true;
9325   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9326   case ISD::SETGE:  Swap = true;
9327   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9328   case ISD::SETULT: Swap = true;
9329   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9330   case ISD::SETUGE: Swap = true;
9331   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9332   }
9333   if (Swap)
9334     std::swap(Op0, Op1);
9335
9336   // Check that the operation in question is available (most are plain SSE2,
9337   // but PCMPGTQ and PCMPEQQ have different requirements).
9338   if (VT == MVT::v2i64) {
9339     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42())
9340       return SDValue();
9341     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9342       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9343       // pcmpeqd + pshufd + pand.
9344       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9345
9346       // First cast everything to the right type,
9347       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9348       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9349
9350       // Do the compare.
9351       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9352
9353       // Make sure the lower and upper halves are both all-ones.
9354       const int Mask[] = { 1, 0, 3, 2 };
9355       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9356       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9357
9358       if (Invert)
9359         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9360
9361       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9362     }
9363   }
9364
9365   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9366   // bits of the inputs before performing those operations.
9367   if (FlipSigns) {
9368     EVT EltVT = VT.getVectorElementType();
9369     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9370                                       EltVT);
9371     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9372     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9373                                     SignBits.size());
9374     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9375     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9376   }
9377
9378   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9379
9380   // If the logical-not of the result is required, perform that now.
9381   if (Invert)
9382     Result = DAG.getNOT(dl, Result, VT);
9383
9384   return Result;
9385 }
9386
9387 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9388
9389   MVT VT = Op.getValueType().getSimpleVT();
9390
9391   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9392
9393   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9394   SDValue Op0 = Op.getOperand(0);
9395   SDValue Op1 = Op.getOperand(1);
9396   DebugLoc dl = Op.getDebugLoc();
9397   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9398
9399   // Optimize to BT if possible.
9400   // Lower (X & (1 << N)) == 0 to BT(X, N).
9401   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9402   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9403   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9404       Op1.getOpcode() == ISD::Constant &&
9405       cast<ConstantSDNode>(Op1)->isNullValue() &&
9406       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9407     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9408     if (NewSetCC.getNode())
9409       return NewSetCC;
9410   }
9411
9412   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9413   // these.
9414   if (Op1.getOpcode() == ISD::Constant &&
9415       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9416        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9417       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9418
9419     // If the input is a setcc, then reuse the input setcc or use a new one with
9420     // the inverted condition.
9421     if (Op0.getOpcode() == X86ISD::SETCC) {
9422       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9423       bool Invert = (CC == ISD::SETNE) ^
9424         cast<ConstantSDNode>(Op1)->isNullValue();
9425       if (!Invert) return Op0;
9426
9427       CCode = X86::GetOppositeBranchCondition(CCode);
9428       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9429                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9430     }
9431   }
9432
9433   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9434   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9435   if (X86CC == X86::COND_INVALID)
9436     return SDValue();
9437
9438   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9439   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9440   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9441                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9442 }
9443
9444 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9445 static bool isX86LogicalCmp(SDValue Op) {
9446   unsigned Opc = Op.getNode()->getOpcode();
9447   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9448       Opc == X86ISD::SAHF)
9449     return true;
9450   if (Op.getResNo() == 1 &&
9451       (Opc == X86ISD::ADD ||
9452        Opc == X86ISD::SUB ||
9453        Opc == X86ISD::ADC ||
9454        Opc == X86ISD::SBB ||
9455        Opc == X86ISD::SMUL ||
9456        Opc == X86ISD::UMUL ||
9457        Opc == X86ISD::INC ||
9458        Opc == X86ISD::DEC ||
9459        Opc == X86ISD::OR ||
9460        Opc == X86ISD::XOR ||
9461        Opc == X86ISD::AND))
9462     return true;
9463
9464   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9465     return true;
9466
9467   return false;
9468 }
9469
9470 static bool isZero(SDValue V) {
9471   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9472   return C && C->isNullValue();
9473 }
9474
9475 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9476   if (V.getOpcode() != ISD::TRUNCATE)
9477     return false;
9478
9479   SDValue VOp0 = V.getOperand(0);
9480   unsigned InBits = VOp0.getValueSizeInBits();
9481   unsigned Bits = V.getValueSizeInBits();
9482   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9483 }
9484
9485 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9486   bool addTest = true;
9487   SDValue Cond  = Op.getOperand(0);
9488   SDValue Op1 = Op.getOperand(1);
9489   SDValue Op2 = Op.getOperand(2);
9490   DebugLoc DL = Op.getDebugLoc();
9491   SDValue CC;
9492
9493   if (Cond.getOpcode() == ISD::SETCC) {
9494     SDValue NewCond = LowerSETCC(Cond, DAG);
9495     if (NewCond.getNode())
9496       Cond = NewCond;
9497   }
9498
9499   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9500   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9501   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9502   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9503   if (Cond.getOpcode() == X86ISD::SETCC &&
9504       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9505       isZero(Cond.getOperand(1).getOperand(1))) {
9506     SDValue Cmp = Cond.getOperand(1);
9507
9508     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9509
9510     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9511         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9512       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9513
9514       SDValue CmpOp0 = Cmp.getOperand(0);
9515       // Apply further optimizations for special cases
9516       // (select (x != 0), -1, 0) -> neg & sbb
9517       // (select (x == 0), 0, -1) -> neg & sbb
9518       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9519         if (YC->isNullValue() &&
9520             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9521           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9522           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9523                                     DAG.getConstant(0, CmpOp0.getValueType()),
9524                                     CmpOp0);
9525           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9526                                     DAG.getConstant(X86::COND_B, MVT::i8),
9527                                     SDValue(Neg.getNode(), 1));
9528           return Res;
9529         }
9530
9531       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9532                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9533       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9534
9535       SDValue Res =   // Res = 0 or -1.
9536         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9537                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9538
9539       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9540         Res = DAG.getNOT(DL, Res, Res.getValueType());
9541
9542       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9543       if (N2C == 0 || !N2C->isNullValue())
9544         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9545       return Res;
9546     }
9547   }
9548
9549   // Look past (and (setcc_carry (cmp ...)), 1).
9550   if (Cond.getOpcode() == ISD::AND &&
9551       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9552     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9553     if (C && C->getAPIntValue() == 1)
9554       Cond = Cond.getOperand(0);
9555   }
9556
9557   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9558   // setting operand in place of the X86ISD::SETCC.
9559   unsigned CondOpcode = Cond.getOpcode();
9560   if (CondOpcode == X86ISD::SETCC ||
9561       CondOpcode == X86ISD::SETCC_CARRY) {
9562     CC = Cond.getOperand(0);
9563
9564     SDValue Cmp = Cond.getOperand(1);
9565     unsigned Opc = Cmp.getOpcode();
9566     MVT VT = Op.getValueType().getSimpleVT();
9567
9568     bool IllegalFPCMov = false;
9569     if (VT.isFloatingPoint() && !VT.isVector() &&
9570         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9571       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9572
9573     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9574         Opc == X86ISD::BT) { // FIXME
9575       Cond = Cmp;
9576       addTest = false;
9577     }
9578   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9579              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9580              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9581               Cond.getOperand(0).getValueType() != MVT::i8)) {
9582     SDValue LHS = Cond.getOperand(0);
9583     SDValue RHS = Cond.getOperand(1);
9584     unsigned X86Opcode;
9585     unsigned X86Cond;
9586     SDVTList VTs;
9587     switch (CondOpcode) {
9588     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9589     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9590     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9591     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9592     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9593     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9594     default: llvm_unreachable("unexpected overflowing operator");
9595     }
9596     if (CondOpcode == ISD::UMULO)
9597       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9598                           MVT::i32);
9599     else
9600       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9601
9602     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9603
9604     if (CondOpcode == ISD::UMULO)
9605       Cond = X86Op.getValue(2);
9606     else
9607       Cond = X86Op.getValue(1);
9608
9609     CC = DAG.getConstant(X86Cond, MVT::i8);
9610     addTest = false;
9611   }
9612
9613   if (addTest) {
9614     // Look pass the truncate if the high bits are known zero.
9615     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9616         Cond = Cond.getOperand(0);
9617
9618     // We know the result of AND is compared against zero. Try to match
9619     // it to BT.
9620     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9621       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9622       if (NewSetCC.getNode()) {
9623         CC = NewSetCC.getOperand(0);
9624         Cond = NewSetCC.getOperand(1);
9625         addTest = false;
9626       }
9627     }
9628   }
9629
9630   if (addTest) {
9631     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9632     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9633   }
9634
9635   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9636   // a <  b ?  0 : -1 -> RES = setcc_carry
9637   // a >= b ? -1 :  0 -> RES = setcc_carry
9638   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9639   if (Cond.getOpcode() == X86ISD::SUB) {
9640     Cond = ConvertCmpIfNecessary(Cond, DAG);
9641     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9642
9643     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9644         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9645       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9646                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9647       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9648         return DAG.getNOT(DL, Res, Res.getValueType());
9649       return Res;
9650     }
9651   }
9652
9653   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9654   // widen the cmov and push the truncate through. This avoids introducing a new
9655   // branch during isel and doesn't add any extensions.
9656   if (Op.getValueType() == MVT::i8 &&
9657       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9658     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9659     if (T1.getValueType() == T2.getValueType() &&
9660         // Blacklist CopyFromReg to avoid partial register stalls.
9661         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9662       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9663       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9664       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9665     }
9666   }
9667
9668   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9669   // condition is true.
9670   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9671   SDValue Ops[] = { Op2, Op1, CC, Cond };
9672   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9673 }
9674
9675 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9676                                             SelectionDAG &DAG) const {
9677   MVT VT = Op->getValueType(0).getSimpleVT();
9678   SDValue In = Op->getOperand(0);
9679   MVT InVT = In.getValueType().getSimpleVT();
9680   DebugLoc dl = Op->getDebugLoc();
9681
9682   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9683       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9684     return SDValue();
9685
9686   if (Subtarget->hasInt256())
9687     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9688
9689   // Optimize vectors in AVX mode
9690   // Sign extend  v8i16 to v8i32 and
9691   //              v4i32 to v4i64
9692   //
9693   // Divide input vector into two parts
9694   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9695   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9696   // concat the vectors to original VT
9697
9698   unsigned NumElems = InVT.getVectorNumElements();
9699   SDValue Undef = DAG.getUNDEF(InVT);
9700
9701   SmallVector<int,8> ShufMask1(NumElems, -1);
9702   for (unsigned i = 0; i != NumElems/2; ++i)
9703     ShufMask1[i] = i;
9704
9705   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9706
9707   SmallVector<int,8> ShufMask2(NumElems, -1);
9708   for (unsigned i = 0; i != NumElems/2; ++i)
9709     ShufMask2[i] = i + NumElems/2;
9710
9711   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9712
9713   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9714                                 VT.getVectorNumElements()/2);
9715
9716   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9717   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9718
9719   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9720 }
9721
9722 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9723 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9724 // from the AND / OR.
9725 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9726   Opc = Op.getOpcode();
9727   if (Opc != ISD::OR && Opc != ISD::AND)
9728     return false;
9729   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9730           Op.getOperand(0).hasOneUse() &&
9731           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9732           Op.getOperand(1).hasOneUse());
9733 }
9734
9735 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9736 // 1 and that the SETCC node has a single use.
9737 static bool isXor1OfSetCC(SDValue Op) {
9738   if (Op.getOpcode() != ISD::XOR)
9739     return false;
9740   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9741   if (N1C && N1C->getAPIntValue() == 1) {
9742     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9743       Op.getOperand(0).hasOneUse();
9744   }
9745   return false;
9746 }
9747
9748 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9749   bool addTest = true;
9750   SDValue Chain = Op.getOperand(0);
9751   SDValue Cond  = Op.getOperand(1);
9752   SDValue Dest  = Op.getOperand(2);
9753   DebugLoc dl = Op.getDebugLoc();
9754   SDValue CC;
9755   bool Inverted = false;
9756
9757   if (Cond.getOpcode() == ISD::SETCC) {
9758     // Check for setcc([su]{add,sub,mul}o == 0).
9759     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9760         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9761         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9762         Cond.getOperand(0).getResNo() == 1 &&
9763         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9764          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9765          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9766          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9767          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9768          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9769       Inverted = true;
9770       Cond = Cond.getOperand(0);
9771     } else {
9772       SDValue NewCond = LowerSETCC(Cond, DAG);
9773       if (NewCond.getNode())
9774         Cond = NewCond;
9775     }
9776   }
9777 #if 0
9778   // FIXME: LowerXALUO doesn't handle these!!
9779   else if (Cond.getOpcode() == X86ISD::ADD  ||
9780            Cond.getOpcode() == X86ISD::SUB  ||
9781            Cond.getOpcode() == X86ISD::SMUL ||
9782            Cond.getOpcode() == X86ISD::UMUL)
9783     Cond = LowerXALUO(Cond, DAG);
9784 #endif
9785
9786   // Look pass (and (setcc_carry (cmp ...)), 1).
9787   if (Cond.getOpcode() == ISD::AND &&
9788       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9789     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9790     if (C && C->getAPIntValue() == 1)
9791       Cond = Cond.getOperand(0);
9792   }
9793
9794   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9795   // setting operand in place of the X86ISD::SETCC.
9796   unsigned CondOpcode = Cond.getOpcode();
9797   if (CondOpcode == X86ISD::SETCC ||
9798       CondOpcode == X86ISD::SETCC_CARRY) {
9799     CC = Cond.getOperand(0);
9800
9801     SDValue Cmp = Cond.getOperand(1);
9802     unsigned Opc = Cmp.getOpcode();
9803     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9804     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9805       Cond = Cmp;
9806       addTest = false;
9807     } else {
9808       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9809       default: break;
9810       case X86::COND_O:
9811       case X86::COND_B:
9812         // These can only come from an arithmetic instruction with overflow,
9813         // e.g. SADDO, UADDO.
9814         Cond = Cond.getNode()->getOperand(1);
9815         addTest = false;
9816         break;
9817       }
9818     }
9819   }
9820   CondOpcode = Cond.getOpcode();
9821   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9822       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9823       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9824        Cond.getOperand(0).getValueType() != MVT::i8)) {
9825     SDValue LHS = Cond.getOperand(0);
9826     SDValue RHS = Cond.getOperand(1);
9827     unsigned X86Opcode;
9828     unsigned X86Cond;
9829     SDVTList VTs;
9830     switch (CondOpcode) {
9831     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9832     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9833     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9834     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9835     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9836     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9837     default: llvm_unreachable("unexpected overflowing operator");
9838     }
9839     if (Inverted)
9840       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9841     if (CondOpcode == ISD::UMULO)
9842       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9843                           MVT::i32);
9844     else
9845       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9846
9847     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9848
9849     if (CondOpcode == ISD::UMULO)
9850       Cond = X86Op.getValue(2);
9851     else
9852       Cond = X86Op.getValue(1);
9853
9854     CC = DAG.getConstant(X86Cond, MVT::i8);
9855     addTest = false;
9856   } else {
9857     unsigned CondOpc;
9858     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9859       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9860       if (CondOpc == ISD::OR) {
9861         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9862         // two branches instead of an explicit OR instruction with a
9863         // separate test.
9864         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9865             isX86LogicalCmp(Cmp)) {
9866           CC = Cond.getOperand(0).getOperand(0);
9867           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9868                               Chain, Dest, CC, Cmp);
9869           CC = Cond.getOperand(1).getOperand(0);
9870           Cond = Cmp;
9871           addTest = false;
9872         }
9873       } else { // ISD::AND
9874         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9875         // two branches instead of an explicit AND instruction with a
9876         // separate test. However, we only do this if this block doesn't
9877         // have a fall-through edge, because this requires an explicit
9878         // jmp when the condition is false.
9879         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9880             isX86LogicalCmp(Cmp) &&
9881             Op.getNode()->hasOneUse()) {
9882           X86::CondCode CCode =
9883             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9884           CCode = X86::GetOppositeBranchCondition(CCode);
9885           CC = DAG.getConstant(CCode, MVT::i8);
9886           SDNode *User = *Op.getNode()->use_begin();
9887           // Look for an unconditional branch following this conditional branch.
9888           // We need this because we need to reverse the successors in order
9889           // to implement FCMP_OEQ.
9890           if (User->getOpcode() == ISD::BR) {
9891             SDValue FalseBB = User->getOperand(1);
9892             SDNode *NewBR =
9893               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9894             assert(NewBR == User);
9895             (void)NewBR;
9896             Dest = FalseBB;
9897
9898             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9899                                 Chain, Dest, CC, Cmp);
9900             X86::CondCode CCode =
9901               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9902             CCode = X86::GetOppositeBranchCondition(CCode);
9903             CC = DAG.getConstant(CCode, MVT::i8);
9904             Cond = Cmp;
9905             addTest = false;
9906           }
9907         }
9908       }
9909     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9910       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9911       // It should be transformed during dag combiner except when the condition
9912       // is set by a arithmetics with overflow node.
9913       X86::CondCode CCode =
9914         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9915       CCode = X86::GetOppositeBranchCondition(CCode);
9916       CC = DAG.getConstant(CCode, MVT::i8);
9917       Cond = Cond.getOperand(0).getOperand(1);
9918       addTest = false;
9919     } else if (Cond.getOpcode() == ISD::SETCC &&
9920                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9921       // For FCMP_OEQ, we can emit
9922       // two branches instead of an explicit AND instruction with a
9923       // separate test. However, we only do this if this block doesn't
9924       // have a fall-through edge, because this requires an explicit
9925       // jmp when the condition is false.
9926       if (Op.getNode()->hasOneUse()) {
9927         SDNode *User = *Op.getNode()->use_begin();
9928         // Look for an unconditional branch following this conditional branch.
9929         // We need this because we need to reverse the successors in order
9930         // to implement FCMP_OEQ.
9931         if (User->getOpcode() == ISD::BR) {
9932           SDValue FalseBB = User->getOperand(1);
9933           SDNode *NewBR =
9934             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9935           assert(NewBR == User);
9936           (void)NewBR;
9937           Dest = FalseBB;
9938
9939           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9940                                     Cond.getOperand(0), Cond.getOperand(1));
9941           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9942           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9943           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9944                               Chain, Dest, CC, Cmp);
9945           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9946           Cond = Cmp;
9947           addTest = false;
9948         }
9949       }
9950     } else if (Cond.getOpcode() == ISD::SETCC &&
9951                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9952       // For FCMP_UNE, we can emit
9953       // two branches instead of an explicit AND instruction with a
9954       // separate test. However, we only do this if this block doesn't
9955       // have a fall-through edge, because this requires an explicit
9956       // jmp when the condition is false.
9957       if (Op.getNode()->hasOneUse()) {
9958         SDNode *User = *Op.getNode()->use_begin();
9959         // Look for an unconditional branch following this conditional branch.
9960         // We need this because we need to reverse the successors in order
9961         // to implement FCMP_UNE.
9962         if (User->getOpcode() == ISD::BR) {
9963           SDValue FalseBB = User->getOperand(1);
9964           SDNode *NewBR =
9965             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9966           assert(NewBR == User);
9967           (void)NewBR;
9968
9969           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9970                                     Cond.getOperand(0), Cond.getOperand(1));
9971           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9972           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9973           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9974                               Chain, Dest, CC, Cmp);
9975           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9976           Cond = Cmp;
9977           addTest = false;
9978           Dest = FalseBB;
9979         }
9980       }
9981     }
9982   }
9983
9984   if (addTest) {
9985     // Look pass the truncate if the high bits are known zero.
9986     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9987         Cond = Cond.getOperand(0);
9988
9989     // We know the result of AND is compared against zero. Try to match
9990     // it to BT.
9991     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9992       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9993       if (NewSetCC.getNode()) {
9994         CC = NewSetCC.getOperand(0);
9995         Cond = NewSetCC.getOperand(1);
9996         addTest = false;
9997       }
9998     }
9999   }
10000
10001   if (addTest) {
10002     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10003     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10004   }
10005   Cond = ConvertCmpIfNecessary(Cond, DAG);
10006   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10007                      Chain, Dest, CC, Cond);
10008 }
10009
10010 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10011 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10012 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10013 // that the guard pages used by the OS virtual memory manager are allocated in
10014 // correct sequence.
10015 SDValue
10016 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10017                                            SelectionDAG &DAG) const {
10018   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10019           getTargetMachine().Options.EnableSegmentedStacks) &&
10020          "This should be used only on Windows targets or when segmented stacks "
10021          "are being used");
10022   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10023   DebugLoc dl = Op.getDebugLoc();
10024
10025   // Get the inputs.
10026   SDValue Chain = Op.getOperand(0);
10027   SDValue Size  = Op.getOperand(1);
10028   // FIXME: Ensure alignment here
10029
10030   bool Is64Bit = Subtarget->is64Bit();
10031   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10032
10033   if (getTargetMachine().Options.EnableSegmentedStacks) {
10034     MachineFunction &MF = DAG.getMachineFunction();
10035     MachineRegisterInfo &MRI = MF.getRegInfo();
10036
10037     if (Is64Bit) {
10038       // The 64 bit implementation of segmented stacks needs to clobber both r10
10039       // r11. This makes it impossible to use it along with nested parameters.
10040       const Function *F = MF.getFunction();
10041
10042       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10043            I != E; ++I)
10044         if (I->hasNestAttr())
10045           report_fatal_error("Cannot use segmented stacks with functions that "
10046                              "have nested arguments.");
10047     }
10048
10049     const TargetRegisterClass *AddrRegClass =
10050       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10051     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10052     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10053     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10054                                 DAG.getRegister(Vreg, SPTy));
10055     SDValue Ops1[2] = { Value, Chain };
10056     return DAG.getMergeValues(Ops1, 2, dl);
10057   } else {
10058     SDValue Flag;
10059     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10060
10061     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10062     Flag = Chain.getValue(1);
10063     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10064
10065     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10066     Flag = Chain.getValue(1);
10067
10068     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10069                                SPTy).getValue(1);
10070
10071     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10072     return DAG.getMergeValues(Ops1, 2, dl);
10073   }
10074 }
10075
10076 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10077   MachineFunction &MF = DAG.getMachineFunction();
10078   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10079
10080   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10081   DebugLoc DL = Op.getDebugLoc();
10082
10083   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10084     // vastart just stores the address of the VarArgsFrameIndex slot into the
10085     // memory location argument.
10086     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10087                                    getPointerTy());
10088     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10089                         MachinePointerInfo(SV), false, false, 0);
10090   }
10091
10092   // __va_list_tag:
10093   //   gp_offset         (0 - 6 * 8)
10094   //   fp_offset         (48 - 48 + 8 * 16)
10095   //   overflow_arg_area (point to parameters coming in memory).
10096   //   reg_save_area
10097   SmallVector<SDValue, 8> MemOps;
10098   SDValue FIN = Op.getOperand(1);
10099   // Store gp_offset
10100   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10101                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10102                                                MVT::i32),
10103                                FIN, MachinePointerInfo(SV), false, false, 0);
10104   MemOps.push_back(Store);
10105
10106   // Store fp_offset
10107   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10108                     FIN, DAG.getIntPtrConstant(4));
10109   Store = DAG.getStore(Op.getOperand(0), DL,
10110                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10111                                        MVT::i32),
10112                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10113   MemOps.push_back(Store);
10114
10115   // Store ptr to overflow_arg_area
10116   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10117                     FIN, DAG.getIntPtrConstant(4));
10118   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10119                                     getPointerTy());
10120   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10121                        MachinePointerInfo(SV, 8),
10122                        false, false, 0);
10123   MemOps.push_back(Store);
10124
10125   // Store ptr to reg_save_area.
10126   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10127                     FIN, DAG.getIntPtrConstant(8));
10128   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10129                                     getPointerTy());
10130   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10131                        MachinePointerInfo(SV, 16), false, false, 0);
10132   MemOps.push_back(Store);
10133   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10134                      &MemOps[0], MemOps.size());
10135 }
10136
10137 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10138   assert(Subtarget->is64Bit() &&
10139          "LowerVAARG only handles 64-bit va_arg!");
10140   assert((Subtarget->isTargetLinux() ||
10141           Subtarget->isTargetDarwin()) &&
10142           "Unhandled target in LowerVAARG");
10143   assert(Op.getNode()->getNumOperands() == 4);
10144   SDValue Chain = Op.getOperand(0);
10145   SDValue SrcPtr = Op.getOperand(1);
10146   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10147   unsigned Align = Op.getConstantOperandVal(3);
10148   DebugLoc dl = Op.getDebugLoc();
10149
10150   EVT ArgVT = Op.getNode()->getValueType(0);
10151   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10152   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10153   uint8_t ArgMode;
10154
10155   // Decide which area this value should be read from.
10156   // TODO: Implement the AMD64 ABI in its entirety. This simple
10157   // selection mechanism works only for the basic types.
10158   if (ArgVT == MVT::f80) {
10159     llvm_unreachable("va_arg for f80 not yet implemented");
10160   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10161     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10162   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10163     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10164   } else {
10165     llvm_unreachable("Unhandled argument type in LowerVAARG");
10166   }
10167
10168   if (ArgMode == 2) {
10169     // Sanity Check: Make sure using fp_offset makes sense.
10170     assert(!getTargetMachine().Options.UseSoftFloat &&
10171            !(DAG.getMachineFunction()
10172                 .getFunction()->getAttributes()
10173                 .hasAttribute(AttributeSet::FunctionIndex,
10174                               Attribute::NoImplicitFloat)) &&
10175            Subtarget->hasSSE1());
10176   }
10177
10178   // Insert VAARG_64 node into the DAG
10179   // VAARG_64 returns two values: Variable Argument Address, Chain
10180   SmallVector<SDValue, 11> InstOps;
10181   InstOps.push_back(Chain);
10182   InstOps.push_back(SrcPtr);
10183   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10184   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10185   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10186   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10187   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10188                                           VTs, &InstOps[0], InstOps.size(),
10189                                           MVT::i64,
10190                                           MachinePointerInfo(SV),
10191                                           /*Align=*/0,
10192                                           /*Volatile=*/false,
10193                                           /*ReadMem=*/true,
10194                                           /*WriteMem=*/true);
10195   Chain = VAARG.getValue(1);
10196
10197   // Load the next argument and return it
10198   return DAG.getLoad(ArgVT, dl,
10199                      Chain,
10200                      VAARG,
10201                      MachinePointerInfo(),
10202                      false, false, false, 0);
10203 }
10204
10205 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10206                            SelectionDAG &DAG) {
10207   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10208   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10209   SDValue Chain = Op.getOperand(0);
10210   SDValue DstPtr = Op.getOperand(1);
10211   SDValue SrcPtr = Op.getOperand(2);
10212   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10213   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10214   DebugLoc DL = Op.getDebugLoc();
10215
10216   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10217                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10218                        false,
10219                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10220 }
10221
10222 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10223 // may or may not be a constant. Takes immediate version of shift as input.
10224 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10225                                    SDValue SrcOp, SDValue ShAmt,
10226                                    SelectionDAG &DAG) {
10227   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10228
10229   if (isa<ConstantSDNode>(ShAmt)) {
10230     // Constant may be a TargetConstant. Use a regular constant.
10231     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10232     switch (Opc) {
10233       default: llvm_unreachable("Unknown target vector shift node");
10234       case X86ISD::VSHLI:
10235       case X86ISD::VSRLI:
10236       case X86ISD::VSRAI:
10237         return DAG.getNode(Opc, dl, VT, SrcOp,
10238                            DAG.getConstant(ShiftAmt, MVT::i32));
10239     }
10240   }
10241
10242   // Change opcode to non-immediate version
10243   switch (Opc) {
10244     default: llvm_unreachable("Unknown target vector shift node");
10245     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10246     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10247     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10248   }
10249
10250   // Need to build a vector containing shift amount
10251   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10252   SDValue ShOps[4];
10253   ShOps[0] = ShAmt;
10254   ShOps[1] = DAG.getConstant(0, MVT::i32);
10255   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10256   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10257
10258   // The return type has to be a 128-bit type with the same element
10259   // type as the input type.
10260   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10261   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10262
10263   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10264   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10265 }
10266
10267 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10268   DebugLoc dl = Op.getDebugLoc();
10269   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10270   switch (IntNo) {
10271   default: return SDValue();    // Don't custom lower most intrinsics.
10272   // Comparison intrinsics.
10273   case Intrinsic::x86_sse_comieq_ss:
10274   case Intrinsic::x86_sse_comilt_ss:
10275   case Intrinsic::x86_sse_comile_ss:
10276   case Intrinsic::x86_sse_comigt_ss:
10277   case Intrinsic::x86_sse_comige_ss:
10278   case Intrinsic::x86_sse_comineq_ss:
10279   case Intrinsic::x86_sse_ucomieq_ss:
10280   case Intrinsic::x86_sse_ucomilt_ss:
10281   case Intrinsic::x86_sse_ucomile_ss:
10282   case Intrinsic::x86_sse_ucomigt_ss:
10283   case Intrinsic::x86_sse_ucomige_ss:
10284   case Intrinsic::x86_sse_ucomineq_ss:
10285   case Intrinsic::x86_sse2_comieq_sd:
10286   case Intrinsic::x86_sse2_comilt_sd:
10287   case Intrinsic::x86_sse2_comile_sd:
10288   case Intrinsic::x86_sse2_comigt_sd:
10289   case Intrinsic::x86_sse2_comige_sd:
10290   case Intrinsic::x86_sse2_comineq_sd:
10291   case Intrinsic::x86_sse2_ucomieq_sd:
10292   case Intrinsic::x86_sse2_ucomilt_sd:
10293   case Intrinsic::x86_sse2_ucomile_sd:
10294   case Intrinsic::x86_sse2_ucomigt_sd:
10295   case Intrinsic::x86_sse2_ucomige_sd:
10296   case Intrinsic::x86_sse2_ucomineq_sd: {
10297     unsigned Opc;
10298     ISD::CondCode CC;
10299     switch (IntNo) {
10300     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10301     case Intrinsic::x86_sse_comieq_ss:
10302     case Intrinsic::x86_sse2_comieq_sd:
10303       Opc = X86ISD::COMI;
10304       CC = ISD::SETEQ;
10305       break;
10306     case Intrinsic::x86_sse_comilt_ss:
10307     case Intrinsic::x86_sse2_comilt_sd:
10308       Opc = X86ISD::COMI;
10309       CC = ISD::SETLT;
10310       break;
10311     case Intrinsic::x86_sse_comile_ss:
10312     case Intrinsic::x86_sse2_comile_sd:
10313       Opc = X86ISD::COMI;
10314       CC = ISD::SETLE;
10315       break;
10316     case Intrinsic::x86_sse_comigt_ss:
10317     case Intrinsic::x86_sse2_comigt_sd:
10318       Opc = X86ISD::COMI;
10319       CC = ISD::SETGT;
10320       break;
10321     case Intrinsic::x86_sse_comige_ss:
10322     case Intrinsic::x86_sse2_comige_sd:
10323       Opc = X86ISD::COMI;
10324       CC = ISD::SETGE;
10325       break;
10326     case Intrinsic::x86_sse_comineq_ss:
10327     case Intrinsic::x86_sse2_comineq_sd:
10328       Opc = X86ISD::COMI;
10329       CC = ISD::SETNE;
10330       break;
10331     case Intrinsic::x86_sse_ucomieq_ss:
10332     case Intrinsic::x86_sse2_ucomieq_sd:
10333       Opc = X86ISD::UCOMI;
10334       CC = ISD::SETEQ;
10335       break;
10336     case Intrinsic::x86_sse_ucomilt_ss:
10337     case Intrinsic::x86_sse2_ucomilt_sd:
10338       Opc = X86ISD::UCOMI;
10339       CC = ISD::SETLT;
10340       break;
10341     case Intrinsic::x86_sse_ucomile_ss:
10342     case Intrinsic::x86_sse2_ucomile_sd:
10343       Opc = X86ISD::UCOMI;
10344       CC = ISD::SETLE;
10345       break;
10346     case Intrinsic::x86_sse_ucomigt_ss:
10347     case Intrinsic::x86_sse2_ucomigt_sd:
10348       Opc = X86ISD::UCOMI;
10349       CC = ISD::SETGT;
10350       break;
10351     case Intrinsic::x86_sse_ucomige_ss:
10352     case Intrinsic::x86_sse2_ucomige_sd:
10353       Opc = X86ISD::UCOMI;
10354       CC = ISD::SETGE;
10355       break;
10356     case Intrinsic::x86_sse_ucomineq_ss:
10357     case Intrinsic::x86_sse2_ucomineq_sd:
10358       Opc = X86ISD::UCOMI;
10359       CC = ISD::SETNE;
10360       break;
10361     }
10362
10363     SDValue LHS = Op.getOperand(1);
10364     SDValue RHS = Op.getOperand(2);
10365     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10366     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10367     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10368     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10369                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10370     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10371   }
10372
10373   // Arithmetic intrinsics.
10374   case Intrinsic::x86_sse2_pmulu_dq:
10375   case Intrinsic::x86_avx2_pmulu_dq:
10376     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10377                        Op.getOperand(1), Op.getOperand(2));
10378
10379   // SSE2/AVX2 sub with unsigned saturation intrinsics
10380   case Intrinsic::x86_sse2_psubus_b:
10381   case Intrinsic::x86_sse2_psubus_w:
10382   case Intrinsic::x86_avx2_psubus_b:
10383   case Intrinsic::x86_avx2_psubus_w:
10384     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10385                        Op.getOperand(1), Op.getOperand(2));
10386
10387   // SSE3/AVX horizontal add/sub intrinsics
10388   case Intrinsic::x86_sse3_hadd_ps:
10389   case Intrinsic::x86_sse3_hadd_pd:
10390   case Intrinsic::x86_avx_hadd_ps_256:
10391   case Intrinsic::x86_avx_hadd_pd_256:
10392   case Intrinsic::x86_sse3_hsub_ps:
10393   case Intrinsic::x86_sse3_hsub_pd:
10394   case Intrinsic::x86_avx_hsub_ps_256:
10395   case Intrinsic::x86_avx_hsub_pd_256:
10396   case Intrinsic::x86_ssse3_phadd_w_128:
10397   case Intrinsic::x86_ssse3_phadd_d_128:
10398   case Intrinsic::x86_avx2_phadd_w:
10399   case Intrinsic::x86_avx2_phadd_d:
10400   case Intrinsic::x86_ssse3_phsub_w_128:
10401   case Intrinsic::x86_ssse3_phsub_d_128:
10402   case Intrinsic::x86_avx2_phsub_w:
10403   case Intrinsic::x86_avx2_phsub_d: {
10404     unsigned Opcode;
10405     switch (IntNo) {
10406     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10407     case Intrinsic::x86_sse3_hadd_ps:
10408     case Intrinsic::x86_sse3_hadd_pd:
10409     case Intrinsic::x86_avx_hadd_ps_256:
10410     case Intrinsic::x86_avx_hadd_pd_256:
10411       Opcode = X86ISD::FHADD;
10412       break;
10413     case Intrinsic::x86_sse3_hsub_ps:
10414     case Intrinsic::x86_sse3_hsub_pd:
10415     case Intrinsic::x86_avx_hsub_ps_256:
10416     case Intrinsic::x86_avx_hsub_pd_256:
10417       Opcode = X86ISD::FHSUB;
10418       break;
10419     case Intrinsic::x86_ssse3_phadd_w_128:
10420     case Intrinsic::x86_ssse3_phadd_d_128:
10421     case Intrinsic::x86_avx2_phadd_w:
10422     case Intrinsic::x86_avx2_phadd_d:
10423       Opcode = X86ISD::HADD;
10424       break;
10425     case Intrinsic::x86_ssse3_phsub_w_128:
10426     case Intrinsic::x86_ssse3_phsub_d_128:
10427     case Intrinsic::x86_avx2_phsub_w:
10428     case Intrinsic::x86_avx2_phsub_d:
10429       Opcode = X86ISD::HSUB;
10430       break;
10431     }
10432     return DAG.getNode(Opcode, dl, Op.getValueType(),
10433                        Op.getOperand(1), Op.getOperand(2));
10434   }
10435
10436   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10437   case Intrinsic::x86_sse2_pmaxu_b:
10438   case Intrinsic::x86_sse41_pmaxuw:
10439   case Intrinsic::x86_sse41_pmaxud:
10440   case Intrinsic::x86_avx2_pmaxu_b:
10441   case Intrinsic::x86_avx2_pmaxu_w:
10442   case Intrinsic::x86_avx2_pmaxu_d:
10443   case Intrinsic::x86_sse2_pminu_b:
10444   case Intrinsic::x86_sse41_pminuw:
10445   case Intrinsic::x86_sse41_pminud:
10446   case Intrinsic::x86_avx2_pminu_b:
10447   case Intrinsic::x86_avx2_pminu_w:
10448   case Intrinsic::x86_avx2_pminu_d:
10449   case Intrinsic::x86_sse41_pmaxsb:
10450   case Intrinsic::x86_sse2_pmaxs_w:
10451   case Intrinsic::x86_sse41_pmaxsd:
10452   case Intrinsic::x86_avx2_pmaxs_b:
10453   case Intrinsic::x86_avx2_pmaxs_w:
10454   case Intrinsic::x86_avx2_pmaxs_d:
10455   case Intrinsic::x86_sse41_pminsb:
10456   case Intrinsic::x86_sse2_pmins_w:
10457   case Intrinsic::x86_sse41_pminsd:
10458   case Intrinsic::x86_avx2_pmins_b:
10459   case Intrinsic::x86_avx2_pmins_w:
10460   case Intrinsic::x86_avx2_pmins_d: {
10461     unsigned Opcode;
10462     switch (IntNo) {
10463     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10464     case Intrinsic::x86_sse2_pmaxu_b:
10465     case Intrinsic::x86_sse41_pmaxuw:
10466     case Intrinsic::x86_sse41_pmaxud:
10467     case Intrinsic::x86_avx2_pmaxu_b:
10468     case Intrinsic::x86_avx2_pmaxu_w:
10469     case Intrinsic::x86_avx2_pmaxu_d:
10470       Opcode = X86ISD::UMAX;
10471       break;
10472     case Intrinsic::x86_sse2_pminu_b:
10473     case Intrinsic::x86_sse41_pminuw:
10474     case Intrinsic::x86_sse41_pminud:
10475     case Intrinsic::x86_avx2_pminu_b:
10476     case Intrinsic::x86_avx2_pminu_w:
10477     case Intrinsic::x86_avx2_pminu_d:
10478       Opcode = X86ISD::UMIN;
10479       break;
10480     case Intrinsic::x86_sse41_pmaxsb:
10481     case Intrinsic::x86_sse2_pmaxs_w:
10482     case Intrinsic::x86_sse41_pmaxsd:
10483     case Intrinsic::x86_avx2_pmaxs_b:
10484     case Intrinsic::x86_avx2_pmaxs_w:
10485     case Intrinsic::x86_avx2_pmaxs_d:
10486       Opcode = X86ISD::SMAX;
10487       break;
10488     case Intrinsic::x86_sse41_pminsb:
10489     case Intrinsic::x86_sse2_pmins_w:
10490     case Intrinsic::x86_sse41_pminsd:
10491     case Intrinsic::x86_avx2_pmins_b:
10492     case Intrinsic::x86_avx2_pmins_w:
10493     case Intrinsic::x86_avx2_pmins_d:
10494       Opcode = X86ISD::SMIN;
10495       break;
10496     }
10497     return DAG.getNode(Opcode, dl, Op.getValueType(),
10498                        Op.getOperand(1), Op.getOperand(2));
10499   }
10500
10501   // SSE/SSE2/AVX floating point max/min intrinsics.
10502   case Intrinsic::x86_sse_max_ps:
10503   case Intrinsic::x86_sse2_max_pd:
10504   case Intrinsic::x86_avx_max_ps_256:
10505   case Intrinsic::x86_avx_max_pd_256:
10506   case Intrinsic::x86_sse_min_ps:
10507   case Intrinsic::x86_sse2_min_pd:
10508   case Intrinsic::x86_avx_min_ps_256:
10509   case Intrinsic::x86_avx_min_pd_256: {
10510     unsigned Opcode;
10511     switch (IntNo) {
10512     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10513     case Intrinsic::x86_sse_max_ps:
10514     case Intrinsic::x86_sse2_max_pd:
10515     case Intrinsic::x86_avx_max_ps_256:
10516     case Intrinsic::x86_avx_max_pd_256:
10517       Opcode = X86ISD::FMAX;
10518       break;
10519     case Intrinsic::x86_sse_min_ps:
10520     case Intrinsic::x86_sse2_min_pd:
10521     case Intrinsic::x86_avx_min_ps_256:
10522     case Intrinsic::x86_avx_min_pd_256:
10523       Opcode = X86ISD::FMIN;
10524       break;
10525     }
10526     return DAG.getNode(Opcode, dl, Op.getValueType(),
10527                        Op.getOperand(1), Op.getOperand(2));
10528   }
10529
10530   // AVX2 variable shift intrinsics
10531   case Intrinsic::x86_avx2_psllv_d:
10532   case Intrinsic::x86_avx2_psllv_q:
10533   case Intrinsic::x86_avx2_psllv_d_256:
10534   case Intrinsic::x86_avx2_psllv_q_256:
10535   case Intrinsic::x86_avx2_psrlv_d:
10536   case Intrinsic::x86_avx2_psrlv_q:
10537   case Intrinsic::x86_avx2_psrlv_d_256:
10538   case Intrinsic::x86_avx2_psrlv_q_256:
10539   case Intrinsic::x86_avx2_psrav_d:
10540   case Intrinsic::x86_avx2_psrav_d_256: {
10541     unsigned Opcode;
10542     switch (IntNo) {
10543     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10544     case Intrinsic::x86_avx2_psllv_d:
10545     case Intrinsic::x86_avx2_psllv_q:
10546     case Intrinsic::x86_avx2_psllv_d_256:
10547     case Intrinsic::x86_avx2_psllv_q_256:
10548       Opcode = ISD::SHL;
10549       break;
10550     case Intrinsic::x86_avx2_psrlv_d:
10551     case Intrinsic::x86_avx2_psrlv_q:
10552     case Intrinsic::x86_avx2_psrlv_d_256:
10553     case Intrinsic::x86_avx2_psrlv_q_256:
10554       Opcode = ISD::SRL;
10555       break;
10556     case Intrinsic::x86_avx2_psrav_d:
10557     case Intrinsic::x86_avx2_psrav_d_256:
10558       Opcode = ISD::SRA;
10559       break;
10560     }
10561     return DAG.getNode(Opcode, dl, Op.getValueType(),
10562                        Op.getOperand(1), Op.getOperand(2));
10563   }
10564
10565   case Intrinsic::x86_ssse3_pshuf_b_128:
10566   case Intrinsic::x86_avx2_pshuf_b:
10567     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10568                        Op.getOperand(1), Op.getOperand(2));
10569
10570   case Intrinsic::x86_ssse3_psign_b_128:
10571   case Intrinsic::x86_ssse3_psign_w_128:
10572   case Intrinsic::x86_ssse3_psign_d_128:
10573   case Intrinsic::x86_avx2_psign_b:
10574   case Intrinsic::x86_avx2_psign_w:
10575   case Intrinsic::x86_avx2_psign_d:
10576     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10577                        Op.getOperand(1), Op.getOperand(2));
10578
10579   case Intrinsic::x86_sse41_insertps:
10580     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10581                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10582
10583   case Intrinsic::x86_avx_vperm2f128_ps_256:
10584   case Intrinsic::x86_avx_vperm2f128_pd_256:
10585   case Intrinsic::x86_avx_vperm2f128_si_256:
10586   case Intrinsic::x86_avx2_vperm2i128:
10587     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10588                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10589
10590   case Intrinsic::x86_avx2_permd:
10591   case Intrinsic::x86_avx2_permps:
10592     // Operands intentionally swapped. Mask is last operand to intrinsic,
10593     // but second operand for node/intruction.
10594     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10595                        Op.getOperand(2), Op.getOperand(1));
10596
10597   case Intrinsic::x86_sse_sqrt_ps:
10598   case Intrinsic::x86_sse2_sqrt_pd:
10599   case Intrinsic::x86_avx_sqrt_ps_256:
10600   case Intrinsic::x86_avx_sqrt_pd_256:
10601     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10602
10603   // ptest and testp intrinsics. The intrinsic these come from are designed to
10604   // return an integer value, not just an instruction so lower it to the ptest
10605   // or testp pattern and a setcc for the result.
10606   case Intrinsic::x86_sse41_ptestz:
10607   case Intrinsic::x86_sse41_ptestc:
10608   case Intrinsic::x86_sse41_ptestnzc:
10609   case Intrinsic::x86_avx_ptestz_256:
10610   case Intrinsic::x86_avx_ptestc_256:
10611   case Intrinsic::x86_avx_ptestnzc_256:
10612   case Intrinsic::x86_avx_vtestz_ps:
10613   case Intrinsic::x86_avx_vtestc_ps:
10614   case Intrinsic::x86_avx_vtestnzc_ps:
10615   case Intrinsic::x86_avx_vtestz_pd:
10616   case Intrinsic::x86_avx_vtestc_pd:
10617   case Intrinsic::x86_avx_vtestnzc_pd:
10618   case Intrinsic::x86_avx_vtestz_ps_256:
10619   case Intrinsic::x86_avx_vtestc_ps_256:
10620   case Intrinsic::x86_avx_vtestnzc_ps_256:
10621   case Intrinsic::x86_avx_vtestz_pd_256:
10622   case Intrinsic::x86_avx_vtestc_pd_256:
10623   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10624     bool IsTestPacked = false;
10625     unsigned X86CC;
10626     switch (IntNo) {
10627     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10628     case Intrinsic::x86_avx_vtestz_ps:
10629     case Intrinsic::x86_avx_vtestz_pd:
10630     case Intrinsic::x86_avx_vtestz_ps_256:
10631     case Intrinsic::x86_avx_vtestz_pd_256:
10632       IsTestPacked = true; // Fallthrough
10633     case Intrinsic::x86_sse41_ptestz:
10634     case Intrinsic::x86_avx_ptestz_256:
10635       // ZF = 1
10636       X86CC = X86::COND_E;
10637       break;
10638     case Intrinsic::x86_avx_vtestc_ps:
10639     case Intrinsic::x86_avx_vtestc_pd:
10640     case Intrinsic::x86_avx_vtestc_ps_256:
10641     case Intrinsic::x86_avx_vtestc_pd_256:
10642       IsTestPacked = true; // Fallthrough
10643     case Intrinsic::x86_sse41_ptestc:
10644     case Intrinsic::x86_avx_ptestc_256:
10645       // CF = 1
10646       X86CC = X86::COND_B;
10647       break;
10648     case Intrinsic::x86_avx_vtestnzc_ps:
10649     case Intrinsic::x86_avx_vtestnzc_pd:
10650     case Intrinsic::x86_avx_vtestnzc_ps_256:
10651     case Intrinsic::x86_avx_vtestnzc_pd_256:
10652       IsTestPacked = true; // Fallthrough
10653     case Intrinsic::x86_sse41_ptestnzc:
10654     case Intrinsic::x86_avx_ptestnzc_256:
10655       // ZF and CF = 0
10656       X86CC = X86::COND_A;
10657       break;
10658     }
10659
10660     SDValue LHS = Op.getOperand(1);
10661     SDValue RHS = Op.getOperand(2);
10662     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10663     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10664     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10665     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10666     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10667   }
10668
10669   // SSE/AVX shift intrinsics
10670   case Intrinsic::x86_sse2_psll_w:
10671   case Intrinsic::x86_sse2_psll_d:
10672   case Intrinsic::x86_sse2_psll_q:
10673   case Intrinsic::x86_avx2_psll_w:
10674   case Intrinsic::x86_avx2_psll_d:
10675   case Intrinsic::x86_avx2_psll_q:
10676   case Intrinsic::x86_sse2_psrl_w:
10677   case Intrinsic::x86_sse2_psrl_d:
10678   case Intrinsic::x86_sse2_psrl_q:
10679   case Intrinsic::x86_avx2_psrl_w:
10680   case Intrinsic::x86_avx2_psrl_d:
10681   case Intrinsic::x86_avx2_psrl_q:
10682   case Intrinsic::x86_sse2_psra_w:
10683   case Intrinsic::x86_sse2_psra_d:
10684   case Intrinsic::x86_avx2_psra_w:
10685   case Intrinsic::x86_avx2_psra_d: {
10686     unsigned Opcode;
10687     switch (IntNo) {
10688     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10689     case Intrinsic::x86_sse2_psll_w:
10690     case Intrinsic::x86_sse2_psll_d:
10691     case Intrinsic::x86_sse2_psll_q:
10692     case Intrinsic::x86_avx2_psll_w:
10693     case Intrinsic::x86_avx2_psll_d:
10694     case Intrinsic::x86_avx2_psll_q:
10695       Opcode = X86ISD::VSHL;
10696       break;
10697     case Intrinsic::x86_sse2_psrl_w:
10698     case Intrinsic::x86_sse2_psrl_d:
10699     case Intrinsic::x86_sse2_psrl_q:
10700     case Intrinsic::x86_avx2_psrl_w:
10701     case Intrinsic::x86_avx2_psrl_d:
10702     case Intrinsic::x86_avx2_psrl_q:
10703       Opcode = X86ISD::VSRL;
10704       break;
10705     case Intrinsic::x86_sse2_psra_w:
10706     case Intrinsic::x86_sse2_psra_d:
10707     case Intrinsic::x86_avx2_psra_w:
10708     case Intrinsic::x86_avx2_psra_d:
10709       Opcode = X86ISD::VSRA;
10710       break;
10711     }
10712     return DAG.getNode(Opcode, dl, Op.getValueType(),
10713                        Op.getOperand(1), Op.getOperand(2));
10714   }
10715
10716   // SSE/AVX immediate shift intrinsics
10717   case Intrinsic::x86_sse2_pslli_w:
10718   case Intrinsic::x86_sse2_pslli_d:
10719   case Intrinsic::x86_sse2_pslli_q:
10720   case Intrinsic::x86_avx2_pslli_w:
10721   case Intrinsic::x86_avx2_pslli_d:
10722   case Intrinsic::x86_avx2_pslli_q:
10723   case Intrinsic::x86_sse2_psrli_w:
10724   case Intrinsic::x86_sse2_psrli_d:
10725   case Intrinsic::x86_sse2_psrli_q:
10726   case Intrinsic::x86_avx2_psrli_w:
10727   case Intrinsic::x86_avx2_psrli_d:
10728   case Intrinsic::x86_avx2_psrli_q:
10729   case Intrinsic::x86_sse2_psrai_w:
10730   case Intrinsic::x86_sse2_psrai_d:
10731   case Intrinsic::x86_avx2_psrai_w:
10732   case Intrinsic::x86_avx2_psrai_d: {
10733     unsigned Opcode;
10734     switch (IntNo) {
10735     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10736     case Intrinsic::x86_sse2_pslli_w:
10737     case Intrinsic::x86_sse2_pslli_d:
10738     case Intrinsic::x86_sse2_pslli_q:
10739     case Intrinsic::x86_avx2_pslli_w:
10740     case Intrinsic::x86_avx2_pslli_d:
10741     case Intrinsic::x86_avx2_pslli_q:
10742       Opcode = X86ISD::VSHLI;
10743       break;
10744     case Intrinsic::x86_sse2_psrli_w:
10745     case Intrinsic::x86_sse2_psrli_d:
10746     case Intrinsic::x86_sse2_psrli_q:
10747     case Intrinsic::x86_avx2_psrli_w:
10748     case Intrinsic::x86_avx2_psrli_d:
10749     case Intrinsic::x86_avx2_psrli_q:
10750       Opcode = X86ISD::VSRLI;
10751       break;
10752     case Intrinsic::x86_sse2_psrai_w:
10753     case Intrinsic::x86_sse2_psrai_d:
10754     case Intrinsic::x86_avx2_psrai_w:
10755     case Intrinsic::x86_avx2_psrai_d:
10756       Opcode = X86ISD::VSRAI;
10757       break;
10758     }
10759     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10760                                Op.getOperand(1), Op.getOperand(2), DAG);
10761   }
10762
10763   case Intrinsic::x86_sse42_pcmpistria128:
10764   case Intrinsic::x86_sse42_pcmpestria128:
10765   case Intrinsic::x86_sse42_pcmpistric128:
10766   case Intrinsic::x86_sse42_pcmpestric128:
10767   case Intrinsic::x86_sse42_pcmpistrio128:
10768   case Intrinsic::x86_sse42_pcmpestrio128:
10769   case Intrinsic::x86_sse42_pcmpistris128:
10770   case Intrinsic::x86_sse42_pcmpestris128:
10771   case Intrinsic::x86_sse42_pcmpistriz128:
10772   case Intrinsic::x86_sse42_pcmpestriz128: {
10773     unsigned Opcode;
10774     unsigned X86CC;
10775     switch (IntNo) {
10776     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10777     case Intrinsic::x86_sse42_pcmpistria128:
10778       Opcode = X86ISD::PCMPISTRI;
10779       X86CC = X86::COND_A;
10780       break;
10781     case Intrinsic::x86_sse42_pcmpestria128:
10782       Opcode = X86ISD::PCMPESTRI;
10783       X86CC = X86::COND_A;
10784       break;
10785     case Intrinsic::x86_sse42_pcmpistric128:
10786       Opcode = X86ISD::PCMPISTRI;
10787       X86CC = X86::COND_B;
10788       break;
10789     case Intrinsic::x86_sse42_pcmpestric128:
10790       Opcode = X86ISD::PCMPESTRI;
10791       X86CC = X86::COND_B;
10792       break;
10793     case Intrinsic::x86_sse42_pcmpistrio128:
10794       Opcode = X86ISD::PCMPISTRI;
10795       X86CC = X86::COND_O;
10796       break;
10797     case Intrinsic::x86_sse42_pcmpestrio128:
10798       Opcode = X86ISD::PCMPESTRI;
10799       X86CC = X86::COND_O;
10800       break;
10801     case Intrinsic::x86_sse42_pcmpistris128:
10802       Opcode = X86ISD::PCMPISTRI;
10803       X86CC = X86::COND_S;
10804       break;
10805     case Intrinsic::x86_sse42_pcmpestris128:
10806       Opcode = X86ISD::PCMPESTRI;
10807       X86CC = X86::COND_S;
10808       break;
10809     case Intrinsic::x86_sse42_pcmpistriz128:
10810       Opcode = X86ISD::PCMPISTRI;
10811       X86CC = X86::COND_E;
10812       break;
10813     case Intrinsic::x86_sse42_pcmpestriz128:
10814       Opcode = X86ISD::PCMPESTRI;
10815       X86CC = X86::COND_E;
10816       break;
10817     }
10818     SmallVector<SDValue, 5> NewOps;
10819     NewOps.append(Op->op_begin()+1, Op->op_end());
10820     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10821     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10822     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10823                                 DAG.getConstant(X86CC, MVT::i8),
10824                                 SDValue(PCMP.getNode(), 1));
10825     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10826   }
10827
10828   case Intrinsic::x86_sse42_pcmpistri128:
10829   case Intrinsic::x86_sse42_pcmpestri128: {
10830     unsigned Opcode;
10831     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10832       Opcode = X86ISD::PCMPISTRI;
10833     else
10834       Opcode = X86ISD::PCMPESTRI;
10835
10836     SmallVector<SDValue, 5> NewOps;
10837     NewOps.append(Op->op_begin()+1, Op->op_end());
10838     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10839     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10840   }
10841   case Intrinsic::x86_fma_vfmadd_ps:
10842   case Intrinsic::x86_fma_vfmadd_pd:
10843   case Intrinsic::x86_fma_vfmsub_ps:
10844   case Intrinsic::x86_fma_vfmsub_pd:
10845   case Intrinsic::x86_fma_vfnmadd_ps:
10846   case Intrinsic::x86_fma_vfnmadd_pd:
10847   case Intrinsic::x86_fma_vfnmsub_ps:
10848   case Intrinsic::x86_fma_vfnmsub_pd:
10849   case Intrinsic::x86_fma_vfmaddsub_ps:
10850   case Intrinsic::x86_fma_vfmaddsub_pd:
10851   case Intrinsic::x86_fma_vfmsubadd_ps:
10852   case Intrinsic::x86_fma_vfmsubadd_pd:
10853   case Intrinsic::x86_fma_vfmadd_ps_256:
10854   case Intrinsic::x86_fma_vfmadd_pd_256:
10855   case Intrinsic::x86_fma_vfmsub_ps_256:
10856   case Intrinsic::x86_fma_vfmsub_pd_256:
10857   case Intrinsic::x86_fma_vfnmadd_ps_256:
10858   case Intrinsic::x86_fma_vfnmadd_pd_256:
10859   case Intrinsic::x86_fma_vfnmsub_ps_256:
10860   case Intrinsic::x86_fma_vfnmsub_pd_256:
10861   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10862   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10863   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10864   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10865     unsigned Opc;
10866     switch (IntNo) {
10867     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10868     case Intrinsic::x86_fma_vfmadd_ps:
10869     case Intrinsic::x86_fma_vfmadd_pd:
10870     case Intrinsic::x86_fma_vfmadd_ps_256:
10871     case Intrinsic::x86_fma_vfmadd_pd_256:
10872       Opc = X86ISD::FMADD;
10873       break;
10874     case Intrinsic::x86_fma_vfmsub_ps:
10875     case Intrinsic::x86_fma_vfmsub_pd:
10876     case Intrinsic::x86_fma_vfmsub_ps_256:
10877     case Intrinsic::x86_fma_vfmsub_pd_256:
10878       Opc = X86ISD::FMSUB;
10879       break;
10880     case Intrinsic::x86_fma_vfnmadd_ps:
10881     case Intrinsic::x86_fma_vfnmadd_pd:
10882     case Intrinsic::x86_fma_vfnmadd_ps_256:
10883     case Intrinsic::x86_fma_vfnmadd_pd_256:
10884       Opc = X86ISD::FNMADD;
10885       break;
10886     case Intrinsic::x86_fma_vfnmsub_ps:
10887     case Intrinsic::x86_fma_vfnmsub_pd:
10888     case Intrinsic::x86_fma_vfnmsub_ps_256:
10889     case Intrinsic::x86_fma_vfnmsub_pd_256:
10890       Opc = X86ISD::FNMSUB;
10891       break;
10892     case Intrinsic::x86_fma_vfmaddsub_ps:
10893     case Intrinsic::x86_fma_vfmaddsub_pd:
10894     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10895     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10896       Opc = X86ISD::FMADDSUB;
10897       break;
10898     case Intrinsic::x86_fma_vfmsubadd_ps:
10899     case Intrinsic::x86_fma_vfmsubadd_pd:
10900     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10901     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10902       Opc = X86ISD::FMSUBADD;
10903       break;
10904     }
10905
10906     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10907                        Op.getOperand(2), Op.getOperand(3));
10908   }
10909   }
10910 }
10911
10912 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10913   DebugLoc dl = Op.getDebugLoc();
10914   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10915   switch (IntNo) {
10916   default: return SDValue();    // Don't custom lower most intrinsics.
10917
10918   // RDRAND intrinsics.
10919   case Intrinsic::x86_rdrand_16:
10920   case Intrinsic::x86_rdrand_32:
10921   case Intrinsic::x86_rdrand_64: {
10922     // Emit the node with the right value type.
10923     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10924     SDValue Result = DAG.getNode(X86ISD::RDRAND, dl, VTs, Op.getOperand(0));
10925
10926     // If the value returned by RDRAND was valid (CF=1), return 1. Otherwise
10927     // return the value from Rand, which is always 0, casted to i32.
10928     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10929                       DAG.getConstant(1, Op->getValueType(1)),
10930                       DAG.getConstant(X86::COND_B, MVT::i32),
10931                       SDValue(Result.getNode(), 1) };
10932     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10933                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10934                                   Ops, 4);
10935
10936     // Return { result, isValid, chain }.
10937     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10938                        SDValue(Result.getNode(), 2));
10939   }
10940   }
10941 }
10942
10943 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
10944                                            SelectionDAG &DAG) const {
10945   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10946   MFI->setReturnAddressIsTaken(true);
10947
10948   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10949   DebugLoc dl = Op.getDebugLoc();
10950   EVT PtrVT = getPointerTy();
10951
10952   if (Depth > 0) {
10953     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
10954     SDValue Offset =
10955       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
10956     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10957                        DAG.getNode(ISD::ADD, dl, PtrVT,
10958                                    FrameAddr, Offset),
10959                        MachinePointerInfo(), false, false, false, 0);
10960   }
10961
10962   // Just load the return address.
10963   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
10964   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
10965                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
10966 }
10967
10968 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
10969   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10970   MFI->setFrameAddressIsTaken(true);
10971
10972   EVT VT = Op.getValueType();
10973   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
10974   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10975   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
10976   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
10977   while (Depth--)
10978     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
10979                             MachinePointerInfo(),
10980                             false, false, false, 0);
10981   return FrameAddr;
10982 }
10983
10984 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
10985                                                      SelectionDAG &DAG) const {
10986   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
10987 }
10988
10989 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
10990   SDValue Chain     = Op.getOperand(0);
10991   SDValue Offset    = Op.getOperand(1);
10992   SDValue Handler   = Op.getOperand(2);
10993   DebugLoc dl       = Op.getDebugLoc();
10994
10995   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
10996                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
10997                                      getPointerTy());
10998   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
10999
11000   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
11001                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11002   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
11003   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11004                        false, false, 0);
11005   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11006
11007   return DAG.getNode(X86ISD::EH_RETURN, dl,
11008                      MVT::Other,
11009                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11010 }
11011
11012 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11013                                                SelectionDAG &DAG) const {
11014   DebugLoc DL = Op.getDebugLoc();
11015   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11016                      DAG.getVTList(MVT::i32, MVT::Other),
11017                      Op.getOperand(0), Op.getOperand(1));
11018 }
11019
11020 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11021                                                 SelectionDAG &DAG) const {
11022   DebugLoc DL = Op.getDebugLoc();
11023   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11024                      Op.getOperand(0), Op.getOperand(1));
11025 }
11026
11027 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11028   return Op.getOperand(0);
11029 }
11030
11031 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11032                                                 SelectionDAG &DAG) const {
11033   SDValue Root = Op.getOperand(0);
11034   SDValue Trmp = Op.getOperand(1); // trampoline
11035   SDValue FPtr = Op.getOperand(2); // nested function
11036   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11037   DebugLoc dl  = Op.getDebugLoc();
11038
11039   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11040   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11041
11042   if (Subtarget->is64Bit()) {
11043     SDValue OutChains[6];
11044
11045     // Large code-model.
11046     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11047     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11048
11049     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11050     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11051
11052     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11053
11054     // Load the pointer to the nested function into R11.
11055     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11056     SDValue Addr = Trmp;
11057     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11058                                 Addr, MachinePointerInfo(TrmpAddr),
11059                                 false, false, 0);
11060
11061     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11062                        DAG.getConstant(2, MVT::i64));
11063     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11064                                 MachinePointerInfo(TrmpAddr, 2),
11065                                 false, false, 2);
11066
11067     // Load the 'nest' parameter value into R10.
11068     // R10 is specified in X86CallingConv.td
11069     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11070     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11071                        DAG.getConstant(10, MVT::i64));
11072     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11073                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11074                                 false, false, 0);
11075
11076     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11077                        DAG.getConstant(12, MVT::i64));
11078     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11079                                 MachinePointerInfo(TrmpAddr, 12),
11080                                 false, false, 2);
11081
11082     // Jump to the nested function.
11083     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11084     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11085                        DAG.getConstant(20, MVT::i64));
11086     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11087                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11088                                 false, false, 0);
11089
11090     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11091     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11092                        DAG.getConstant(22, MVT::i64));
11093     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11094                                 MachinePointerInfo(TrmpAddr, 22),
11095                                 false, false, 0);
11096
11097     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11098   } else {
11099     const Function *Func =
11100       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11101     CallingConv::ID CC = Func->getCallingConv();
11102     unsigned NestReg;
11103
11104     switch (CC) {
11105     default:
11106       llvm_unreachable("Unsupported calling convention");
11107     case CallingConv::C:
11108     case CallingConv::X86_StdCall: {
11109       // Pass 'nest' parameter in ECX.
11110       // Must be kept in sync with X86CallingConv.td
11111       NestReg = X86::ECX;
11112
11113       // Check that ECX wasn't needed by an 'inreg' parameter.
11114       FunctionType *FTy = Func->getFunctionType();
11115       const AttributeSet &Attrs = Func->getAttributes();
11116
11117       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11118         unsigned InRegCount = 0;
11119         unsigned Idx = 1;
11120
11121         for (FunctionType::param_iterator I = FTy->param_begin(),
11122              E = FTy->param_end(); I != E; ++I, ++Idx)
11123           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11124             // FIXME: should only count parameters that are lowered to integers.
11125             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11126
11127         if (InRegCount > 2) {
11128           report_fatal_error("Nest register in use - reduce number of inreg"
11129                              " parameters!");
11130         }
11131       }
11132       break;
11133     }
11134     case CallingConv::X86_FastCall:
11135     case CallingConv::X86_ThisCall:
11136     case CallingConv::Fast:
11137       // Pass 'nest' parameter in EAX.
11138       // Must be kept in sync with X86CallingConv.td
11139       NestReg = X86::EAX;
11140       break;
11141     }
11142
11143     SDValue OutChains[4];
11144     SDValue Addr, Disp;
11145
11146     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11147                        DAG.getConstant(10, MVT::i32));
11148     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11149
11150     // This is storing the opcode for MOV32ri.
11151     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11152     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11153     OutChains[0] = DAG.getStore(Root, dl,
11154                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11155                                 Trmp, MachinePointerInfo(TrmpAddr),
11156                                 false, false, 0);
11157
11158     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11159                        DAG.getConstant(1, MVT::i32));
11160     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11161                                 MachinePointerInfo(TrmpAddr, 1),
11162                                 false, false, 1);
11163
11164     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11165     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11166                        DAG.getConstant(5, MVT::i32));
11167     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11168                                 MachinePointerInfo(TrmpAddr, 5),
11169                                 false, false, 1);
11170
11171     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11172                        DAG.getConstant(6, MVT::i32));
11173     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11174                                 MachinePointerInfo(TrmpAddr, 6),
11175                                 false, false, 1);
11176
11177     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11178   }
11179 }
11180
11181 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11182                                             SelectionDAG &DAG) const {
11183   /*
11184    The rounding mode is in bits 11:10 of FPSR, and has the following
11185    settings:
11186      00 Round to nearest
11187      01 Round to -inf
11188      10 Round to +inf
11189      11 Round to 0
11190
11191   FLT_ROUNDS, on the other hand, expects the following:
11192     -1 Undefined
11193      0 Round to 0
11194      1 Round to nearest
11195      2 Round to +inf
11196      3 Round to -inf
11197
11198   To perform the conversion, we do:
11199     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11200   */
11201
11202   MachineFunction &MF = DAG.getMachineFunction();
11203   const TargetMachine &TM = MF.getTarget();
11204   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11205   unsigned StackAlignment = TFI.getStackAlignment();
11206   EVT VT = Op.getValueType();
11207   DebugLoc DL = Op.getDebugLoc();
11208
11209   // Save FP Control Word to stack slot
11210   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11211   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11212
11213   MachineMemOperand *MMO =
11214    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11215                            MachineMemOperand::MOStore, 2, 2);
11216
11217   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11218   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11219                                           DAG.getVTList(MVT::Other),
11220                                           Ops, 2, MVT::i16, MMO);
11221
11222   // Load FP Control Word from stack slot
11223   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11224                             MachinePointerInfo(), false, false, false, 0);
11225
11226   // Transform as necessary
11227   SDValue CWD1 =
11228     DAG.getNode(ISD::SRL, DL, MVT::i16,
11229                 DAG.getNode(ISD::AND, DL, MVT::i16,
11230                             CWD, DAG.getConstant(0x800, MVT::i16)),
11231                 DAG.getConstant(11, MVT::i8));
11232   SDValue CWD2 =
11233     DAG.getNode(ISD::SRL, DL, MVT::i16,
11234                 DAG.getNode(ISD::AND, DL, MVT::i16,
11235                             CWD, DAG.getConstant(0x400, MVT::i16)),
11236                 DAG.getConstant(9, MVT::i8));
11237
11238   SDValue RetVal =
11239     DAG.getNode(ISD::AND, DL, MVT::i16,
11240                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11241                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11242                             DAG.getConstant(1, MVT::i16)),
11243                 DAG.getConstant(3, MVT::i16));
11244
11245   return DAG.getNode((VT.getSizeInBits() < 16 ?
11246                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11247 }
11248
11249 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11250   EVT VT = Op.getValueType();
11251   EVT OpVT = VT;
11252   unsigned NumBits = VT.getSizeInBits();
11253   DebugLoc dl = Op.getDebugLoc();
11254
11255   Op = Op.getOperand(0);
11256   if (VT == MVT::i8) {
11257     // Zero extend to i32 since there is not an i8 bsr.
11258     OpVT = MVT::i32;
11259     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11260   }
11261
11262   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11263   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11264   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11265
11266   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11267   SDValue Ops[] = {
11268     Op,
11269     DAG.getConstant(NumBits+NumBits-1, OpVT),
11270     DAG.getConstant(X86::COND_E, MVT::i8),
11271     Op.getValue(1)
11272   };
11273   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11274
11275   // Finally xor with NumBits-1.
11276   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11277
11278   if (VT == MVT::i8)
11279     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11280   return Op;
11281 }
11282
11283 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11284   EVT VT = Op.getValueType();
11285   EVT OpVT = VT;
11286   unsigned NumBits = VT.getSizeInBits();
11287   DebugLoc dl = Op.getDebugLoc();
11288
11289   Op = Op.getOperand(0);
11290   if (VT == MVT::i8) {
11291     // Zero extend to i32 since there is not an i8 bsr.
11292     OpVT = MVT::i32;
11293     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11294   }
11295
11296   // Issue a bsr (scan bits in reverse).
11297   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11298   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11299
11300   // And xor with NumBits-1.
11301   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11302
11303   if (VT == MVT::i8)
11304     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11305   return Op;
11306 }
11307
11308 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11309   EVT VT = Op.getValueType();
11310   unsigned NumBits = VT.getSizeInBits();
11311   DebugLoc dl = Op.getDebugLoc();
11312   Op = Op.getOperand(0);
11313
11314   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11315   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11316   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11317
11318   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11319   SDValue Ops[] = {
11320     Op,
11321     DAG.getConstant(NumBits, VT),
11322     DAG.getConstant(X86::COND_E, MVT::i8),
11323     Op.getValue(1)
11324   };
11325   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11326 }
11327
11328 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11329 // ones, and then concatenate the result back.
11330 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11331   EVT VT = Op.getValueType();
11332
11333   assert(VT.is256BitVector() && VT.isInteger() &&
11334          "Unsupported value type for operation");
11335
11336   unsigned NumElems = VT.getVectorNumElements();
11337   DebugLoc dl = Op.getDebugLoc();
11338
11339   // Extract the LHS vectors
11340   SDValue LHS = Op.getOperand(0);
11341   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11342   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11343
11344   // Extract the RHS vectors
11345   SDValue RHS = Op.getOperand(1);
11346   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11347   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11348
11349   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11350   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11351
11352   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11353                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11354                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11355 }
11356
11357 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11358   assert(Op.getValueType().is256BitVector() &&
11359          Op.getValueType().isInteger() &&
11360          "Only handle AVX 256-bit vector integer operation");
11361   return Lower256IntArith(Op, DAG);
11362 }
11363
11364 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11365   assert(Op.getValueType().is256BitVector() &&
11366          Op.getValueType().isInteger() &&
11367          "Only handle AVX 256-bit vector integer operation");
11368   return Lower256IntArith(Op, DAG);
11369 }
11370
11371 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11372                         SelectionDAG &DAG) {
11373   DebugLoc dl = Op.getDebugLoc();
11374   EVT VT = Op.getValueType();
11375
11376   // Decompose 256-bit ops into smaller 128-bit ops.
11377   if (VT.is256BitVector() && !Subtarget->hasInt256())
11378     return Lower256IntArith(Op, DAG);
11379
11380   SDValue A = Op.getOperand(0);
11381   SDValue B = Op.getOperand(1);
11382
11383   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11384   if (VT == MVT::v4i32) {
11385     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11386            "Should not custom lower when pmuldq is available!");
11387
11388     // Extract the odd parts.
11389     const int UnpackMask[] = { 1, -1, 3, -1 };
11390     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11391     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11392
11393     // Multiply the even parts.
11394     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11395     // Now multiply odd parts.
11396     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11397
11398     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11399     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11400
11401     // Merge the two vectors back together with a shuffle. This expands into 2
11402     // shuffles.
11403     const int ShufMask[] = { 0, 4, 2, 6 };
11404     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11405   }
11406
11407   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11408          "Only know how to lower V2I64/V4I64 multiply");
11409
11410   //  Ahi = psrlqi(a, 32);
11411   //  Bhi = psrlqi(b, 32);
11412   //
11413   //  AloBlo = pmuludq(a, b);
11414   //  AloBhi = pmuludq(a, Bhi);
11415   //  AhiBlo = pmuludq(Ahi, b);
11416
11417   //  AloBhi = psllqi(AloBhi, 32);
11418   //  AhiBlo = psllqi(AhiBlo, 32);
11419   //  return AloBlo + AloBhi + AhiBlo;
11420
11421   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11422
11423   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11424   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11425
11426   // Bit cast to 32-bit vectors for MULUDQ
11427   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11428   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11429   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11430   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11431   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11432
11433   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11434   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11435   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11436
11437   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11438   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11439
11440   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11441   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11442 }
11443
11444 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11445   EVT VT = Op.getValueType();
11446   EVT EltTy = VT.getVectorElementType();
11447   unsigned NumElts = VT.getVectorNumElements();
11448   SDValue N0 = Op.getOperand(0);
11449   DebugLoc dl = Op.getDebugLoc();
11450
11451   // Lower sdiv X, pow2-const.
11452   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11453   if (!C)
11454     return SDValue();
11455
11456   APInt SplatValue, SplatUndef;
11457   unsigned MinSplatBits;
11458   bool HasAnyUndefs;
11459   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11460     return SDValue();
11461
11462   if ((SplatValue != 0) &&
11463       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11464     unsigned lg2 = SplatValue.countTrailingZeros();
11465     // Splat the sign bit.
11466     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11467     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11468     // Add (N0 < 0) ? abs2 - 1 : 0;
11469     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11470     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11471     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11472     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11473     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11474
11475     // If we're dividing by a positive value, we're done.  Otherwise, we must
11476     // negate the result.
11477     if (SplatValue.isNonNegative())
11478       return SRA;
11479
11480     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11481     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11482     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11483   }
11484   return SDValue();
11485 }
11486
11487 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11488
11489   EVT VT = Op.getValueType();
11490   DebugLoc dl = Op.getDebugLoc();
11491   SDValue R = Op.getOperand(0);
11492   SDValue Amt = Op.getOperand(1);
11493
11494   if (!Subtarget->hasSSE2())
11495     return SDValue();
11496
11497   // Optimize shl/srl/sra with constant shift amount.
11498   if (isSplatVector(Amt.getNode())) {
11499     SDValue SclrAmt = Amt->getOperand(0);
11500     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11501       uint64_t ShiftAmt = C->getZExtValue();
11502
11503       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11504           (Subtarget->hasInt256() &&
11505            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11506         if (Op.getOpcode() == ISD::SHL)
11507           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11508                              DAG.getConstant(ShiftAmt, MVT::i32));
11509         if (Op.getOpcode() == ISD::SRL)
11510           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11511                              DAG.getConstant(ShiftAmt, MVT::i32));
11512         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11513           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11514                              DAG.getConstant(ShiftAmt, MVT::i32));
11515       }
11516
11517       if (VT == MVT::v16i8) {
11518         if (Op.getOpcode() == ISD::SHL) {
11519           // Make a large shift.
11520           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11521                                     DAG.getConstant(ShiftAmt, MVT::i32));
11522           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11523           // Zero out the rightmost bits.
11524           SmallVector<SDValue, 16> V(16,
11525                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11526                                                      MVT::i8));
11527           return DAG.getNode(ISD::AND, dl, VT, SHL,
11528                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11529         }
11530         if (Op.getOpcode() == ISD::SRL) {
11531           // Make a large shift.
11532           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11533                                     DAG.getConstant(ShiftAmt, MVT::i32));
11534           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11535           // Zero out the leftmost bits.
11536           SmallVector<SDValue, 16> V(16,
11537                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11538                                                      MVT::i8));
11539           return DAG.getNode(ISD::AND, dl, VT, SRL,
11540                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11541         }
11542         if (Op.getOpcode() == ISD::SRA) {
11543           if (ShiftAmt == 7) {
11544             // R s>> 7  ===  R s< 0
11545             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11546             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11547           }
11548
11549           // R s>> a === ((R u>> a) ^ m) - m
11550           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11551           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11552                                                          MVT::i8));
11553           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11554           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11555           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11556           return Res;
11557         }
11558         llvm_unreachable("Unknown shift opcode.");
11559       }
11560
11561       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11562         if (Op.getOpcode() == ISD::SHL) {
11563           // Make a large shift.
11564           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11565                                     DAG.getConstant(ShiftAmt, MVT::i32));
11566           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11567           // Zero out the rightmost bits.
11568           SmallVector<SDValue, 32> V(32,
11569                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11570                                                      MVT::i8));
11571           return DAG.getNode(ISD::AND, dl, VT, SHL,
11572                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11573         }
11574         if (Op.getOpcode() == ISD::SRL) {
11575           // Make a large shift.
11576           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11577                                     DAG.getConstant(ShiftAmt, MVT::i32));
11578           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11579           // Zero out the leftmost bits.
11580           SmallVector<SDValue, 32> V(32,
11581                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11582                                                      MVT::i8));
11583           return DAG.getNode(ISD::AND, dl, VT, SRL,
11584                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11585         }
11586         if (Op.getOpcode() == ISD::SRA) {
11587           if (ShiftAmt == 7) {
11588             // R s>> 7  ===  R s< 0
11589             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11590             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11591           }
11592
11593           // R s>> a === ((R u>> a) ^ m) - m
11594           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11595           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11596                                                          MVT::i8));
11597           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11598           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11599           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11600           return Res;
11601         }
11602         llvm_unreachable("Unknown shift opcode.");
11603       }
11604     }
11605   }
11606
11607   // Lower SHL with variable shift amount.
11608   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11609     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11610
11611     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11612     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11613     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11614     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11615   }
11616   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11617     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11618
11619     // a = a << 5;
11620     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11621     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11622
11623     // Turn 'a' into a mask suitable for VSELECT
11624     SDValue VSelM = DAG.getConstant(0x80, VT);
11625     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11626     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11627
11628     SDValue CM1 = DAG.getConstant(0x0f, VT);
11629     SDValue CM2 = DAG.getConstant(0x3f, VT);
11630
11631     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11632     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11633     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11634                             DAG.getConstant(4, MVT::i32), DAG);
11635     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11636     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11637
11638     // a += a
11639     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11640     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11641     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11642
11643     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11644     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11645     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11646                             DAG.getConstant(2, MVT::i32), DAG);
11647     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11648     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11649
11650     // a += a
11651     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11652     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11653     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11654
11655     // return VSELECT(r, r+r, a);
11656     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11657                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11658     return R;
11659   }
11660
11661   // Decompose 256-bit shifts into smaller 128-bit shifts.
11662   if (VT.is256BitVector()) {
11663     unsigned NumElems = VT.getVectorNumElements();
11664     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11665     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11666
11667     // Extract the two vectors
11668     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11669     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11670
11671     // Recreate the shift amount vectors
11672     SDValue Amt1, Amt2;
11673     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11674       // Constant shift amount
11675       SmallVector<SDValue, 4> Amt1Csts;
11676       SmallVector<SDValue, 4> Amt2Csts;
11677       for (unsigned i = 0; i != NumElems/2; ++i)
11678         Amt1Csts.push_back(Amt->getOperand(i));
11679       for (unsigned i = NumElems/2; i != NumElems; ++i)
11680         Amt2Csts.push_back(Amt->getOperand(i));
11681
11682       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11683                                  &Amt1Csts[0], NumElems/2);
11684       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11685                                  &Amt2Csts[0], NumElems/2);
11686     } else {
11687       // Variable shift amount
11688       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11689       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11690     }
11691
11692     // Issue new vector shifts for the smaller types
11693     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11694     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11695
11696     // Concatenate the result back
11697     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11698   }
11699
11700   return SDValue();
11701 }
11702
11703 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11704   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11705   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11706   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11707   // has only one use.
11708   SDNode *N = Op.getNode();
11709   SDValue LHS = N->getOperand(0);
11710   SDValue RHS = N->getOperand(1);
11711   unsigned BaseOp = 0;
11712   unsigned Cond = 0;
11713   DebugLoc DL = Op.getDebugLoc();
11714   switch (Op.getOpcode()) {
11715   default: llvm_unreachable("Unknown ovf instruction!");
11716   case ISD::SADDO:
11717     // A subtract of one will be selected as a INC. Note that INC doesn't
11718     // set CF, so we can't do this for UADDO.
11719     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11720       if (C->isOne()) {
11721         BaseOp = X86ISD::INC;
11722         Cond = X86::COND_O;
11723         break;
11724       }
11725     BaseOp = X86ISD::ADD;
11726     Cond = X86::COND_O;
11727     break;
11728   case ISD::UADDO:
11729     BaseOp = X86ISD::ADD;
11730     Cond = X86::COND_B;
11731     break;
11732   case ISD::SSUBO:
11733     // A subtract of one will be selected as a DEC. Note that DEC doesn't
11734     // set CF, so we can't do this for USUBO.
11735     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11736       if (C->isOne()) {
11737         BaseOp = X86ISD::DEC;
11738         Cond = X86::COND_O;
11739         break;
11740       }
11741     BaseOp = X86ISD::SUB;
11742     Cond = X86::COND_O;
11743     break;
11744   case ISD::USUBO:
11745     BaseOp = X86ISD::SUB;
11746     Cond = X86::COND_B;
11747     break;
11748   case ISD::SMULO:
11749     BaseOp = X86ISD::SMUL;
11750     Cond = X86::COND_O;
11751     break;
11752   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
11753     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
11754                                  MVT::i32);
11755     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
11756
11757     SDValue SetCC =
11758       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
11759                   DAG.getConstant(X86::COND_O, MVT::i32),
11760                   SDValue(Sum.getNode(), 2));
11761
11762     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11763   }
11764   }
11765
11766   // Also sets EFLAGS.
11767   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
11768   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
11769
11770   SDValue SetCC =
11771     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
11772                 DAG.getConstant(Cond, MVT::i32),
11773                 SDValue(Sum.getNode(), 1));
11774
11775   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
11776 }
11777
11778 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
11779                                                   SelectionDAG &DAG) const {
11780   DebugLoc dl = Op.getDebugLoc();
11781   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
11782   EVT VT = Op.getValueType();
11783
11784   if (!Subtarget->hasSSE2() || !VT.isVector())
11785     return SDValue();
11786
11787   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
11788                       ExtraVT.getScalarType().getSizeInBits();
11789   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
11790
11791   switch (VT.getSimpleVT().SimpleTy) {
11792     default: return SDValue();
11793     case MVT::v8i32:
11794     case MVT::v16i16:
11795       if (!Subtarget->hasFp256())
11796         return SDValue();
11797       if (!Subtarget->hasInt256()) {
11798         // needs to be split
11799         unsigned NumElems = VT.getVectorNumElements();
11800
11801         // Extract the LHS vectors
11802         SDValue LHS = Op.getOperand(0);
11803         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11804         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11805
11806         MVT EltVT = VT.getVectorElementType().getSimpleVT();
11807         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11808
11809         EVT ExtraEltVT = ExtraVT.getVectorElementType();
11810         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
11811         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
11812                                    ExtraNumElems/2);
11813         SDValue Extra = DAG.getValueType(ExtraVT);
11814
11815         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
11816         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
11817
11818         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
11819       }
11820       // fall through
11821     case MVT::v4i32:
11822     case MVT::v8i16: {
11823       SDValue Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT,
11824                                          Op.getOperand(0), ShAmt, DAG);
11825       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
11826     }
11827   }
11828 }
11829
11830 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
11831                               SelectionDAG &DAG) {
11832   DebugLoc dl = Op.getDebugLoc();
11833
11834   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
11835   // There isn't any reason to disable it if the target processor supports it.
11836   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
11837     SDValue Chain = Op.getOperand(0);
11838     SDValue Zero = DAG.getConstant(0, MVT::i32);
11839     SDValue Ops[] = {
11840       DAG.getRegister(X86::ESP, MVT::i32), // Base
11841       DAG.getTargetConstant(1, MVT::i8),   // Scale
11842       DAG.getRegister(0, MVT::i32),        // Index
11843       DAG.getTargetConstant(0, MVT::i32),  // Disp
11844       DAG.getRegister(0, MVT::i32),        // Segment.
11845       Zero,
11846       Chain
11847     };
11848     SDNode *Res =
11849       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11850                           array_lengthof(Ops));
11851     return SDValue(Res, 0);
11852   }
11853
11854   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
11855   if (!isDev)
11856     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11857
11858   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11859   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11860   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
11861   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
11862
11863   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
11864   if (!Op1 && !Op2 && !Op3 && Op4)
11865     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
11866
11867   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
11868   if (Op1 && !Op2 && !Op3 && !Op4)
11869     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
11870
11871   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
11872   //           (MFENCE)>;
11873   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11874 }
11875
11876 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
11877                                  SelectionDAG &DAG) {
11878   DebugLoc dl = Op.getDebugLoc();
11879   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
11880     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
11881   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
11882     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
11883
11884   // The only fence that needs an instruction is a sequentially-consistent
11885   // cross-thread fence.
11886   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
11887     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
11888     // no-sse2). There isn't any reason to disable it if the target processor
11889     // supports it.
11890     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
11891       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
11892
11893     SDValue Chain = Op.getOperand(0);
11894     SDValue Zero = DAG.getConstant(0, MVT::i32);
11895     SDValue Ops[] = {
11896       DAG.getRegister(X86::ESP, MVT::i32), // Base
11897       DAG.getTargetConstant(1, MVT::i8),   // Scale
11898       DAG.getRegister(0, MVT::i32),        // Index
11899       DAG.getTargetConstant(0, MVT::i32),  // Disp
11900       DAG.getRegister(0, MVT::i32),        // Segment.
11901       Zero,
11902       Chain
11903     };
11904     SDNode *Res =
11905       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
11906                          array_lengthof(Ops));
11907     return SDValue(Res, 0);
11908   }
11909
11910   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
11911   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
11912 }
11913
11914 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
11915                              SelectionDAG &DAG) {
11916   EVT T = Op.getValueType();
11917   DebugLoc DL = Op.getDebugLoc();
11918   unsigned Reg = 0;
11919   unsigned size = 0;
11920   switch(T.getSimpleVT().SimpleTy) {
11921   default: llvm_unreachable("Invalid value type!");
11922   case MVT::i8:  Reg = X86::AL;  size = 1; break;
11923   case MVT::i16: Reg = X86::AX;  size = 2; break;
11924   case MVT::i32: Reg = X86::EAX; size = 4; break;
11925   case MVT::i64:
11926     assert(Subtarget->is64Bit() && "Node not type legal!");
11927     Reg = X86::RAX; size = 8;
11928     break;
11929   }
11930   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
11931                                     Op.getOperand(2), SDValue());
11932   SDValue Ops[] = { cpIn.getValue(0),
11933                     Op.getOperand(1),
11934                     Op.getOperand(3),
11935                     DAG.getTargetConstant(size, MVT::i8),
11936                     cpIn.getValue(1) };
11937   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11938   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
11939   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
11940                                            Ops, 5, T, MMO);
11941   SDValue cpOut =
11942     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
11943   return cpOut;
11944 }
11945
11946 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
11947                                      SelectionDAG &DAG) {
11948   assert(Subtarget->is64Bit() && "Result not type legalized?");
11949   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11950   SDValue TheChain = Op.getOperand(0);
11951   DebugLoc dl = Op.getDebugLoc();
11952   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11953   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
11954   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
11955                                    rax.getValue(2));
11956   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
11957                             DAG.getConstant(32, MVT::i8));
11958   SDValue Ops[] = {
11959     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
11960     rdx.getValue(1)
11961   };
11962   return DAG.getMergeValues(Ops, 2, dl);
11963 }
11964
11965 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
11966   EVT SrcVT = Op.getOperand(0).getValueType();
11967   EVT DstVT = Op.getValueType();
11968   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
11969          Subtarget->hasMMX() && "Unexpected custom BITCAST");
11970   assert((DstVT == MVT::i64 ||
11971           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
11972          "Unexpected custom BITCAST");
11973   // i64 <=> MMX conversions are Legal.
11974   if (SrcVT==MVT::i64 && DstVT.isVector())
11975     return Op;
11976   if (DstVT==MVT::i64 && SrcVT.isVector())
11977     return Op;
11978   // MMX <=> MMX conversions are Legal.
11979   if (SrcVT.isVector() && DstVT.isVector())
11980     return Op;
11981   // All other conversions need to be expanded.
11982   return SDValue();
11983 }
11984
11985 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
11986   SDNode *Node = Op.getNode();
11987   DebugLoc dl = Node->getDebugLoc();
11988   EVT T = Node->getValueType(0);
11989   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
11990                               DAG.getConstant(0, T), Node->getOperand(2));
11991   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
11992                        cast<AtomicSDNode>(Node)->getMemoryVT(),
11993                        Node->getOperand(0),
11994                        Node->getOperand(1), negOp,
11995                        cast<AtomicSDNode>(Node)->getSrcValue(),
11996                        cast<AtomicSDNode>(Node)->getAlignment(),
11997                        cast<AtomicSDNode>(Node)->getOrdering(),
11998                        cast<AtomicSDNode>(Node)->getSynchScope());
11999 }
12000
12001 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12002   SDNode *Node = Op.getNode();
12003   DebugLoc dl = Node->getDebugLoc();
12004   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12005
12006   // Convert seq_cst store -> xchg
12007   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12008   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12009   //        (The only way to get a 16-byte store is cmpxchg16b)
12010   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12011   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12012       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12013     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12014                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12015                                  Node->getOperand(0),
12016                                  Node->getOperand(1), Node->getOperand(2),
12017                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12018                                  cast<AtomicSDNode>(Node)->getOrdering(),
12019                                  cast<AtomicSDNode>(Node)->getSynchScope());
12020     return Swap.getValue(1);
12021   }
12022   // Other atomic stores have a simple pattern.
12023   return Op;
12024 }
12025
12026 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12027   EVT VT = Op.getNode()->getValueType(0);
12028
12029   // Let legalize expand this if it isn't a legal type yet.
12030   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12031     return SDValue();
12032
12033   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12034
12035   unsigned Opc;
12036   bool ExtraOp = false;
12037   switch (Op.getOpcode()) {
12038   default: llvm_unreachable("Invalid code");
12039   case ISD::ADDC: Opc = X86ISD::ADD; break;
12040   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12041   case ISD::SUBC: Opc = X86ISD::SUB; break;
12042   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12043   }
12044
12045   if (!ExtraOp)
12046     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12047                        Op.getOperand(1));
12048   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12049                      Op.getOperand(1), Op.getOperand(2));
12050 }
12051
12052 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12053   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12054
12055   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12056   // which returns the values in two XMM registers.
12057   DebugLoc dl = Op.getDebugLoc();
12058   SDValue Arg = Op.getOperand(0);
12059   EVT ArgVT = Arg.getValueType();
12060   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12061
12062   ArgListTy Args;
12063   ArgListEntry Entry;
12064
12065   Entry.Node = Arg;
12066   Entry.Ty = ArgTy;
12067   Entry.isSExt = false;
12068   Entry.isZExt = false;
12069   Args.push_back(Entry);
12070
12071   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12072   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12073   // the results are returned via SRet in memory.
12074   const char *LibcallName = (ArgVT == MVT::f64)
12075     ? "__sincos_stret" : "__sincosf_stret";
12076   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12077
12078   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
12079   TargetLowering::
12080     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12081                          false, false, false, false, 0,
12082                          CallingConv::C, /*isTaillCall=*/false,
12083                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12084                          Callee, Args, DAG, dl);
12085   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12086   return CallResult.first;
12087 }
12088
12089 /// LowerOperation - Provide custom lowering hooks for some operations.
12090 ///
12091 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12092   switch (Op.getOpcode()) {
12093   default: llvm_unreachable("Should not custom lower this!");
12094   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12095   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12096   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12097   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12098   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12099   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12100   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12101   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12102   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12103   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12104   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12105   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12106   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12107   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12108   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12109   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12110   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12111   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12112   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12113   case ISD::SHL_PARTS:
12114   case ISD::SRA_PARTS:
12115   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12116   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12117   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12118   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12119   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12120   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12121   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12122   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12123   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12124   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12125   case ISD::FABS:               return LowerFABS(Op, DAG);
12126   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12127   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12128   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12129   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12130   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12131   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12132   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12133   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12134   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12135   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12136   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12137   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12138   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12139   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12140   case ISD::FRAME_TO_ARGS_OFFSET:
12141                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12142   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12143   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12144   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12145   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12146   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12147   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12148   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12149   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12150   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12151   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12152   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12153   case ISD::SRA:
12154   case ISD::SRL:
12155   case ISD::SHL:                return LowerShift(Op, DAG);
12156   case ISD::SADDO:
12157   case ISD::UADDO:
12158   case ISD::SSUBO:
12159   case ISD::USUBO:
12160   case ISD::SMULO:
12161   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12162   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12163   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12164   case ISD::ADDC:
12165   case ISD::ADDE:
12166   case ISD::SUBC:
12167   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12168   case ISD::ADD:                return LowerADD(Op, DAG);
12169   case ISD::SUB:                return LowerSUB(Op, DAG);
12170   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12171   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12172   }
12173 }
12174
12175 static void ReplaceATOMIC_LOAD(SDNode *Node,
12176                                   SmallVectorImpl<SDValue> &Results,
12177                                   SelectionDAG &DAG) {
12178   DebugLoc dl = Node->getDebugLoc();
12179   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12180
12181   // Convert wide load -> cmpxchg8b/cmpxchg16b
12182   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12183   //        (The only way to get a 16-byte load is cmpxchg16b)
12184   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12185   SDValue Zero = DAG.getConstant(0, VT);
12186   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12187                                Node->getOperand(0),
12188                                Node->getOperand(1), Zero, Zero,
12189                                cast<AtomicSDNode>(Node)->getMemOperand(),
12190                                cast<AtomicSDNode>(Node)->getOrdering(),
12191                                cast<AtomicSDNode>(Node)->getSynchScope());
12192   Results.push_back(Swap.getValue(0));
12193   Results.push_back(Swap.getValue(1));
12194 }
12195
12196 static void
12197 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12198                         SelectionDAG &DAG, unsigned NewOp) {
12199   DebugLoc dl = Node->getDebugLoc();
12200   assert (Node->getValueType(0) == MVT::i64 &&
12201           "Only know how to expand i64 atomics");
12202
12203   SDValue Chain = Node->getOperand(0);
12204   SDValue In1 = Node->getOperand(1);
12205   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12206                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12207   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12208                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12209   SDValue Ops[] = { Chain, In1, In2L, In2H };
12210   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12211   SDValue Result =
12212     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12213                             cast<MemSDNode>(Node)->getMemOperand());
12214   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12215   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12216   Results.push_back(Result.getValue(2));
12217 }
12218
12219 /// ReplaceNodeResults - Replace a node with an illegal result type
12220 /// with a new node built out of custom code.
12221 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12222                                            SmallVectorImpl<SDValue>&Results,
12223                                            SelectionDAG &DAG) const {
12224   DebugLoc dl = N->getDebugLoc();
12225   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12226   switch (N->getOpcode()) {
12227   default:
12228     llvm_unreachable("Do not know how to custom type legalize this operation!");
12229   case ISD::SIGN_EXTEND_INREG:
12230   case ISD::ADDC:
12231   case ISD::ADDE:
12232   case ISD::SUBC:
12233   case ISD::SUBE:
12234     // We don't want to expand or promote these.
12235     return;
12236   case ISD::FP_TO_SINT:
12237   case ISD::FP_TO_UINT: {
12238     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12239
12240     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12241       return;
12242
12243     std::pair<SDValue,SDValue> Vals =
12244         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12245     SDValue FIST = Vals.first, StackSlot = Vals.second;
12246     if (FIST.getNode() != 0) {
12247       EVT VT = N->getValueType(0);
12248       // Return a load from the stack slot.
12249       if (StackSlot.getNode() != 0)
12250         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12251                                       MachinePointerInfo(),
12252                                       false, false, false, 0));
12253       else
12254         Results.push_back(FIST);
12255     }
12256     return;
12257   }
12258   case ISD::UINT_TO_FP: {
12259     if (N->getOperand(0).getValueType() != MVT::v2i32 &&
12260         N->getValueType(0) != MVT::v2f32)
12261       return;
12262     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12263                                  N->getOperand(0));
12264     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12265                                      MVT::f64);
12266     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12267     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12268                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12269     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12270     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12271     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12272     return;
12273   }
12274   case ISD::FP_ROUND: {
12275     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12276         return;
12277     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12278     Results.push_back(V);
12279     return;
12280   }
12281   case ISD::READCYCLECOUNTER: {
12282     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12283     SDValue TheChain = N->getOperand(0);
12284     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12285     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12286                                      rd.getValue(1));
12287     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12288                                      eax.getValue(2));
12289     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12290     SDValue Ops[] = { eax, edx };
12291     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12292     Results.push_back(edx.getValue(1));
12293     return;
12294   }
12295   case ISD::ATOMIC_CMP_SWAP: {
12296     EVT T = N->getValueType(0);
12297     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12298     bool Regs64bit = T == MVT::i128;
12299     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12300     SDValue cpInL, cpInH;
12301     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12302                         DAG.getConstant(0, HalfT));
12303     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12304                         DAG.getConstant(1, HalfT));
12305     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12306                              Regs64bit ? X86::RAX : X86::EAX,
12307                              cpInL, SDValue());
12308     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12309                              Regs64bit ? X86::RDX : X86::EDX,
12310                              cpInH, cpInL.getValue(1));
12311     SDValue swapInL, swapInH;
12312     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12313                           DAG.getConstant(0, HalfT));
12314     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12315                           DAG.getConstant(1, HalfT));
12316     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12317                                Regs64bit ? X86::RBX : X86::EBX,
12318                                swapInL, cpInH.getValue(1));
12319     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12320                                Regs64bit ? X86::RCX : X86::ECX,
12321                                swapInH, swapInL.getValue(1));
12322     SDValue Ops[] = { swapInH.getValue(0),
12323                       N->getOperand(1),
12324                       swapInH.getValue(1) };
12325     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12326     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12327     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12328                                   X86ISD::LCMPXCHG8_DAG;
12329     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12330                                              Ops, 3, T, MMO);
12331     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12332                                         Regs64bit ? X86::RAX : X86::EAX,
12333                                         HalfT, Result.getValue(1));
12334     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12335                                         Regs64bit ? X86::RDX : X86::EDX,
12336                                         HalfT, cpOutL.getValue(2));
12337     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12338     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12339     Results.push_back(cpOutH.getValue(1));
12340     return;
12341   }
12342   case ISD::ATOMIC_LOAD_ADD:
12343   case ISD::ATOMIC_LOAD_AND:
12344   case ISD::ATOMIC_LOAD_NAND:
12345   case ISD::ATOMIC_LOAD_OR:
12346   case ISD::ATOMIC_LOAD_SUB:
12347   case ISD::ATOMIC_LOAD_XOR:
12348   case ISD::ATOMIC_LOAD_MAX:
12349   case ISD::ATOMIC_LOAD_MIN:
12350   case ISD::ATOMIC_LOAD_UMAX:
12351   case ISD::ATOMIC_LOAD_UMIN:
12352   case ISD::ATOMIC_SWAP: {
12353     unsigned Opc;
12354     switch (N->getOpcode()) {
12355     default: llvm_unreachable("Unexpected opcode");
12356     case ISD::ATOMIC_LOAD_ADD:
12357       Opc = X86ISD::ATOMADD64_DAG;
12358       break;
12359     case ISD::ATOMIC_LOAD_AND:
12360       Opc = X86ISD::ATOMAND64_DAG;
12361       break;
12362     case ISD::ATOMIC_LOAD_NAND:
12363       Opc = X86ISD::ATOMNAND64_DAG;
12364       break;
12365     case ISD::ATOMIC_LOAD_OR:
12366       Opc = X86ISD::ATOMOR64_DAG;
12367       break;
12368     case ISD::ATOMIC_LOAD_SUB:
12369       Opc = X86ISD::ATOMSUB64_DAG;
12370       break;
12371     case ISD::ATOMIC_LOAD_XOR:
12372       Opc = X86ISD::ATOMXOR64_DAG;
12373       break;
12374     case ISD::ATOMIC_LOAD_MAX:
12375       Opc = X86ISD::ATOMMAX64_DAG;
12376       break;
12377     case ISD::ATOMIC_LOAD_MIN:
12378       Opc = X86ISD::ATOMMIN64_DAG;
12379       break;
12380     case ISD::ATOMIC_LOAD_UMAX:
12381       Opc = X86ISD::ATOMUMAX64_DAG;
12382       break;
12383     case ISD::ATOMIC_LOAD_UMIN:
12384       Opc = X86ISD::ATOMUMIN64_DAG;
12385       break;
12386     case ISD::ATOMIC_SWAP:
12387       Opc = X86ISD::ATOMSWAP64_DAG;
12388       break;
12389     }
12390     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12391     return;
12392   }
12393   case ISD::ATOMIC_LOAD:
12394     ReplaceATOMIC_LOAD(N, Results, DAG);
12395   }
12396 }
12397
12398 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12399   switch (Opcode) {
12400   default: return NULL;
12401   case X86ISD::BSF:                return "X86ISD::BSF";
12402   case X86ISD::BSR:                return "X86ISD::BSR";
12403   case X86ISD::SHLD:               return "X86ISD::SHLD";
12404   case X86ISD::SHRD:               return "X86ISD::SHRD";
12405   case X86ISD::FAND:               return "X86ISD::FAND";
12406   case X86ISD::FOR:                return "X86ISD::FOR";
12407   case X86ISD::FXOR:               return "X86ISD::FXOR";
12408   case X86ISD::FSRL:               return "X86ISD::FSRL";
12409   case X86ISD::FILD:               return "X86ISD::FILD";
12410   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12411   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12412   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12413   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12414   case X86ISD::FLD:                return "X86ISD::FLD";
12415   case X86ISD::FST:                return "X86ISD::FST";
12416   case X86ISD::CALL:               return "X86ISD::CALL";
12417   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12418   case X86ISD::BT:                 return "X86ISD::BT";
12419   case X86ISD::CMP:                return "X86ISD::CMP";
12420   case X86ISD::COMI:               return "X86ISD::COMI";
12421   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12422   case X86ISD::SETCC:              return "X86ISD::SETCC";
12423   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12424   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12425   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12426   case X86ISD::CMOV:               return "X86ISD::CMOV";
12427   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12428   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12429   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12430   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12431   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12432   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12433   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12434   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12435   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12436   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12437   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12438   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12439   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12440   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12441   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12442   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12443   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12444   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12445   case X86ISD::HADD:               return "X86ISD::HADD";
12446   case X86ISD::HSUB:               return "X86ISD::HSUB";
12447   case X86ISD::FHADD:              return "X86ISD::FHADD";
12448   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12449   case X86ISD::UMAX:               return "X86ISD::UMAX";
12450   case X86ISD::UMIN:               return "X86ISD::UMIN";
12451   case X86ISD::SMAX:               return "X86ISD::SMAX";
12452   case X86ISD::SMIN:               return "X86ISD::SMIN";
12453   case X86ISD::FMAX:               return "X86ISD::FMAX";
12454   case X86ISD::FMIN:               return "X86ISD::FMIN";
12455   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12456   case X86ISD::FMINC:              return "X86ISD::FMINC";
12457   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12458   case X86ISD::FRCP:               return "X86ISD::FRCP";
12459   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12460   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12461   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12462   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12463   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12464   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12465   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12466   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12467   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12468   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12469   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12470   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12471   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12472   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12473   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12474   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12475   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12476   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12477   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12478   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12479   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12480   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12481   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12482   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12483   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12484   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12485   case X86ISD::VSHL:               return "X86ISD::VSHL";
12486   case X86ISD::VSRL:               return "X86ISD::VSRL";
12487   case X86ISD::VSRA:               return "X86ISD::VSRA";
12488   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12489   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12490   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12491   case X86ISD::CMPP:               return "X86ISD::CMPP";
12492   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12493   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12494   case X86ISD::ADD:                return "X86ISD::ADD";
12495   case X86ISD::SUB:                return "X86ISD::SUB";
12496   case X86ISD::ADC:                return "X86ISD::ADC";
12497   case X86ISD::SBB:                return "X86ISD::SBB";
12498   case X86ISD::SMUL:               return "X86ISD::SMUL";
12499   case X86ISD::UMUL:               return "X86ISD::UMUL";
12500   case X86ISD::INC:                return "X86ISD::INC";
12501   case X86ISD::DEC:                return "X86ISD::DEC";
12502   case X86ISD::OR:                 return "X86ISD::OR";
12503   case X86ISD::XOR:                return "X86ISD::XOR";
12504   case X86ISD::AND:                return "X86ISD::AND";
12505   case X86ISD::BLSI:               return "X86ISD::BLSI";
12506   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12507   case X86ISD::BLSR:               return "X86ISD::BLSR";
12508   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12509   case X86ISD::PTEST:              return "X86ISD::PTEST";
12510   case X86ISD::TESTP:              return "X86ISD::TESTP";
12511   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12512   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12513   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12514   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12515   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12516   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12517   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12518   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12519   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12520   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12521   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12522   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12523   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12524   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12525   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12526   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12527   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12528   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12529   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12530   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12531   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12532   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12533   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12534   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12535   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12536   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12537   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12538   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12539   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12540   case X86ISD::SAHF:               return "X86ISD::SAHF";
12541   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12542   case X86ISD::FMADD:              return "X86ISD::FMADD";
12543   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12544   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12545   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12546   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12547   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12548   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12549   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12550   }
12551 }
12552
12553 // isLegalAddressingMode - Return true if the addressing mode represented
12554 // by AM is legal for this target, for a load/store of the specified type.
12555 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12556                                               Type *Ty) const {
12557   // X86 supports extremely general addressing modes.
12558   CodeModel::Model M = getTargetMachine().getCodeModel();
12559   Reloc::Model R = getTargetMachine().getRelocationModel();
12560
12561   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12562   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12563     return false;
12564
12565   if (AM.BaseGV) {
12566     unsigned GVFlags =
12567       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12568
12569     // If a reference to this global requires an extra load, we can't fold it.
12570     if (isGlobalStubReference(GVFlags))
12571       return false;
12572
12573     // If BaseGV requires a register for the PIC base, we cannot also have a
12574     // BaseReg specified.
12575     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12576       return false;
12577
12578     // If lower 4G is not available, then we must use rip-relative addressing.
12579     if ((M != CodeModel::Small || R != Reloc::Static) &&
12580         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12581       return false;
12582   }
12583
12584   switch (AM.Scale) {
12585   case 0:
12586   case 1:
12587   case 2:
12588   case 4:
12589   case 8:
12590     // These scales always work.
12591     break;
12592   case 3:
12593   case 5:
12594   case 9:
12595     // These scales are formed with basereg+scalereg.  Only accept if there is
12596     // no basereg yet.
12597     if (AM.HasBaseReg)
12598       return false;
12599     break;
12600   default:  // Other stuff never works.
12601     return false;
12602   }
12603
12604   return true;
12605 }
12606
12607 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12608   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12609     return false;
12610   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12611   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12612   return NumBits1 > NumBits2;
12613 }
12614
12615 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12616   return isInt<32>(Imm);
12617 }
12618
12619 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12620   // Can also use sub to handle negated immediates.
12621   return isInt<32>(Imm);
12622 }
12623
12624 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12625   if (!VT1.isInteger() || !VT2.isInteger())
12626     return false;
12627   unsigned NumBits1 = VT1.getSizeInBits();
12628   unsigned NumBits2 = VT2.getSizeInBits();
12629   return NumBits1 > NumBits2;
12630 }
12631
12632 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12633   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12634   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12635 }
12636
12637 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12638   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12639   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12640 }
12641
12642 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12643   EVT VT1 = Val.getValueType();
12644   if (isZExtFree(VT1, VT2))
12645     return true;
12646
12647   if (Val.getOpcode() != ISD::LOAD)
12648     return false;
12649
12650   if (!VT1.isSimple() || !VT1.isInteger() ||
12651       !VT2.isSimple() || !VT2.isInteger())
12652     return false;
12653
12654   switch (VT1.getSimpleVT().SimpleTy) {
12655   default: break;
12656   case MVT::i8:
12657   case MVT::i16:
12658   case MVT::i32:
12659     // X86 has 8, 16, and 32-bit zero-extending loads.
12660     return true;
12661   }
12662
12663   return false;
12664 }
12665
12666 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12667   // i16 instructions are longer (0x66 prefix) and potentially slower.
12668   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12669 }
12670
12671 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12672 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12673 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12674 /// are assumed to be legal.
12675 bool
12676 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12677                                       EVT VT) const {
12678   // Very little shuffling can be done for 64-bit vectors right now.
12679   if (VT.getSizeInBits() == 64)
12680     return false;
12681
12682   // FIXME: pshufb, blends, shifts.
12683   return (VT.getVectorNumElements() == 2 ||
12684           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12685           isMOVLMask(M, VT) ||
12686           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12687           isPSHUFDMask(M, VT) ||
12688           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12689           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12690           isPALIGNRMask(M, VT, Subtarget) ||
12691           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12692           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12693           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12694           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12695 }
12696
12697 bool
12698 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12699                                           EVT VT) const {
12700   unsigned NumElts = VT.getVectorNumElements();
12701   // FIXME: This collection of masks seems suspect.
12702   if (NumElts == 2)
12703     return true;
12704   if (NumElts == 4 && VT.is128BitVector()) {
12705     return (isMOVLMask(Mask, VT)  ||
12706             isCommutedMOVLMask(Mask, VT, true) ||
12707             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12708             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12709   }
12710   return false;
12711 }
12712
12713 //===----------------------------------------------------------------------===//
12714 //                           X86 Scheduler Hooks
12715 //===----------------------------------------------------------------------===//
12716
12717 /// Utility function to emit xbegin specifying the start of an RTM region.
12718 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
12719                                      const TargetInstrInfo *TII) {
12720   DebugLoc DL = MI->getDebugLoc();
12721
12722   const BasicBlock *BB = MBB->getBasicBlock();
12723   MachineFunction::iterator I = MBB;
12724   ++I;
12725
12726   // For the v = xbegin(), we generate
12727   //
12728   // thisMBB:
12729   //  xbegin sinkMBB
12730   //
12731   // mainMBB:
12732   //  eax = -1
12733   //
12734   // sinkMBB:
12735   //  v = eax
12736
12737   MachineBasicBlock *thisMBB = MBB;
12738   MachineFunction *MF = MBB->getParent();
12739   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12740   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12741   MF->insert(I, mainMBB);
12742   MF->insert(I, sinkMBB);
12743
12744   // Transfer the remainder of BB and its successor edges to sinkMBB.
12745   sinkMBB->splice(sinkMBB->begin(), MBB,
12746                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12747   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12748
12749   // thisMBB:
12750   //  xbegin sinkMBB
12751   //  # fallthrough to mainMBB
12752   //  # abortion to sinkMBB
12753   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
12754   thisMBB->addSuccessor(mainMBB);
12755   thisMBB->addSuccessor(sinkMBB);
12756
12757   // mainMBB:
12758   //  EAX = -1
12759   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
12760   mainMBB->addSuccessor(sinkMBB);
12761
12762   // sinkMBB:
12763   // EAX is live into the sinkMBB
12764   sinkMBB->addLiveIn(X86::EAX);
12765   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12766           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
12767     .addReg(X86::EAX);
12768
12769   MI->eraseFromParent();
12770   return sinkMBB;
12771 }
12772
12773 // Get CMPXCHG opcode for the specified data type.
12774 static unsigned getCmpXChgOpcode(EVT VT) {
12775   switch (VT.getSimpleVT().SimpleTy) {
12776   case MVT::i8:  return X86::LCMPXCHG8;
12777   case MVT::i16: return X86::LCMPXCHG16;
12778   case MVT::i32: return X86::LCMPXCHG32;
12779   case MVT::i64: return X86::LCMPXCHG64;
12780   default:
12781     break;
12782   }
12783   llvm_unreachable("Invalid operand size!");
12784 }
12785
12786 // Get LOAD opcode for the specified data type.
12787 static unsigned getLoadOpcode(EVT VT) {
12788   switch (VT.getSimpleVT().SimpleTy) {
12789   case MVT::i8:  return X86::MOV8rm;
12790   case MVT::i16: return X86::MOV16rm;
12791   case MVT::i32: return X86::MOV32rm;
12792   case MVT::i64: return X86::MOV64rm;
12793   default:
12794     break;
12795   }
12796   llvm_unreachable("Invalid operand size!");
12797 }
12798
12799 // Get opcode of the non-atomic one from the specified atomic instruction.
12800 static unsigned getNonAtomicOpcode(unsigned Opc) {
12801   switch (Opc) {
12802   case X86::ATOMAND8:  return X86::AND8rr;
12803   case X86::ATOMAND16: return X86::AND16rr;
12804   case X86::ATOMAND32: return X86::AND32rr;
12805   case X86::ATOMAND64: return X86::AND64rr;
12806   case X86::ATOMOR8:   return X86::OR8rr;
12807   case X86::ATOMOR16:  return X86::OR16rr;
12808   case X86::ATOMOR32:  return X86::OR32rr;
12809   case X86::ATOMOR64:  return X86::OR64rr;
12810   case X86::ATOMXOR8:  return X86::XOR8rr;
12811   case X86::ATOMXOR16: return X86::XOR16rr;
12812   case X86::ATOMXOR32: return X86::XOR32rr;
12813   case X86::ATOMXOR64: return X86::XOR64rr;
12814   }
12815   llvm_unreachable("Unhandled atomic-load-op opcode!");
12816 }
12817
12818 // Get opcode of the non-atomic one from the specified atomic instruction with
12819 // extra opcode.
12820 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
12821                                                unsigned &ExtraOpc) {
12822   switch (Opc) {
12823   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
12824   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
12825   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
12826   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
12827   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
12828   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
12829   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
12830   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
12831   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
12832   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
12833   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
12834   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
12835   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
12836   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
12837   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
12838   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
12839   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
12840   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
12841   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
12842   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
12843   }
12844   llvm_unreachable("Unhandled atomic-load-op opcode!");
12845 }
12846
12847 // Get opcode of the non-atomic one from the specified atomic instruction for
12848 // 64-bit data type on 32-bit target.
12849 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
12850   switch (Opc) {
12851   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
12852   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
12853   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
12854   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
12855   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
12856   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
12857   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
12858   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
12859   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
12860   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
12861   }
12862   llvm_unreachable("Unhandled atomic-load-op opcode!");
12863 }
12864
12865 // Get opcode of the non-atomic one from the specified atomic instruction for
12866 // 64-bit data type on 32-bit target with extra opcode.
12867 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
12868                                                    unsigned &HiOpc,
12869                                                    unsigned &ExtraOpc) {
12870   switch (Opc) {
12871   case X86::ATOMNAND6432:
12872     ExtraOpc = X86::NOT32r;
12873     HiOpc = X86::AND32rr;
12874     return X86::AND32rr;
12875   }
12876   llvm_unreachable("Unhandled atomic-load-op opcode!");
12877 }
12878
12879 // Get pseudo CMOV opcode from the specified data type.
12880 static unsigned getPseudoCMOVOpc(EVT VT) {
12881   switch (VT.getSimpleVT().SimpleTy) {
12882   case MVT::i8:  return X86::CMOV_GR8;
12883   case MVT::i16: return X86::CMOV_GR16;
12884   case MVT::i32: return X86::CMOV_GR32;
12885   default:
12886     break;
12887   }
12888   llvm_unreachable("Unknown CMOV opcode!");
12889 }
12890
12891 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
12892 // They will be translated into a spin-loop or compare-exchange loop from
12893 //
12894 //    ...
12895 //    dst = atomic-fetch-op MI.addr, MI.val
12896 //    ...
12897 //
12898 // to
12899 //
12900 //    ...
12901 //    t1 = LOAD MI.addr
12902 // loop:
12903 //    t4 = phi(t1, t3 / loop)
12904 //    t2 = OP MI.val, t4
12905 //    EAX = t4
12906 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
12907 //    t3 = EAX
12908 //    JNE loop
12909 // sink:
12910 //    dst = t3
12911 //    ...
12912 MachineBasicBlock *
12913 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
12914                                        MachineBasicBlock *MBB) const {
12915   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12916   DebugLoc DL = MI->getDebugLoc();
12917
12918   MachineFunction *MF = MBB->getParent();
12919   MachineRegisterInfo &MRI = MF->getRegInfo();
12920
12921   const BasicBlock *BB = MBB->getBasicBlock();
12922   MachineFunction::iterator I = MBB;
12923   ++I;
12924
12925   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
12926          "Unexpected number of operands");
12927
12928   assert(MI->hasOneMemOperand() &&
12929          "Expected atomic-load-op to have one memoperand");
12930
12931   // Memory Reference
12932   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
12933   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
12934
12935   unsigned DstReg, SrcReg;
12936   unsigned MemOpndSlot;
12937
12938   unsigned CurOp = 0;
12939
12940   DstReg = MI->getOperand(CurOp++).getReg();
12941   MemOpndSlot = CurOp;
12942   CurOp += X86::AddrNumOperands;
12943   SrcReg = MI->getOperand(CurOp++).getReg();
12944
12945   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
12946   MVT::SimpleValueType VT = *RC->vt_begin();
12947   unsigned t1 = MRI.createVirtualRegister(RC);
12948   unsigned t2 = MRI.createVirtualRegister(RC);
12949   unsigned t3 = MRI.createVirtualRegister(RC);
12950   unsigned t4 = MRI.createVirtualRegister(RC);
12951   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
12952
12953   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
12954   unsigned LOADOpc = getLoadOpcode(VT);
12955
12956   // For the atomic load-arith operator, we generate
12957   //
12958   //  thisMBB:
12959   //    t1 = LOAD [MI.addr]
12960   //  mainMBB:
12961   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
12962   //    t1 = OP MI.val, EAX
12963   //    EAX = t4
12964   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
12965   //    t3 = EAX
12966   //    JNE mainMBB
12967   //  sinkMBB:
12968   //    dst = t3
12969
12970   MachineBasicBlock *thisMBB = MBB;
12971   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
12972   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
12973   MF->insert(I, mainMBB);
12974   MF->insert(I, sinkMBB);
12975
12976   MachineInstrBuilder MIB;
12977
12978   // Transfer the remainder of BB and its successor edges to sinkMBB.
12979   sinkMBB->splice(sinkMBB->begin(), MBB,
12980                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
12981   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
12982
12983   // thisMBB:
12984   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
12985   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
12986     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
12987     if (NewMO.isReg())
12988       NewMO.setIsKill(false);
12989     MIB.addOperand(NewMO);
12990   }
12991   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
12992     unsigned flags = (*MMOI)->getFlags();
12993     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
12994     MachineMemOperand *MMO =
12995       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
12996                                (*MMOI)->getSize(),
12997                                (*MMOI)->getBaseAlignment(),
12998                                (*MMOI)->getTBAAInfo(),
12999                                (*MMOI)->getRanges());
13000     MIB.addMemOperand(MMO);
13001   }
13002
13003   thisMBB->addSuccessor(mainMBB);
13004
13005   // mainMBB:
13006   MachineBasicBlock *origMainMBB = mainMBB;
13007
13008   // Add a PHI.
13009   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13010                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13011
13012   unsigned Opc = MI->getOpcode();
13013   switch (Opc) {
13014   default:
13015     llvm_unreachable("Unhandled atomic-load-op opcode!");
13016   case X86::ATOMAND8:
13017   case X86::ATOMAND16:
13018   case X86::ATOMAND32:
13019   case X86::ATOMAND64:
13020   case X86::ATOMOR8:
13021   case X86::ATOMOR16:
13022   case X86::ATOMOR32:
13023   case X86::ATOMOR64:
13024   case X86::ATOMXOR8:
13025   case X86::ATOMXOR16:
13026   case X86::ATOMXOR32:
13027   case X86::ATOMXOR64: {
13028     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13029     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13030       .addReg(t4);
13031     break;
13032   }
13033   case X86::ATOMNAND8:
13034   case X86::ATOMNAND16:
13035   case X86::ATOMNAND32:
13036   case X86::ATOMNAND64: {
13037     unsigned Tmp = MRI.createVirtualRegister(RC);
13038     unsigned NOTOpc;
13039     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13040     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13041       .addReg(t4);
13042     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13043     break;
13044   }
13045   case X86::ATOMMAX8:
13046   case X86::ATOMMAX16:
13047   case X86::ATOMMAX32:
13048   case X86::ATOMMAX64:
13049   case X86::ATOMMIN8:
13050   case X86::ATOMMIN16:
13051   case X86::ATOMMIN32:
13052   case X86::ATOMMIN64:
13053   case X86::ATOMUMAX8:
13054   case X86::ATOMUMAX16:
13055   case X86::ATOMUMAX32:
13056   case X86::ATOMUMAX64:
13057   case X86::ATOMUMIN8:
13058   case X86::ATOMUMIN16:
13059   case X86::ATOMUMIN32:
13060   case X86::ATOMUMIN64: {
13061     unsigned CMPOpc;
13062     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13063
13064     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13065       .addReg(SrcReg)
13066       .addReg(t4);
13067
13068     if (Subtarget->hasCMov()) {
13069       if (VT != MVT::i8) {
13070         // Native support
13071         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13072           .addReg(SrcReg)
13073           .addReg(t4);
13074       } else {
13075         // Promote i8 to i32 to use CMOV32
13076         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13077         const TargetRegisterClass *RC32 =
13078           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13079         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13080         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13081         unsigned Tmp = MRI.createVirtualRegister(RC32);
13082
13083         unsigned Undef = MRI.createVirtualRegister(RC32);
13084         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13085
13086         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13087           .addReg(Undef)
13088           .addReg(SrcReg)
13089           .addImm(X86::sub_8bit);
13090         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13091           .addReg(Undef)
13092           .addReg(t4)
13093           .addImm(X86::sub_8bit);
13094
13095         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13096           .addReg(SrcReg32)
13097           .addReg(AccReg32);
13098
13099         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13100           .addReg(Tmp, 0, X86::sub_8bit);
13101       }
13102     } else {
13103       // Use pseudo select and lower them.
13104       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13105              "Invalid atomic-load-op transformation!");
13106       unsigned SelOpc = getPseudoCMOVOpc(VT);
13107       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13108       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13109       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13110               .addReg(SrcReg).addReg(t4)
13111               .addImm(CC);
13112       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13113       // Replace the original PHI node as mainMBB is changed after CMOV
13114       // lowering.
13115       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13116         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13117       Phi->eraseFromParent();
13118     }
13119     break;
13120   }
13121   }
13122
13123   // Copy PhyReg back from virtual register.
13124   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13125     .addReg(t4);
13126
13127   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13128   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13129     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13130     if (NewMO.isReg())
13131       NewMO.setIsKill(false);
13132     MIB.addOperand(NewMO);
13133   }
13134   MIB.addReg(t2);
13135   MIB.setMemRefs(MMOBegin, MMOEnd);
13136
13137   // Copy PhyReg back to virtual register.
13138   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13139     .addReg(PhyReg);
13140
13141   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13142
13143   mainMBB->addSuccessor(origMainMBB);
13144   mainMBB->addSuccessor(sinkMBB);
13145
13146   // sinkMBB:
13147   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13148           TII->get(TargetOpcode::COPY), DstReg)
13149     .addReg(t3);
13150
13151   MI->eraseFromParent();
13152   return sinkMBB;
13153 }
13154
13155 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13156 // instructions. They will be translated into a spin-loop or compare-exchange
13157 // loop from
13158 //
13159 //    ...
13160 //    dst = atomic-fetch-op MI.addr, MI.val
13161 //    ...
13162 //
13163 // to
13164 //
13165 //    ...
13166 //    t1L = LOAD [MI.addr + 0]
13167 //    t1H = LOAD [MI.addr + 4]
13168 // loop:
13169 //    t4L = phi(t1L, t3L / loop)
13170 //    t4H = phi(t1H, t3H / loop)
13171 //    t2L = OP MI.val.lo, t4L
13172 //    t2H = OP MI.val.hi, t4H
13173 //    EAX = t4L
13174 //    EDX = t4H
13175 //    EBX = t2L
13176 //    ECX = t2H
13177 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13178 //    t3L = EAX
13179 //    t3H = EDX
13180 //    JNE loop
13181 // sink:
13182 //    dstL = t3L
13183 //    dstH = t3H
13184 //    ...
13185 MachineBasicBlock *
13186 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13187                                            MachineBasicBlock *MBB) const {
13188   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13189   DebugLoc DL = MI->getDebugLoc();
13190
13191   MachineFunction *MF = MBB->getParent();
13192   MachineRegisterInfo &MRI = MF->getRegInfo();
13193
13194   const BasicBlock *BB = MBB->getBasicBlock();
13195   MachineFunction::iterator I = MBB;
13196   ++I;
13197
13198   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13199          "Unexpected number of operands");
13200
13201   assert(MI->hasOneMemOperand() &&
13202          "Expected atomic-load-op32 to have one memoperand");
13203
13204   // Memory Reference
13205   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13206   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13207
13208   unsigned DstLoReg, DstHiReg;
13209   unsigned SrcLoReg, SrcHiReg;
13210   unsigned MemOpndSlot;
13211
13212   unsigned CurOp = 0;
13213
13214   DstLoReg = MI->getOperand(CurOp++).getReg();
13215   DstHiReg = MI->getOperand(CurOp++).getReg();
13216   MemOpndSlot = CurOp;
13217   CurOp += X86::AddrNumOperands;
13218   SrcLoReg = MI->getOperand(CurOp++).getReg();
13219   SrcHiReg = MI->getOperand(CurOp++).getReg();
13220
13221   const TargetRegisterClass *RC = &X86::GR32RegClass;
13222   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13223
13224   unsigned t1L = MRI.createVirtualRegister(RC);
13225   unsigned t1H = MRI.createVirtualRegister(RC);
13226   unsigned t2L = MRI.createVirtualRegister(RC);
13227   unsigned t2H = MRI.createVirtualRegister(RC);
13228   unsigned t3L = MRI.createVirtualRegister(RC);
13229   unsigned t3H = MRI.createVirtualRegister(RC);
13230   unsigned t4L = MRI.createVirtualRegister(RC);
13231   unsigned t4H = MRI.createVirtualRegister(RC);
13232
13233   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13234   unsigned LOADOpc = X86::MOV32rm;
13235
13236   // For the atomic load-arith operator, we generate
13237   //
13238   //  thisMBB:
13239   //    t1L = LOAD [MI.addr + 0]
13240   //    t1H = LOAD [MI.addr + 4]
13241   //  mainMBB:
13242   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13243   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13244   //    t2L = OP MI.val.lo, t4L
13245   //    t2H = OP MI.val.hi, t4H
13246   //    EBX = t2L
13247   //    ECX = t2H
13248   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13249   //    t3L = EAX
13250   //    t3H = EDX
13251   //    JNE loop
13252   //  sinkMBB:
13253   //    dstL = t3L
13254   //    dstH = t3H
13255
13256   MachineBasicBlock *thisMBB = MBB;
13257   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13258   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13259   MF->insert(I, mainMBB);
13260   MF->insert(I, sinkMBB);
13261
13262   MachineInstrBuilder MIB;
13263
13264   // Transfer the remainder of BB and its successor edges to sinkMBB.
13265   sinkMBB->splice(sinkMBB->begin(), MBB,
13266                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13267   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13268
13269   // thisMBB:
13270   // Lo
13271   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13272   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13273     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13274     if (NewMO.isReg())
13275       NewMO.setIsKill(false);
13276     MIB.addOperand(NewMO);
13277   }
13278   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13279     unsigned flags = (*MMOI)->getFlags();
13280     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13281     MachineMemOperand *MMO =
13282       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13283                                (*MMOI)->getSize(),
13284                                (*MMOI)->getBaseAlignment(),
13285                                (*MMOI)->getTBAAInfo(),
13286                                (*MMOI)->getRanges());
13287     MIB.addMemOperand(MMO);
13288   };
13289   MachineInstr *LowMI = MIB;
13290
13291   // Hi
13292   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13293   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13294     if (i == X86::AddrDisp) {
13295       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13296     } else {
13297       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13298       if (NewMO.isReg())
13299         NewMO.setIsKill(false);
13300       MIB.addOperand(NewMO);
13301     }
13302   }
13303   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13304
13305   thisMBB->addSuccessor(mainMBB);
13306
13307   // mainMBB:
13308   MachineBasicBlock *origMainMBB = mainMBB;
13309
13310   // Add PHIs.
13311   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13312                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13313   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13314                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13315
13316   unsigned Opc = MI->getOpcode();
13317   switch (Opc) {
13318   default:
13319     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13320   case X86::ATOMAND6432:
13321   case X86::ATOMOR6432:
13322   case X86::ATOMXOR6432:
13323   case X86::ATOMADD6432:
13324   case X86::ATOMSUB6432: {
13325     unsigned HiOpc;
13326     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13327     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13328       .addReg(SrcLoReg);
13329     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13330       .addReg(SrcHiReg);
13331     break;
13332   }
13333   case X86::ATOMNAND6432: {
13334     unsigned HiOpc, NOTOpc;
13335     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13336     unsigned TmpL = MRI.createVirtualRegister(RC);
13337     unsigned TmpH = MRI.createVirtualRegister(RC);
13338     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13339       .addReg(t4L);
13340     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13341       .addReg(t4H);
13342     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13343     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13344     break;
13345   }
13346   case X86::ATOMMAX6432:
13347   case X86::ATOMMIN6432:
13348   case X86::ATOMUMAX6432:
13349   case X86::ATOMUMIN6432: {
13350     unsigned HiOpc;
13351     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13352     unsigned cL = MRI.createVirtualRegister(RC8);
13353     unsigned cH = MRI.createVirtualRegister(RC8);
13354     unsigned cL32 = MRI.createVirtualRegister(RC);
13355     unsigned cH32 = MRI.createVirtualRegister(RC);
13356     unsigned cc = MRI.createVirtualRegister(RC);
13357     // cl := cmp src_lo, lo
13358     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13359       .addReg(SrcLoReg).addReg(t4L);
13360     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13361     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13362     // ch := cmp src_hi, hi
13363     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13364       .addReg(SrcHiReg).addReg(t4H);
13365     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13366     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13367     // cc := if (src_hi == hi) ? cl : ch;
13368     if (Subtarget->hasCMov()) {
13369       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13370         .addReg(cH32).addReg(cL32);
13371     } else {
13372       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13373               .addReg(cH32).addReg(cL32)
13374               .addImm(X86::COND_E);
13375       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13376     }
13377     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13378     if (Subtarget->hasCMov()) {
13379       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13380         .addReg(SrcLoReg).addReg(t4L);
13381       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13382         .addReg(SrcHiReg).addReg(t4H);
13383     } else {
13384       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13385               .addReg(SrcLoReg).addReg(t4L)
13386               .addImm(X86::COND_NE);
13387       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13388       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13389       // 2nd CMOV lowering.
13390       mainMBB->addLiveIn(X86::EFLAGS);
13391       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13392               .addReg(SrcHiReg).addReg(t4H)
13393               .addImm(X86::COND_NE);
13394       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13395       // Replace the original PHI node as mainMBB is changed after CMOV
13396       // lowering.
13397       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13398         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13399       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13400         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13401       PhiL->eraseFromParent();
13402       PhiH->eraseFromParent();
13403     }
13404     break;
13405   }
13406   case X86::ATOMSWAP6432: {
13407     unsigned HiOpc;
13408     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13409     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13410     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13411     break;
13412   }
13413   }
13414
13415   // Copy EDX:EAX back from HiReg:LoReg
13416   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13417   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13418   // Copy ECX:EBX from t1H:t1L
13419   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13420   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13421
13422   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13423   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13424     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13425     if (NewMO.isReg())
13426       NewMO.setIsKill(false);
13427     MIB.addOperand(NewMO);
13428   }
13429   MIB.setMemRefs(MMOBegin, MMOEnd);
13430
13431   // Copy EDX:EAX back to t3H:t3L
13432   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13433   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13434
13435   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13436
13437   mainMBB->addSuccessor(origMainMBB);
13438   mainMBB->addSuccessor(sinkMBB);
13439
13440   // sinkMBB:
13441   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13442           TII->get(TargetOpcode::COPY), DstLoReg)
13443     .addReg(t3L);
13444   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13445           TII->get(TargetOpcode::COPY), DstHiReg)
13446     .addReg(t3H);
13447
13448   MI->eraseFromParent();
13449   return sinkMBB;
13450 }
13451
13452 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13453 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13454 // in the .td file.
13455 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13456                                        const TargetInstrInfo *TII) {
13457   unsigned Opc;
13458   switch (MI->getOpcode()) {
13459   default: llvm_unreachable("illegal opcode!");
13460   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13461   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13462   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13463   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13464   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13465   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13466   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13467   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13468   }
13469
13470   DebugLoc dl = MI->getDebugLoc();
13471   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13472
13473   unsigned NumArgs = MI->getNumOperands();
13474   for (unsigned i = 1; i < NumArgs; ++i) {
13475     MachineOperand &Op = MI->getOperand(i);
13476     if (!(Op.isReg() && Op.isImplicit()))
13477       MIB.addOperand(Op);
13478   }
13479   if (MI->hasOneMemOperand())
13480     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13481
13482   BuildMI(*BB, MI, dl,
13483     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13484     .addReg(X86::XMM0);
13485
13486   MI->eraseFromParent();
13487   return BB;
13488 }
13489
13490 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13491 // defs in an instruction pattern
13492 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13493                                        const TargetInstrInfo *TII) {
13494   unsigned Opc;
13495   switch (MI->getOpcode()) {
13496   default: llvm_unreachable("illegal opcode!");
13497   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13498   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13499   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13500   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13501   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13502   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13503   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13504   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13505   }
13506
13507   DebugLoc dl = MI->getDebugLoc();
13508   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13509
13510   unsigned NumArgs = MI->getNumOperands(); // remove the results
13511   for (unsigned i = 1; i < NumArgs; ++i) {
13512     MachineOperand &Op = MI->getOperand(i);
13513     if (!(Op.isReg() && Op.isImplicit()))
13514       MIB.addOperand(Op);
13515   }
13516   if (MI->hasOneMemOperand())
13517     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13518
13519   BuildMI(*BB, MI, dl,
13520     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13521     .addReg(X86::ECX);
13522
13523   MI->eraseFromParent();
13524   return BB;
13525 }
13526
13527 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13528                                        const TargetInstrInfo *TII,
13529                                        const X86Subtarget* Subtarget) {
13530   DebugLoc dl = MI->getDebugLoc();
13531
13532   // Address into RAX/EAX, other two args into ECX, EDX.
13533   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13534   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13535   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13536   for (int i = 0; i < X86::AddrNumOperands; ++i)
13537     MIB.addOperand(MI->getOperand(i));
13538
13539   unsigned ValOps = X86::AddrNumOperands;
13540   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13541     .addReg(MI->getOperand(ValOps).getReg());
13542   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13543     .addReg(MI->getOperand(ValOps+1).getReg());
13544
13545   // The instruction doesn't actually take any operands though.
13546   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13547
13548   MI->eraseFromParent(); // The pseudo is gone now.
13549   return BB;
13550 }
13551
13552 MachineBasicBlock *
13553 X86TargetLowering::EmitVAARG64WithCustomInserter(
13554                    MachineInstr *MI,
13555                    MachineBasicBlock *MBB) const {
13556   // Emit va_arg instruction on X86-64.
13557
13558   // Operands to this pseudo-instruction:
13559   // 0  ) Output        : destination address (reg)
13560   // 1-5) Input         : va_list address (addr, i64mem)
13561   // 6  ) ArgSize       : Size (in bytes) of vararg type
13562   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13563   // 8  ) Align         : Alignment of type
13564   // 9  ) EFLAGS (implicit-def)
13565
13566   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13567   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13568
13569   unsigned DestReg = MI->getOperand(0).getReg();
13570   MachineOperand &Base = MI->getOperand(1);
13571   MachineOperand &Scale = MI->getOperand(2);
13572   MachineOperand &Index = MI->getOperand(3);
13573   MachineOperand &Disp = MI->getOperand(4);
13574   MachineOperand &Segment = MI->getOperand(5);
13575   unsigned ArgSize = MI->getOperand(6).getImm();
13576   unsigned ArgMode = MI->getOperand(7).getImm();
13577   unsigned Align = MI->getOperand(8).getImm();
13578
13579   // Memory Reference
13580   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13581   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13582   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13583
13584   // Machine Information
13585   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13586   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13587   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13588   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13589   DebugLoc DL = MI->getDebugLoc();
13590
13591   // struct va_list {
13592   //   i32   gp_offset
13593   //   i32   fp_offset
13594   //   i64   overflow_area (address)
13595   //   i64   reg_save_area (address)
13596   // }
13597   // sizeof(va_list) = 24
13598   // alignment(va_list) = 8
13599
13600   unsigned TotalNumIntRegs = 6;
13601   unsigned TotalNumXMMRegs = 8;
13602   bool UseGPOffset = (ArgMode == 1);
13603   bool UseFPOffset = (ArgMode == 2);
13604   unsigned MaxOffset = TotalNumIntRegs * 8 +
13605                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13606
13607   /* Align ArgSize to a multiple of 8 */
13608   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13609   bool NeedsAlign = (Align > 8);
13610
13611   MachineBasicBlock *thisMBB = MBB;
13612   MachineBasicBlock *overflowMBB;
13613   MachineBasicBlock *offsetMBB;
13614   MachineBasicBlock *endMBB;
13615
13616   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13617   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13618   unsigned OffsetReg = 0;
13619
13620   if (!UseGPOffset && !UseFPOffset) {
13621     // If we only pull from the overflow region, we don't create a branch.
13622     // We don't need to alter control flow.
13623     OffsetDestReg = 0; // unused
13624     OverflowDestReg = DestReg;
13625
13626     offsetMBB = NULL;
13627     overflowMBB = thisMBB;
13628     endMBB = thisMBB;
13629   } else {
13630     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13631     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13632     // If not, pull from overflow_area. (branch to overflowMBB)
13633     //
13634     //       thisMBB
13635     //         |     .
13636     //         |        .
13637     //     offsetMBB   overflowMBB
13638     //         |        .
13639     //         |     .
13640     //        endMBB
13641
13642     // Registers for the PHI in endMBB
13643     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13644     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13645
13646     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13647     MachineFunction *MF = MBB->getParent();
13648     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13649     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13650     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13651
13652     MachineFunction::iterator MBBIter = MBB;
13653     ++MBBIter;
13654
13655     // Insert the new basic blocks
13656     MF->insert(MBBIter, offsetMBB);
13657     MF->insert(MBBIter, overflowMBB);
13658     MF->insert(MBBIter, endMBB);
13659
13660     // Transfer the remainder of MBB and its successor edges to endMBB.
13661     endMBB->splice(endMBB->begin(), thisMBB,
13662                     llvm::next(MachineBasicBlock::iterator(MI)),
13663                     thisMBB->end());
13664     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13665
13666     // Make offsetMBB and overflowMBB successors of thisMBB
13667     thisMBB->addSuccessor(offsetMBB);
13668     thisMBB->addSuccessor(overflowMBB);
13669
13670     // endMBB is a successor of both offsetMBB and overflowMBB
13671     offsetMBB->addSuccessor(endMBB);
13672     overflowMBB->addSuccessor(endMBB);
13673
13674     // Load the offset value into a register
13675     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13676     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13677       .addOperand(Base)
13678       .addOperand(Scale)
13679       .addOperand(Index)
13680       .addDisp(Disp, UseFPOffset ? 4 : 0)
13681       .addOperand(Segment)
13682       .setMemRefs(MMOBegin, MMOEnd);
13683
13684     // Check if there is enough room left to pull this argument.
13685     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13686       .addReg(OffsetReg)
13687       .addImm(MaxOffset + 8 - ArgSizeA8);
13688
13689     // Branch to "overflowMBB" if offset >= max
13690     // Fall through to "offsetMBB" otherwise
13691     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13692       .addMBB(overflowMBB);
13693   }
13694
13695   // In offsetMBB, emit code to use the reg_save_area.
13696   if (offsetMBB) {
13697     assert(OffsetReg != 0);
13698
13699     // Read the reg_save_area address.
13700     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13701     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13702       .addOperand(Base)
13703       .addOperand(Scale)
13704       .addOperand(Index)
13705       .addDisp(Disp, 16)
13706       .addOperand(Segment)
13707       .setMemRefs(MMOBegin, MMOEnd);
13708
13709     // Zero-extend the offset
13710     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13711       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13712         .addImm(0)
13713         .addReg(OffsetReg)
13714         .addImm(X86::sub_32bit);
13715
13716     // Add the offset to the reg_save_area to get the final address.
13717     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
13718       .addReg(OffsetReg64)
13719       .addReg(RegSaveReg);
13720
13721     // Compute the offset for the next argument
13722     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13723     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
13724       .addReg(OffsetReg)
13725       .addImm(UseFPOffset ? 16 : 8);
13726
13727     // Store it back into the va_list.
13728     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
13729       .addOperand(Base)
13730       .addOperand(Scale)
13731       .addOperand(Index)
13732       .addDisp(Disp, UseFPOffset ? 4 : 0)
13733       .addOperand(Segment)
13734       .addReg(NextOffsetReg)
13735       .setMemRefs(MMOBegin, MMOEnd);
13736
13737     // Jump to endMBB
13738     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
13739       .addMBB(endMBB);
13740   }
13741
13742   //
13743   // Emit code to use overflow area
13744   //
13745
13746   // Load the overflow_area address into a register.
13747   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
13748   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
13749     .addOperand(Base)
13750     .addOperand(Scale)
13751     .addOperand(Index)
13752     .addDisp(Disp, 8)
13753     .addOperand(Segment)
13754     .setMemRefs(MMOBegin, MMOEnd);
13755
13756   // If we need to align it, do so. Otherwise, just copy the address
13757   // to OverflowDestReg.
13758   if (NeedsAlign) {
13759     // Align the overflow address
13760     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
13761     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
13762
13763     // aligned_addr = (addr + (align-1)) & ~(align-1)
13764     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
13765       .addReg(OverflowAddrReg)
13766       .addImm(Align-1);
13767
13768     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
13769       .addReg(TmpReg)
13770       .addImm(~(uint64_t)(Align-1));
13771   } else {
13772     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
13773       .addReg(OverflowAddrReg);
13774   }
13775
13776   // Compute the next overflow address after this argument.
13777   // (the overflow address should be kept 8-byte aligned)
13778   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
13779   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
13780     .addReg(OverflowDestReg)
13781     .addImm(ArgSizeA8);
13782
13783   // Store the new overflow address.
13784   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
13785     .addOperand(Base)
13786     .addOperand(Scale)
13787     .addOperand(Index)
13788     .addDisp(Disp, 8)
13789     .addOperand(Segment)
13790     .addReg(NextAddrReg)
13791     .setMemRefs(MMOBegin, MMOEnd);
13792
13793   // If we branched, emit the PHI to the front of endMBB.
13794   if (offsetMBB) {
13795     BuildMI(*endMBB, endMBB->begin(), DL,
13796             TII->get(X86::PHI), DestReg)
13797       .addReg(OffsetDestReg).addMBB(offsetMBB)
13798       .addReg(OverflowDestReg).addMBB(overflowMBB);
13799   }
13800
13801   // Erase the pseudo instruction
13802   MI->eraseFromParent();
13803
13804   return endMBB;
13805 }
13806
13807 MachineBasicBlock *
13808 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
13809                                                  MachineInstr *MI,
13810                                                  MachineBasicBlock *MBB) const {
13811   // Emit code to save XMM registers to the stack. The ABI says that the
13812   // number of registers to save is given in %al, so it's theoretically
13813   // possible to do an indirect jump trick to avoid saving all of them,
13814   // however this code takes a simpler approach and just executes all
13815   // of the stores if %al is non-zero. It's less code, and it's probably
13816   // easier on the hardware branch predictor, and stores aren't all that
13817   // expensive anyway.
13818
13819   // Create the new basic blocks. One block contains all the XMM stores,
13820   // and one block is the final destination regardless of whether any
13821   // stores were performed.
13822   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13823   MachineFunction *F = MBB->getParent();
13824   MachineFunction::iterator MBBIter = MBB;
13825   ++MBBIter;
13826   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
13827   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
13828   F->insert(MBBIter, XMMSaveMBB);
13829   F->insert(MBBIter, EndMBB);
13830
13831   // Transfer the remainder of MBB and its successor edges to EndMBB.
13832   EndMBB->splice(EndMBB->begin(), MBB,
13833                  llvm::next(MachineBasicBlock::iterator(MI)),
13834                  MBB->end());
13835   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
13836
13837   // The original block will now fall through to the XMM save block.
13838   MBB->addSuccessor(XMMSaveMBB);
13839   // The XMMSaveMBB will fall through to the end block.
13840   XMMSaveMBB->addSuccessor(EndMBB);
13841
13842   // Now add the instructions.
13843   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13844   DebugLoc DL = MI->getDebugLoc();
13845
13846   unsigned CountReg = MI->getOperand(0).getReg();
13847   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
13848   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
13849
13850   if (!Subtarget->isTargetWin64()) {
13851     // If %al is 0, branch around the XMM save block.
13852     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
13853     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
13854     MBB->addSuccessor(EndMBB);
13855   }
13856
13857   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
13858   // In the XMM save block, save all the XMM argument registers.
13859   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
13860     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
13861     MachineMemOperand *MMO =
13862       F->getMachineMemOperand(
13863           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
13864         MachineMemOperand::MOStore,
13865         /*Size=*/16, /*Align=*/16);
13866     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
13867       .addFrameIndex(RegSaveFrameIndex)
13868       .addImm(/*Scale=*/1)
13869       .addReg(/*IndexReg=*/0)
13870       .addImm(/*Disp=*/Offset)
13871       .addReg(/*Segment=*/0)
13872       .addReg(MI->getOperand(i).getReg())
13873       .addMemOperand(MMO);
13874   }
13875
13876   MI->eraseFromParent();   // The pseudo instruction is gone now.
13877
13878   return EndMBB;
13879 }
13880
13881 // The EFLAGS operand of SelectItr might be missing a kill marker
13882 // because there were multiple uses of EFLAGS, and ISel didn't know
13883 // which to mark. Figure out whether SelectItr should have had a
13884 // kill marker, and set it if it should. Returns the correct kill
13885 // marker value.
13886 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
13887                                      MachineBasicBlock* BB,
13888                                      const TargetRegisterInfo* TRI) {
13889   // Scan forward through BB for a use/def of EFLAGS.
13890   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
13891   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
13892     const MachineInstr& mi = *miI;
13893     if (mi.readsRegister(X86::EFLAGS))
13894       return false;
13895     if (mi.definesRegister(X86::EFLAGS))
13896       break; // Should have kill-flag - update below.
13897   }
13898
13899   // If we hit the end of the block, check whether EFLAGS is live into a
13900   // successor.
13901   if (miI == BB->end()) {
13902     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
13903                                           sEnd = BB->succ_end();
13904          sItr != sEnd; ++sItr) {
13905       MachineBasicBlock* succ = *sItr;
13906       if (succ->isLiveIn(X86::EFLAGS))
13907         return false;
13908     }
13909   }
13910
13911   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
13912   // out. SelectMI should have a kill flag on EFLAGS.
13913   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
13914   return true;
13915 }
13916
13917 MachineBasicBlock *
13918 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
13919                                      MachineBasicBlock *BB) const {
13920   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13921   DebugLoc DL = MI->getDebugLoc();
13922
13923   // To "insert" a SELECT_CC instruction, we actually have to insert the
13924   // diamond control-flow pattern.  The incoming instruction knows the
13925   // destination vreg to set, the condition code register to branch on, the
13926   // true/false values to select between, and a branch opcode to use.
13927   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13928   MachineFunction::iterator It = BB;
13929   ++It;
13930
13931   //  thisMBB:
13932   //  ...
13933   //   TrueVal = ...
13934   //   cmpTY ccX, r1, r2
13935   //   bCC copy1MBB
13936   //   fallthrough --> copy0MBB
13937   MachineBasicBlock *thisMBB = BB;
13938   MachineFunction *F = BB->getParent();
13939   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
13940   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
13941   F->insert(It, copy0MBB);
13942   F->insert(It, sinkMBB);
13943
13944   // If the EFLAGS register isn't dead in the terminator, then claim that it's
13945   // live into the sink and copy blocks.
13946   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13947   if (!MI->killsRegister(X86::EFLAGS) &&
13948       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
13949     copy0MBB->addLiveIn(X86::EFLAGS);
13950     sinkMBB->addLiveIn(X86::EFLAGS);
13951   }
13952
13953   // Transfer the remainder of BB and its successor edges to sinkMBB.
13954   sinkMBB->splice(sinkMBB->begin(), BB,
13955                   llvm::next(MachineBasicBlock::iterator(MI)),
13956                   BB->end());
13957   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
13958
13959   // Add the true and fallthrough blocks as its successors.
13960   BB->addSuccessor(copy0MBB);
13961   BB->addSuccessor(sinkMBB);
13962
13963   // Create the conditional branch instruction.
13964   unsigned Opc =
13965     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
13966   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
13967
13968   //  copy0MBB:
13969   //   %FalseValue = ...
13970   //   # fallthrough to sinkMBB
13971   copy0MBB->addSuccessor(sinkMBB);
13972
13973   //  sinkMBB:
13974   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
13975   //  ...
13976   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13977           TII->get(X86::PHI), MI->getOperand(0).getReg())
13978     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
13979     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
13980
13981   MI->eraseFromParent();   // The pseudo instruction is gone now.
13982   return sinkMBB;
13983 }
13984
13985 MachineBasicBlock *
13986 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
13987                                         bool Is64Bit) const {
13988   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13989   DebugLoc DL = MI->getDebugLoc();
13990   MachineFunction *MF = BB->getParent();
13991   const BasicBlock *LLVM_BB = BB->getBasicBlock();
13992
13993   assert(getTargetMachine().Options.EnableSegmentedStacks);
13994
13995   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
13996   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
13997
13998   // BB:
13999   //  ... [Till the alloca]
14000   // If stacklet is not large enough, jump to mallocMBB
14001   //
14002   // bumpMBB:
14003   //  Allocate by subtracting from RSP
14004   //  Jump to continueMBB
14005   //
14006   // mallocMBB:
14007   //  Allocate by call to runtime
14008   //
14009   // continueMBB:
14010   //  ...
14011   //  [rest of original BB]
14012   //
14013
14014   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14015   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14016   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14017
14018   MachineRegisterInfo &MRI = MF->getRegInfo();
14019   const TargetRegisterClass *AddrRegClass =
14020     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14021
14022   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14023     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14024     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14025     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14026     sizeVReg = MI->getOperand(1).getReg(),
14027     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14028
14029   MachineFunction::iterator MBBIter = BB;
14030   ++MBBIter;
14031
14032   MF->insert(MBBIter, bumpMBB);
14033   MF->insert(MBBIter, mallocMBB);
14034   MF->insert(MBBIter, continueMBB);
14035
14036   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14037                       (MachineBasicBlock::iterator(MI)), BB->end());
14038   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14039
14040   // Add code to the main basic block to check if the stack limit has been hit,
14041   // and if so, jump to mallocMBB otherwise to bumpMBB.
14042   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14043   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14044     .addReg(tmpSPVReg).addReg(sizeVReg);
14045   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14046     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14047     .addReg(SPLimitVReg);
14048   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14049
14050   // bumpMBB simply decreases the stack pointer, since we know the current
14051   // stacklet has enough space.
14052   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14053     .addReg(SPLimitVReg);
14054   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14055     .addReg(SPLimitVReg);
14056   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14057
14058   // Calls into a routine in libgcc to allocate more space from the heap.
14059   const uint32_t *RegMask =
14060     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14061   if (Is64Bit) {
14062     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14063       .addReg(sizeVReg);
14064     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14065       .addExternalSymbol("__morestack_allocate_stack_space")
14066       .addRegMask(RegMask)
14067       .addReg(X86::RDI, RegState::Implicit)
14068       .addReg(X86::RAX, RegState::ImplicitDefine);
14069   } else {
14070     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14071       .addImm(12);
14072     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14073     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14074       .addExternalSymbol("__morestack_allocate_stack_space")
14075       .addRegMask(RegMask)
14076       .addReg(X86::EAX, RegState::ImplicitDefine);
14077   }
14078
14079   if (!Is64Bit)
14080     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14081       .addImm(16);
14082
14083   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14084     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14085   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14086
14087   // Set up the CFG correctly.
14088   BB->addSuccessor(bumpMBB);
14089   BB->addSuccessor(mallocMBB);
14090   mallocMBB->addSuccessor(continueMBB);
14091   bumpMBB->addSuccessor(continueMBB);
14092
14093   // Take care of the PHI nodes.
14094   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14095           MI->getOperand(0).getReg())
14096     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14097     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14098
14099   // Delete the original pseudo instruction.
14100   MI->eraseFromParent();
14101
14102   // And we're done.
14103   return continueMBB;
14104 }
14105
14106 MachineBasicBlock *
14107 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14108                                           MachineBasicBlock *BB) const {
14109   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14110   DebugLoc DL = MI->getDebugLoc();
14111
14112   assert(!Subtarget->isTargetEnvMacho());
14113
14114   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14115   // non-trivial part is impdef of ESP.
14116
14117   if (Subtarget->isTargetWin64()) {
14118     if (Subtarget->isTargetCygMing()) {
14119       // ___chkstk(Mingw64):
14120       // Clobbers R10, R11, RAX and EFLAGS.
14121       // Updates RSP.
14122       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14123         .addExternalSymbol("___chkstk")
14124         .addReg(X86::RAX, RegState::Implicit)
14125         .addReg(X86::RSP, RegState::Implicit)
14126         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14127         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14128         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14129     } else {
14130       // __chkstk(MSVCRT): does not update stack pointer.
14131       // Clobbers R10, R11 and EFLAGS.
14132       // FIXME: RAX(allocated size) might be reused and not killed.
14133       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14134         .addExternalSymbol("__chkstk")
14135         .addReg(X86::RAX, RegState::Implicit)
14136         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14137       // RAX has the offset to subtracted from RSP.
14138       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14139         .addReg(X86::RSP)
14140         .addReg(X86::RAX);
14141     }
14142   } else {
14143     const char *StackProbeSymbol =
14144       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14145
14146     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14147       .addExternalSymbol(StackProbeSymbol)
14148       .addReg(X86::EAX, RegState::Implicit)
14149       .addReg(X86::ESP, RegState::Implicit)
14150       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14151       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14152       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14153   }
14154
14155   MI->eraseFromParent();   // The pseudo instruction is gone now.
14156   return BB;
14157 }
14158
14159 MachineBasicBlock *
14160 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14161                                       MachineBasicBlock *BB) const {
14162   // This is pretty easy.  We're taking the value that we received from
14163   // our load from the relocation, sticking it in either RDI (x86-64)
14164   // or EAX and doing an indirect call.  The return value will then
14165   // be in the normal return register.
14166   const X86InstrInfo *TII
14167     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14168   DebugLoc DL = MI->getDebugLoc();
14169   MachineFunction *F = BB->getParent();
14170
14171   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14172   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14173
14174   // Get a register mask for the lowered call.
14175   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14176   // proper register mask.
14177   const uint32_t *RegMask =
14178     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14179   if (Subtarget->is64Bit()) {
14180     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14181                                       TII->get(X86::MOV64rm), X86::RDI)
14182     .addReg(X86::RIP)
14183     .addImm(0).addReg(0)
14184     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14185                       MI->getOperand(3).getTargetFlags())
14186     .addReg(0);
14187     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14188     addDirectMem(MIB, X86::RDI);
14189     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14190   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14191     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14192                                       TII->get(X86::MOV32rm), X86::EAX)
14193     .addReg(0)
14194     .addImm(0).addReg(0)
14195     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14196                       MI->getOperand(3).getTargetFlags())
14197     .addReg(0);
14198     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14199     addDirectMem(MIB, X86::EAX);
14200     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14201   } else {
14202     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14203                                       TII->get(X86::MOV32rm), X86::EAX)
14204     .addReg(TII->getGlobalBaseReg(F))
14205     .addImm(0).addReg(0)
14206     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14207                       MI->getOperand(3).getTargetFlags())
14208     .addReg(0);
14209     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14210     addDirectMem(MIB, X86::EAX);
14211     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14212   }
14213
14214   MI->eraseFromParent(); // The pseudo instruction is gone now.
14215   return BB;
14216 }
14217
14218 MachineBasicBlock *
14219 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14220                                     MachineBasicBlock *MBB) const {
14221   DebugLoc DL = MI->getDebugLoc();
14222   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14223
14224   MachineFunction *MF = MBB->getParent();
14225   MachineRegisterInfo &MRI = MF->getRegInfo();
14226
14227   const BasicBlock *BB = MBB->getBasicBlock();
14228   MachineFunction::iterator I = MBB;
14229   ++I;
14230
14231   // Memory Reference
14232   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14233   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14234
14235   unsigned DstReg;
14236   unsigned MemOpndSlot = 0;
14237
14238   unsigned CurOp = 0;
14239
14240   DstReg = MI->getOperand(CurOp++).getReg();
14241   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14242   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14243   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14244   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14245
14246   MemOpndSlot = CurOp;
14247
14248   MVT PVT = getPointerTy();
14249   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14250          "Invalid Pointer Size!");
14251
14252   // For v = setjmp(buf), we generate
14253   //
14254   // thisMBB:
14255   //  buf[LabelOffset] = restoreMBB
14256   //  SjLjSetup restoreMBB
14257   //
14258   // mainMBB:
14259   //  v_main = 0
14260   //
14261   // sinkMBB:
14262   //  v = phi(main, restore)
14263   //
14264   // restoreMBB:
14265   //  v_restore = 1
14266
14267   MachineBasicBlock *thisMBB = MBB;
14268   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14269   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14270   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14271   MF->insert(I, mainMBB);
14272   MF->insert(I, sinkMBB);
14273   MF->push_back(restoreMBB);
14274
14275   MachineInstrBuilder MIB;
14276
14277   // Transfer the remainder of BB and its successor edges to sinkMBB.
14278   sinkMBB->splice(sinkMBB->begin(), MBB,
14279                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14280   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14281
14282   // thisMBB:
14283   unsigned PtrStoreOpc = 0;
14284   unsigned LabelReg = 0;
14285   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14286   Reloc::Model RM = getTargetMachine().getRelocationModel();
14287   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14288                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14289
14290   // Prepare IP either in reg or imm.
14291   if (!UseImmLabel) {
14292     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14293     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14294     LabelReg = MRI.createVirtualRegister(PtrRC);
14295     if (Subtarget->is64Bit()) {
14296       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14297               .addReg(X86::RIP)
14298               .addImm(0)
14299               .addReg(0)
14300               .addMBB(restoreMBB)
14301               .addReg(0);
14302     } else {
14303       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14304       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14305               .addReg(XII->getGlobalBaseReg(MF))
14306               .addImm(0)
14307               .addReg(0)
14308               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14309               .addReg(0);
14310     }
14311   } else
14312     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14313   // Store IP
14314   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14315   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14316     if (i == X86::AddrDisp)
14317       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14318     else
14319       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14320   }
14321   if (!UseImmLabel)
14322     MIB.addReg(LabelReg);
14323   else
14324     MIB.addMBB(restoreMBB);
14325   MIB.setMemRefs(MMOBegin, MMOEnd);
14326   // Setup
14327   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14328           .addMBB(restoreMBB);
14329   MIB.addRegMask(RegInfo->getNoPreservedMask());
14330   thisMBB->addSuccessor(mainMBB);
14331   thisMBB->addSuccessor(restoreMBB);
14332
14333   // mainMBB:
14334   //  EAX = 0
14335   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14336   mainMBB->addSuccessor(sinkMBB);
14337
14338   // sinkMBB:
14339   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14340           TII->get(X86::PHI), DstReg)
14341     .addReg(mainDstReg).addMBB(mainMBB)
14342     .addReg(restoreDstReg).addMBB(restoreMBB);
14343
14344   // restoreMBB:
14345   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14346   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14347   restoreMBB->addSuccessor(sinkMBB);
14348
14349   MI->eraseFromParent();
14350   return sinkMBB;
14351 }
14352
14353 MachineBasicBlock *
14354 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14355                                      MachineBasicBlock *MBB) const {
14356   DebugLoc DL = MI->getDebugLoc();
14357   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14358
14359   MachineFunction *MF = MBB->getParent();
14360   MachineRegisterInfo &MRI = MF->getRegInfo();
14361
14362   // Memory Reference
14363   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14364   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14365
14366   MVT PVT = getPointerTy();
14367   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14368          "Invalid Pointer Size!");
14369
14370   const TargetRegisterClass *RC =
14371     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14372   unsigned Tmp = MRI.createVirtualRegister(RC);
14373   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14374   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14375   unsigned SP = RegInfo->getStackRegister();
14376
14377   MachineInstrBuilder MIB;
14378
14379   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14380   const int64_t SPOffset = 2 * PVT.getStoreSize();
14381
14382   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14383   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14384
14385   // Reload FP
14386   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14387   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14388     MIB.addOperand(MI->getOperand(i));
14389   MIB.setMemRefs(MMOBegin, MMOEnd);
14390   // Reload IP
14391   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14392   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14393     if (i == X86::AddrDisp)
14394       MIB.addDisp(MI->getOperand(i), LabelOffset);
14395     else
14396       MIB.addOperand(MI->getOperand(i));
14397   }
14398   MIB.setMemRefs(MMOBegin, MMOEnd);
14399   // Reload SP
14400   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14401   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14402     if (i == X86::AddrDisp)
14403       MIB.addDisp(MI->getOperand(i), SPOffset);
14404     else
14405       MIB.addOperand(MI->getOperand(i));
14406   }
14407   MIB.setMemRefs(MMOBegin, MMOEnd);
14408   // Jump
14409   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14410
14411   MI->eraseFromParent();
14412   return MBB;
14413 }
14414
14415 MachineBasicBlock *
14416 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14417                                                MachineBasicBlock *BB) const {
14418   switch (MI->getOpcode()) {
14419   default: llvm_unreachable("Unexpected instr type to insert");
14420   case X86::TAILJMPd64:
14421   case X86::TAILJMPr64:
14422   case X86::TAILJMPm64:
14423     llvm_unreachable("TAILJMP64 would not be touched here.");
14424   case X86::TCRETURNdi64:
14425   case X86::TCRETURNri64:
14426   case X86::TCRETURNmi64:
14427     return BB;
14428   case X86::WIN_ALLOCA:
14429     return EmitLoweredWinAlloca(MI, BB);
14430   case X86::SEG_ALLOCA_32:
14431     return EmitLoweredSegAlloca(MI, BB, false);
14432   case X86::SEG_ALLOCA_64:
14433     return EmitLoweredSegAlloca(MI, BB, true);
14434   case X86::TLSCall_32:
14435   case X86::TLSCall_64:
14436     return EmitLoweredTLSCall(MI, BB);
14437   case X86::CMOV_GR8:
14438   case X86::CMOV_FR32:
14439   case X86::CMOV_FR64:
14440   case X86::CMOV_V4F32:
14441   case X86::CMOV_V2F64:
14442   case X86::CMOV_V2I64:
14443   case X86::CMOV_V8F32:
14444   case X86::CMOV_V4F64:
14445   case X86::CMOV_V4I64:
14446   case X86::CMOV_GR16:
14447   case X86::CMOV_GR32:
14448   case X86::CMOV_RFP32:
14449   case X86::CMOV_RFP64:
14450   case X86::CMOV_RFP80:
14451     return EmitLoweredSelect(MI, BB);
14452
14453   case X86::FP32_TO_INT16_IN_MEM:
14454   case X86::FP32_TO_INT32_IN_MEM:
14455   case X86::FP32_TO_INT64_IN_MEM:
14456   case X86::FP64_TO_INT16_IN_MEM:
14457   case X86::FP64_TO_INT32_IN_MEM:
14458   case X86::FP64_TO_INT64_IN_MEM:
14459   case X86::FP80_TO_INT16_IN_MEM:
14460   case X86::FP80_TO_INT32_IN_MEM:
14461   case X86::FP80_TO_INT64_IN_MEM: {
14462     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14463     DebugLoc DL = MI->getDebugLoc();
14464
14465     // Change the floating point control register to use "round towards zero"
14466     // mode when truncating to an integer value.
14467     MachineFunction *F = BB->getParent();
14468     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14469     addFrameReference(BuildMI(*BB, MI, DL,
14470                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14471
14472     // Load the old value of the high byte of the control word...
14473     unsigned OldCW =
14474       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14475     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14476                       CWFrameIdx);
14477
14478     // Set the high part to be round to zero...
14479     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14480       .addImm(0xC7F);
14481
14482     // Reload the modified control word now...
14483     addFrameReference(BuildMI(*BB, MI, DL,
14484                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14485
14486     // Restore the memory image of control word to original value
14487     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14488       .addReg(OldCW);
14489
14490     // Get the X86 opcode to use.
14491     unsigned Opc;
14492     switch (MI->getOpcode()) {
14493     default: llvm_unreachable("illegal opcode!");
14494     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14495     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14496     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14497     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14498     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14499     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14500     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14501     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14502     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14503     }
14504
14505     X86AddressMode AM;
14506     MachineOperand &Op = MI->getOperand(0);
14507     if (Op.isReg()) {
14508       AM.BaseType = X86AddressMode::RegBase;
14509       AM.Base.Reg = Op.getReg();
14510     } else {
14511       AM.BaseType = X86AddressMode::FrameIndexBase;
14512       AM.Base.FrameIndex = Op.getIndex();
14513     }
14514     Op = MI->getOperand(1);
14515     if (Op.isImm())
14516       AM.Scale = Op.getImm();
14517     Op = MI->getOperand(2);
14518     if (Op.isImm())
14519       AM.IndexReg = Op.getImm();
14520     Op = MI->getOperand(3);
14521     if (Op.isGlobal()) {
14522       AM.GV = Op.getGlobal();
14523     } else {
14524       AM.Disp = Op.getImm();
14525     }
14526     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14527                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14528
14529     // Reload the original control word now.
14530     addFrameReference(BuildMI(*BB, MI, DL,
14531                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14532
14533     MI->eraseFromParent();   // The pseudo instruction is gone now.
14534     return BB;
14535   }
14536     // String/text processing lowering.
14537   case X86::PCMPISTRM128REG:
14538   case X86::VPCMPISTRM128REG:
14539   case X86::PCMPISTRM128MEM:
14540   case X86::VPCMPISTRM128MEM:
14541   case X86::PCMPESTRM128REG:
14542   case X86::VPCMPESTRM128REG:
14543   case X86::PCMPESTRM128MEM:
14544   case X86::VPCMPESTRM128MEM:
14545     assert(Subtarget->hasSSE42() &&
14546            "Target must have SSE4.2 or AVX features enabled");
14547     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14548
14549   // String/text processing lowering.
14550   case X86::PCMPISTRIREG:
14551   case X86::VPCMPISTRIREG:
14552   case X86::PCMPISTRIMEM:
14553   case X86::VPCMPISTRIMEM:
14554   case X86::PCMPESTRIREG:
14555   case X86::VPCMPESTRIREG:
14556   case X86::PCMPESTRIMEM:
14557   case X86::VPCMPESTRIMEM:
14558     assert(Subtarget->hasSSE42() &&
14559            "Target must have SSE4.2 or AVX features enabled");
14560     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14561
14562   // Thread synchronization.
14563   case X86::MONITOR:
14564     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14565
14566   // xbegin
14567   case X86::XBEGIN:
14568     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14569
14570   // Atomic Lowering.
14571   case X86::ATOMAND8:
14572   case X86::ATOMAND16:
14573   case X86::ATOMAND32:
14574   case X86::ATOMAND64:
14575     // Fall through
14576   case X86::ATOMOR8:
14577   case X86::ATOMOR16:
14578   case X86::ATOMOR32:
14579   case X86::ATOMOR64:
14580     // Fall through
14581   case X86::ATOMXOR16:
14582   case X86::ATOMXOR8:
14583   case X86::ATOMXOR32:
14584   case X86::ATOMXOR64:
14585     // Fall through
14586   case X86::ATOMNAND8:
14587   case X86::ATOMNAND16:
14588   case X86::ATOMNAND32:
14589   case X86::ATOMNAND64:
14590     // Fall through
14591   case X86::ATOMMAX8:
14592   case X86::ATOMMAX16:
14593   case X86::ATOMMAX32:
14594   case X86::ATOMMAX64:
14595     // Fall through
14596   case X86::ATOMMIN8:
14597   case X86::ATOMMIN16:
14598   case X86::ATOMMIN32:
14599   case X86::ATOMMIN64:
14600     // Fall through
14601   case X86::ATOMUMAX8:
14602   case X86::ATOMUMAX16:
14603   case X86::ATOMUMAX32:
14604   case X86::ATOMUMAX64:
14605     // Fall through
14606   case X86::ATOMUMIN8:
14607   case X86::ATOMUMIN16:
14608   case X86::ATOMUMIN32:
14609   case X86::ATOMUMIN64:
14610     return EmitAtomicLoadArith(MI, BB);
14611
14612   // This group does 64-bit operations on a 32-bit host.
14613   case X86::ATOMAND6432:
14614   case X86::ATOMOR6432:
14615   case X86::ATOMXOR6432:
14616   case X86::ATOMNAND6432:
14617   case X86::ATOMADD6432:
14618   case X86::ATOMSUB6432:
14619   case X86::ATOMMAX6432:
14620   case X86::ATOMMIN6432:
14621   case X86::ATOMUMAX6432:
14622   case X86::ATOMUMIN6432:
14623   case X86::ATOMSWAP6432:
14624     return EmitAtomicLoadArith6432(MI, BB);
14625
14626   case X86::VASTART_SAVE_XMM_REGS:
14627     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14628
14629   case X86::VAARG_64:
14630     return EmitVAARG64WithCustomInserter(MI, BB);
14631
14632   case X86::EH_SjLj_SetJmp32:
14633   case X86::EH_SjLj_SetJmp64:
14634     return emitEHSjLjSetJmp(MI, BB);
14635
14636   case X86::EH_SjLj_LongJmp32:
14637   case X86::EH_SjLj_LongJmp64:
14638     return emitEHSjLjLongJmp(MI, BB);
14639   }
14640 }
14641
14642 //===----------------------------------------------------------------------===//
14643 //                           X86 Optimization Hooks
14644 //===----------------------------------------------------------------------===//
14645
14646 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14647                                                        APInt &KnownZero,
14648                                                        APInt &KnownOne,
14649                                                        const SelectionDAG &DAG,
14650                                                        unsigned Depth) const {
14651   unsigned BitWidth = KnownZero.getBitWidth();
14652   unsigned Opc = Op.getOpcode();
14653   assert((Opc >= ISD::BUILTIN_OP_END ||
14654           Opc == ISD::INTRINSIC_WO_CHAIN ||
14655           Opc == ISD::INTRINSIC_W_CHAIN ||
14656           Opc == ISD::INTRINSIC_VOID) &&
14657          "Should use MaskedValueIsZero if you don't know whether Op"
14658          " is a target node!");
14659
14660   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14661   switch (Opc) {
14662   default: break;
14663   case X86ISD::ADD:
14664   case X86ISD::SUB:
14665   case X86ISD::ADC:
14666   case X86ISD::SBB:
14667   case X86ISD::SMUL:
14668   case X86ISD::UMUL:
14669   case X86ISD::INC:
14670   case X86ISD::DEC:
14671   case X86ISD::OR:
14672   case X86ISD::XOR:
14673   case X86ISD::AND:
14674     // These nodes' second result is a boolean.
14675     if (Op.getResNo() == 0)
14676       break;
14677     // Fallthrough
14678   case X86ISD::SETCC:
14679     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14680     break;
14681   case ISD::INTRINSIC_WO_CHAIN: {
14682     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14683     unsigned NumLoBits = 0;
14684     switch (IntId) {
14685     default: break;
14686     case Intrinsic::x86_sse_movmsk_ps:
14687     case Intrinsic::x86_avx_movmsk_ps_256:
14688     case Intrinsic::x86_sse2_movmsk_pd:
14689     case Intrinsic::x86_avx_movmsk_pd_256:
14690     case Intrinsic::x86_mmx_pmovmskb:
14691     case Intrinsic::x86_sse2_pmovmskb_128:
14692     case Intrinsic::x86_avx2_pmovmskb: {
14693       // High bits of movmskp{s|d}, pmovmskb are known zero.
14694       switch (IntId) {
14695         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14696         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14697         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14698         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14699         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14700         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14701         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14702         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14703       }
14704       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14705       break;
14706     }
14707     }
14708     break;
14709   }
14710   }
14711 }
14712
14713 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
14714                                                          unsigned Depth) const {
14715   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
14716   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
14717     return Op.getValueType().getScalarType().getSizeInBits();
14718
14719   // Fallback case.
14720   return 1;
14721 }
14722
14723 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
14724 /// node is a GlobalAddress + offset.
14725 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
14726                                        const GlobalValue* &GA,
14727                                        int64_t &Offset) const {
14728   if (N->getOpcode() == X86ISD::Wrapper) {
14729     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
14730       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
14731       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
14732       return true;
14733     }
14734   }
14735   return TargetLowering::isGAPlusOffset(N, GA, Offset);
14736 }
14737
14738 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
14739 /// same as extracting the high 128-bit part of 256-bit vector and then
14740 /// inserting the result into the low part of a new 256-bit vector
14741 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
14742   EVT VT = SVOp->getValueType(0);
14743   unsigned NumElems = VT.getVectorNumElements();
14744
14745   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14746   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
14747     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14748         SVOp->getMaskElt(j) >= 0)
14749       return false;
14750
14751   return true;
14752 }
14753
14754 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
14755 /// same as extracting the low 128-bit part of 256-bit vector and then
14756 /// inserting the result into the high part of a new 256-bit vector
14757 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
14758   EVT VT = SVOp->getValueType(0);
14759   unsigned NumElems = VT.getVectorNumElements();
14760
14761   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14762   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
14763     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
14764         SVOp->getMaskElt(j) >= 0)
14765       return false;
14766
14767   return true;
14768 }
14769
14770 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
14771 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
14772                                         TargetLowering::DAGCombinerInfo &DCI,
14773                                         const X86Subtarget* Subtarget) {
14774   DebugLoc dl = N->getDebugLoc();
14775   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
14776   SDValue V1 = SVOp->getOperand(0);
14777   SDValue V2 = SVOp->getOperand(1);
14778   EVT VT = SVOp->getValueType(0);
14779   unsigned NumElems = VT.getVectorNumElements();
14780
14781   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
14782       V2.getOpcode() == ISD::CONCAT_VECTORS) {
14783     //
14784     //                   0,0,0,...
14785     //                      |
14786     //    V      UNDEF    BUILD_VECTOR    UNDEF
14787     //     \      /           \           /
14788     //  CONCAT_VECTOR         CONCAT_VECTOR
14789     //         \                  /
14790     //          \                /
14791     //          RESULT: V + zero extended
14792     //
14793     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
14794         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
14795         V1.getOperand(1).getOpcode() != ISD::UNDEF)
14796       return SDValue();
14797
14798     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
14799       return SDValue();
14800
14801     // To match the shuffle mask, the first half of the mask should
14802     // be exactly the first vector, and all the rest a splat with the
14803     // first element of the second one.
14804     for (unsigned i = 0; i != NumElems/2; ++i)
14805       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
14806           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
14807         return SDValue();
14808
14809     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
14810     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
14811       if (Ld->hasNUsesOfValue(1, 0)) {
14812         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
14813         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
14814         SDValue ResNode =
14815           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
14816                                   Ld->getMemoryVT(),
14817                                   Ld->getPointerInfo(),
14818                                   Ld->getAlignment(),
14819                                   false/*isVolatile*/, true/*ReadMem*/,
14820                                   false/*WriteMem*/);
14821
14822         // Make sure the newly-created LOAD is in the same position as Ld in
14823         // terms of dependency. We create a TokenFactor for Ld and ResNode,
14824         // and update uses of Ld's output chain to use the TokenFactor.
14825         if (Ld->hasAnyUseOfValue(1)) {
14826           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14827                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
14828           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
14829           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
14830                                  SDValue(ResNode.getNode(), 1));
14831         }
14832
14833         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
14834       }
14835     }
14836
14837     // Emit a zeroed vector and insert the desired subvector on its
14838     // first half.
14839     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14840     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
14841     return DCI.CombineTo(N, InsV);
14842   }
14843
14844   //===--------------------------------------------------------------------===//
14845   // Combine some shuffles into subvector extracts and inserts:
14846   //
14847
14848   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
14849   if (isShuffleHigh128VectorInsertLow(SVOp)) {
14850     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
14851     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
14852     return DCI.CombineTo(N, InsV);
14853   }
14854
14855   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
14856   if (isShuffleLow128VectorInsertHigh(SVOp)) {
14857     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
14858     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
14859     return DCI.CombineTo(N, InsV);
14860   }
14861
14862   return SDValue();
14863 }
14864
14865 /// PerformShuffleCombine - Performs several different shuffle combines.
14866 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
14867                                      TargetLowering::DAGCombinerInfo &DCI,
14868                                      const X86Subtarget *Subtarget) {
14869   DebugLoc dl = N->getDebugLoc();
14870   EVT VT = N->getValueType(0);
14871
14872   // Don't create instructions with illegal types after legalize types has run.
14873   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14874   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
14875     return SDValue();
14876
14877   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
14878   if (Subtarget->hasFp256() && VT.is256BitVector() &&
14879       N->getOpcode() == ISD::VECTOR_SHUFFLE)
14880     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
14881
14882   // Only handle 128 wide vector from here on.
14883   if (!VT.is128BitVector())
14884     return SDValue();
14885
14886   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
14887   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
14888   // consecutive, non-overlapping, and in the right order.
14889   SmallVector<SDValue, 16> Elts;
14890   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
14891     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
14892
14893   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
14894 }
14895
14896 /// PerformTruncateCombine - Converts truncate operation to
14897 /// a sequence of vector shuffle operations.
14898 /// It is possible when we truncate 256-bit vector to 128-bit vector
14899 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
14900                                       TargetLowering::DAGCombinerInfo &DCI,
14901                                       const X86Subtarget *Subtarget)  {
14902   return SDValue();
14903 }
14904
14905 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
14906 /// specific shuffle of a load can be folded into a single element load.
14907 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
14908 /// shuffles have been customed lowered so we need to handle those here.
14909 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
14910                                          TargetLowering::DAGCombinerInfo &DCI) {
14911   if (DCI.isBeforeLegalizeOps())
14912     return SDValue();
14913
14914   SDValue InVec = N->getOperand(0);
14915   SDValue EltNo = N->getOperand(1);
14916
14917   if (!isa<ConstantSDNode>(EltNo))
14918     return SDValue();
14919
14920   EVT VT = InVec.getValueType();
14921
14922   bool HasShuffleIntoBitcast = false;
14923   if (InVec.getOpcode() == ISD::BITCAST) {
14924     // Don't duplicate a load with other uses.
14925     if (!InVec.hasOneUse())
14926       return SDValue();
14927     EVT BCVT = InVec.getOperand(0).getValueType();
14928     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
14929       return SDValue();
14930     InVec = InVec.getOperand(0);
14931     HasShuffleIntoBitcast = true;
14932   }
14933
14934   if (!isTargetShuffle(InVec.getOpcode()))
14935     return SDValue();
14936
14937   // Don't duplicate a load with other uses.
14938   if (!InVec.hasOneUse())
14939     return SDValue();
14940
14941   SmallVector<int, 16> ShuffleMask;
14942   bool UnaryShuffle;
14943   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
14944                             UnaryShuffle))
14945     return SDValue();
14946
14947   // Select the input vector, guarding against out of range extract vector.
14948   unsigned NumElems = VT.getVectorNumElements();
14949   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
14950   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
14951   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
14952                                          : InVec.getOperand(1);
14953
14954   // If inputs to shuffle are the same for both ops, then allow 2 uses
14955   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
14956
14957   if (LdNode.getOpcode() == ISD::BITCAST) {
14958     // Don't duplicate a load with other uses.
14959     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
14960       return SDValue();
14961
14962     AllowedUses = 1; // only allow 1 load use if we have a bitcast
14963     LdNode = LdNode.getOperand(0);
14964   }
14965
14966   if (!ISD::isNormalLoad(LdNode.getNode()))
14967     return SDValue();
14968
14969   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
14970
14971   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
14972     return SDValue();
14973
14974   if (HasShuffleIntoBitcast) {
14975     // If there's a bitcast before the shuffle, check if the load type and
14976     // alignment is valid.
14977     unsigned Align = LN0->getAlignment();
14978     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14979     unsigned NewAlign = TLI.getDataLayout()->
14980       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
14981
14982     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
14983       return SDValue();
14984   }
14985
14986   // All checks match so transform back to vector_shuffle so that DAG combiner
14987   // can finish the job
14988   DebugLoc dl = N->getDebugLoc();
14989
14990   // Create shuffle node taking into account the case that its a unary shuffle
14991   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
14992   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
14993                                  InVec.getOperand(0), Shuffle,
14994                                  &ShuffleMask[0]);
14995   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
14996   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
14997                      EltNo);
14998 }
14999
15000 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15001 /// generation and convert it from being a bunch of shuffles and extracts
15002 /// to a simple store and scalar loads to extract the elements.
15003 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15004                                          TargetLowering::DAGCombinerInfo &DCI) {
15005   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15006   if (NewOp.getNode())
15007     return NewOp;
15008
15009   SDValue InputVector = N->getOperand(0);
15010   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15011   // from mmx to v2i32 has a single usage.
15012   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15013       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15014       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15015     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15016                        N->getValueType(0),
15017                        InputVector.getNode()->getOperand(0));
15018
15019   // Only operate on vectors of 4 elements, where the alternative shuffling
15020   // gets to be more expensive.
15021   if (InputVector.getValueType() != MVT::v4i32)
15022     return SDValue();
15023
15024   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15025   // single use which is a sign-extend or zero-extend, and all elements are
15026   // used.
15027   SmallVector<SDNode *, 4> Uses;
15028   unsigned ExtractedElements = 0;
15029   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15030        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15031     if (UI.getUse().getResNo() != InputVector.getResNo())
15032       return SDValue();
15033
15034     SDNode *Extract = *UI;
15035     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15036       return SDValue();
15037
15038     if (Extract->getValueType(0) != MVT::i32)
15039       return SDValue();
15040     if (!Extract->hasOneUse())
15041       return SDValue();
15042     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15043         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15044       return SDValue();
15045     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15046       return SDValue();
15047
15048     // Record which element was extracted.
15049     ExtractedElements |=
15050       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15051
15052     Uses.push_back(Extract);
15053   }
15054
15055   // If not all the elements were used, this may not be worthwhile.
15056   if (ExtractedElements != 15)
15057     return SDValue();
15058
15059   // Ok, we've now decided to do the transformation.
15060   DebugLoc dl = InputVector.getDebugLoc();
15061
15062   // Store the value to a temporary stack slot.
15063   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15064   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15065                             MachinePointerInfo(), false, false, 0);
15066
15067   // Replace each use (extract) with a load of the appropriate element.
15068   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15069        UE = Uses.end(); UI != UE; ++UI) {
15070     SDNode *Extract = *UI;
15071
15072     // cOMpute the element's address.
15073     SDValue Idx = Extract->getOperand(1);
15074     unsigned EltSize =
15075         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15076     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15077     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15078     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15079
15080     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15081                                      StackPtr, OffsetVal);
15082
15083     // Load the scalar.
15084     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15085                                      ScalarAddr, MachinePointerInfo(),
15086                                      false, false, false, 0);
15087
15088     // Replace the exact with the load.
15089     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15090   }
15091
15092   // The replacement was made in place; don't return anything.
15093   return SDValue();
15094 }
15095
15096 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15097 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15098                                    SDValue RHS, SelectionDAG &DAG,
15099                                    const X86Subtarget *Subtarget) {
15100   if (!VT.isVector())
15101     return 0;
15102
15103   switch (VT.getSimpleVT().SimpleTy) {
15104   default: return 0;
15105   case MVT::v32i8:
15106   case MVT::v16i16:
15107   case MVT::v8i32:
15108     if (!Subtarget->hasAVX2())
15109       return 0;
15110   case MVT::v16i8:
15111   case MVT::v8i16:
15112   case MVT::v4i32:
15113     if (!Subtarget->hasSSE2())
15114       return 0;
15115   }
15116
15117   // SSE2 has only a small subset of the operations.
15118   bool hasUnsigned = Subtarget->hasSSE41() ||
15119                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15120   bool hasSigned = Subtarget->hasSSE41() ||
15121                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15122
15123   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15124
15125   // Check for x CC y ? x : y.
15126   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15127       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15128     switch (CC) {
15129     default: break;
15130     case ISD::SETULT:
15131     case ISD::SETULE:
15132       return hasUnsigned ? X86ISD::UMIN : 0;
15133     case ISD::SETUGT:
15134     case ISD::SETUGE:
15135       return hasUnsigned ? X86ISD::UMAX : 0;
15136     case ISD::SETLT:
15137     case ISD::SETLE:
15138       return hasSigned ? X86ISD::SMIN : 0;
15139     case ISD::SETGT:
15140     case ISD::SETGE:
15141       return hasSigned ? X86ISD::SMAX : 0;
15142     }
15143   // Check for x CC y ? y : x -- a min/max with reversed arms.
15144   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15145              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15146     switch (CC) {
15147     default: break;
15148     case ISD::SETULT:
15149     case ISD::SETULE:
15150       return hasUnsigned ? X86ISD::UMAX : 0;
15151     case ISD::SETUGT:
15152     case ISD::SETUGE:
15153       return hasUnsigned ? X86ISD::UMIN : 0;
15154     case ISD::SETLT:
15155     case ISD::SETLE:
15156       return hasSigned ? X86ISD::SMAX : 0;
15157     case ISD::SETGT:
15158     case ISD::SETGE:
15159       return hasSigned ? X86ISD::SMIN : 0;
15160     }
15161   }
15162
15163   return 0;
15164 }
15165
15166 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15167 /// nodes.
15168 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15169                                     TargetLowering::DAGCombinerInfo &DCI,
15170                                     const X86Subtarget *Subtarget) {
15171   DebugLoc DL = N->getDebugLoc();
15172   SDValue Cond = N->getOperand(0);
15173   // Get the LHS/RHS of the select.
15174   SDValue LHS = N->getOperand(1);
15175   SDValue RHS = N->getOperand(2);
15176   EVT VT = LHS.getValueType();
15177
15178   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15179   // instructions match the semantics of the common C idiom x<y?x:y but not
15180   // x<=y?x:y, because of how they handle negative zero (which can be
15181   // ignored in unsafe-math mode).
15182   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15183       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15184       (Subtarget->hasSSE2() ||
15185        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15186     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15187
15188     unsigned Opcode = 0;
15189     // Check for x CC y ? x : y.
15190     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15191         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15192       switch (CC) {
15193       default: break;
15194       case ISD::SETULT:
15195         // Converting this to a min would handle NaNs incorrectly, and swapping
15196         // the operands would cause it to handle comparisons between positive
15197         // and negative zero incorrectly.
15198         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15199           if (!DAG.getTarget().Options.UnsafeFPMath &&
15200               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15201             break;
15202           std::swap(LHS, RHS);
15203         }
15204         Opcode = X86ISD::FMIN;
15205         break;
15206       case ISD::SETOLE:
15207         // Converting this to a min would handle comparisons between positive
15208         // and negative zero incorrectly.
15209         if (!DAG.getTarget().Options.UnsafeFPMath &&
15210             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15211           break;
15212         Opcode = X86ISD::FMIN;
15213         break;
15214       case ISD::SETULE:
15215         // Converting this to a min would handle both negative zeros and NaNs
15216         // incorrectly, but we can swap the operands to fix both.
15217         std::swap(LHS, RHS);
15218       case ISD::SETOLT:
15219       case ISD::SETLT:
15220       case ISD::SETLE:
15221         Opcode = X86ISD::FMIN;
15222         break;
15223
15224       case ISD::SETOGE:
15225         // Converting this to a max would handle comparisons between positive
15226         // and negative zero incorrectly.
15227         if (!DAG.getTarget().Options.UnsafeFPMath &&
15228             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15229           break;
15230         Opcode = X86ISD::FMAX;
15231         break;
15232       case ISD::SETUGT:
15233         // Converting this to a max would handle NaNs incorrectly, and swapping
15234         // the operands would cause it to handle comparisons between positive
15235         // and negative zero incorrectly.
15236         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15237           if (!DAG.getTarget().Options.UnsafeFPMath &&
15238               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15239             break;
15240           std::swap(LHS, RHS);
15241         }
15242         Opcode = X86ISD::FMAX;
15243         break;
15244       case ISD::SETUGE:
15245         // Converting this to a max would handle both negative zeros and NaNs
15246         // incorrectly, but we can swap the operands to fix both.
15247         std::swap(LHS, RHS);
15248       case ISD::SETOGT:
15249       case ISD::SETGT:
15250       case ISD::SETGE:
15251         Opcode = X86ISD::FMAX;
15252         break;
15253       }
15254     // Check for x CC y ? y : x -- a min/max with reversed arms.
15255     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15256                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15257       switch (CC) {
15258       default: break;
15259       case ISD::SETOGE:
15260         // Converting this to a min would handle comparisons between positive
15261         // and negative zero incorrectly, and swapping the operands would
15262         // cause it to handle NaNs incorrectly.
15263         if (!DAG.getTarget().Options.UnsafeFPMath &&
15264             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15265           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15266             break;
15267           std::swap(LHS, RHS);
15268         }
15269         Opcode = X86ISD::FMIN;
15270         break;
15271       case ISD::SETUGT:
15272         // Converting this to a min would handle NaNs incorrectly.
15273         if (!DAG.getTarget().Options.UnsafeFPMath &&
15274             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15275           break;
15276         Opcode = X86ISD::FMIN;
15277         break;
15278       case ISD::SETUGE:
15279         // Converting this to a min would handle both negative zeros and NaNs
15280         // incorrectly, but we can swap the operands to fix both.
15281         std::swap(LHS, RHS);
15282       case ISD::SETOGT:
15283       case ISD::SETGT:
15284       case ISD::SETGE:
15285         Opcode = X86ISD::FMIN;
15286         break;
15287
15288       case ISD::SETULT:
15289         // Converting this to a max would handle NaNs incorrectly.
15290         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15291           break;
15292         Opcode = X86ISD::FMAX;
15293         break;
15294       case ISD::SETOLE:
15295         // Converting this to a max would handle comparisons between positive
15296         // and negative zero incorrectly, and swapping the operands would
15297         // cause it to handle NaNs incorrectly.
15298         if (!DAG.getTarget().Options.UnsafeFPMath &&
15299             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15300           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15301             break;
15302           std::swap(LHS, RHS);
15303         }
15304         Opcode = X86ISD::FMAX;
15305         break;
15306       case ISD::SETULE:
15307         // Converting this to a max would handle both negative zeros and NaNs
15308         // incorrectly, but we can swap the operands to fix both.
15309         std::swap(LHS, RHS);
15310       case ISD::SETOLT:
15311       case ISD::SETLT:
15312       case ISD::SETLE:
15313         Opcode = X86ISD::FMAX;
15314         break;
15315       }
15316     }
15317
15318     if (Opcode)
15319       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15320   }
15321
15322   // If this is a select between two integer constants, try to do some
15323   // optimizations.
15324   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15325     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15326       // Don't do this for crazy integer types.
15327       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15328         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15329         // so that TrueC (the true value) is larger than FalseC.
15330         bool NeedsCondInvert = false;
15331
15332         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15333             // Efficiently invertible.
15334             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15335              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15336               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15337           NeedsCondInvert = true;
15338           std::swap(TrueC, FalseC);
15339         }
15340
15341         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15342         if (FalseC->getAPIntValue() == 0 &&
15343             TrueC->getAPIntValue().isPowerOf2()) {
15344           if (NeedsCondInvert) // Invert the condition if needed.
15345             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15346                                DAG.getConstant(1, Cond.getValueType()));
15347
15348           // Zero extend the condition if needed.
15349           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15350
15351           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15352           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15353                              DAG.getConstant(ShAmt, MVT::i8));
15354         }
15355
15356         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15357         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15358           if (NeedsCondInvert) // Invert the condition if needed.
15359             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15360                                DAG.getConstant(1, Cond.getValueType()));
15361
15362           // Zero extend the condition if needed.
15363           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15364                              FalseC->getValueType(0), Cond);
15365           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15366                              SDValue(FalseC, 0));
15367         }
15368
15369         // Optimize cases that will turn into an LEA instruction.  This requires
15370         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15371         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15372           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15373           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15374
15375           bool isFastMultiplier = false;
15376           if (Diff < 10) {
15377             switch ((unsigned char)Diff) {
15378               default: break;
15379               case 1:  // result = add base, cond
15380               case 2:  // result = lea base(    , cond*2)
15381               case 3:  // result = lea base(cond, cond*2)
15382               case 4:  // result = lea base(    , cond*4)
15383               case 5:  // result = lea base(cond, cond*4)
15384               case 8:  // result = lea base(    , cond*8)
15385               case 9:  // result = lea base(cond, cond*8)
15386                 isFastMultiplier = true;
15387                 break;
15388             }
15389           }
15390
15391           if (isFastMultiplier) {
15392             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15393             if (NeedsCondInvert) // Invert the condition if needed.
15394               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15395                                  DAG.getConstant(1, Cond.getValueType()));
15396
15397             // Zero extend the condition if needed.
15398             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15399                                Cond);
15400             // Scale the condition by the difference.
15401             if (Diff != 1)
15402               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15403                                  DAG.getConstant(Diff, Cond.getValueType()));
15404
15405             // Add the base if non-zero.
15406             if (FalseC->getAPIntValue() != 0)
15407               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15408                                  SDValue(FalseC, 0));
15409             return Cond;
15410           }
15411         }
15412       }
15413   }
15414
15415   // Canonicalize max and min:
15416   // (x > y) ? x : y -> (x >= y) ? x : y
15417   // (x < y) ? x : y -> (x <= y) ? x : y
15418   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15419   // the need for an extra compare
15420   // against zero. e.g.
15421   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15422   // subl   %esi, %edi
15423   // testl  %edi, %edi
15424   // movl   $0, %eax
15425   // cmovgl %edi, %eax
15426   // =>
15427   // xorl   %eax, %eax
15428   // subl   %esi, $edi
15429   // cmovsl %eax, %edi
15430   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15431       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15432       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15433     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15434     switch (CC) {
15435     default: break;
15436     case ISD::SETLT:
15437     case ISD::SETGT: {
15438       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15439       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15440                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15441       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15442     }
15443     }
15444   }
15445
15446   // Match VSELECTs into subs with unsigned saturation.
15447   if (!DCI.isBeforeLegalize() &&
15448       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15449       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15450       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15451        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15452     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15453
15454     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15455     // left side invert the predicate to simplify logic below.
15456     SDValue Other;
15457     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15458       Other = RHS;
15459       CC = ISD::getSetCCInverse(CC, true);
15460     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15461       Other = LHS;
15462     }
15463
15464     if (Other.getNode() && Other->getNumOperands() == 2 &&
15465         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15466       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15467       SDValue CondRHS = Cond->getOperand(1);
15468
15469       // Look for a general sub with unsigned saturation first.
15470       // x >= y ? x-y : 0 --> subus x, y
15471       // x >  y ? x-y : 0 --> subus x, y
15472       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15473           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15474         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15475
15476       // If the RHS is a constant we have to reverse the const canonicalization.
15477       // x > C-1 ? x+-C : 0 --> subus x, C
15478       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15479           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15480         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15481         if (CondRHS.getConstantOperandVal(0) == -A-1)
15482           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15483                              DAG.getConstant(-A, VT));
15484       }
15485
15486       // Another special case: If C was a sign bit, the sub has been
15487       // canonicalized into a xor.
15488       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15489       //        it's safe to decanonicalize the xor?
15490       // x s< 0 ? x^C : 0 --> subus x, C
15491       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15492           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15493           isSplatVector(OpRHS.getNode())) {
15494         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15495         if (A.isSignBit())
15496           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15497       }
15498     }
15499   }
15500
15501   // Try to match a min/max vector operation.
15502   if (!DCI.isBeforeLegalize() &&
15503       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15504     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15505       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15506
15507   // If we know that this node is legal then we know that it is going to be
15508   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15509   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15510   // to simplify previous instructions.
15511   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15512   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15513       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15514     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15515
15516     // Don't optimize vector selects that map to mask-registers.
15517     if (BitWidth == 1)
15518       return SDValue();
15519
15520     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15521     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15522
15523     APInt KnownZero, KnownOne;
15524     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15525                                           DCI.isBeforeLegalizeOps());
15526     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15527         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15528       DCI.CommitTargetLoweringOpt(TLO);
15529   }
15530
15531   return SDValue();
15532 }
15533
15534 // Check whether a boolean test is testing a boolean value generated by
15535 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15536 // code.
15537 //
15538 // Simplify the following patterns:
15539 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15540 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15541 // to (Op EFLAGS Cond)
15542 //
15543 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15544 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15545 // to (Op EFLAGS !Cond)
15546 //
15547 // where Op could be BRCOND or CMOV.
15548 //
15549 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15550   // Quit if not CMP and SUB with its value result used.
15551   if (Cmp.getOpcode() != X86ISD::CMP &&
15552       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15553       return SDValue();
15554
15555   // Quit if not used as a boolean value.
15556   if (CC != X86::COND_E && CC != X86::COND_NE)
15557     return SDValue();
15558
15559   // Check CMP operands. One of them should be 0 or 1 and the other should be
15560   // an SetCC or extended from it.
15561   SDValue Op1 = Cmp.getOperand(0);
15562   SDValue Op2 = Cmp.getOperand(1);
15563
15564   SDValue SetCC;
15565   const ConstantSDNode* C = 0;
15566   bool needOppositeCond = (CC == X86::COND_E);
15567
15568   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15569     SetCC = Op2;
15570   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15571     SetCC = Op1;
15572   else // Quit if all operands are not constants.
15573     return SDValue();
15574
15575   if (C->getZExtValue() == 1)
15576     needOppositeCond = !needOppositeCond;
15577   else if (C->getZExtValue() != 0)
15578     // Quit if the constant is neither 0 or 1.
15579     return SDValue();
15580
15581   // Skip 'zext' node.
15582   if (SetCC.getOpcode() == ISD::ZERO_EXTEND)
15583     SetCC = SetCC.getOperand(0);
15584
15585   switch (SetCC.getOpcode()) {
15586   case X86ISD::SETCC:
15587     // Set the condition code or opposite one if necessary.
15588     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15589     if (needOppositeCond)
15590       CC = X86::GetOppositeBranchCondition(CC);
15591     return SetCC.getOperand(1);
15592   case X86ISD::CMOV: {
15593     // Check whether false/true value has canonical one, i.e. 0 or 1.
15594     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15595     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15596     // Quit if true value is not a constant.
15597     if (!TVal)
15598       return SDValue();
15599     // Quit if false value is not a constant.
15600     if (!FVal) {
15601       // A special case for rdrand, where 0 is set if false cond is found.
15602       SDValue Op = SetCC.getOperand(0);
15603       if (Op.getOpcode() != X86ISD::RDRAND)
15604         return SDValue();
15605     }
15606     // Quit if false value is not the constant 0 or 1.
15607     bool FValIsFalse = true;
15608     if (FVal && FVal->getZExtValue() != 0) {
15609       if (FVal->getZExtValue() != 1)
15610         return SDValue();
15611       // If FVal is 1, opposite cond is needed.
15612       needOppositeCond = !needOppositeCond;
15613       FValIsFalse = false;
15614     }
15615     // Quit if TVal is not the constant opposite of FVal.
15616     if (FValIsFalse && TVal->getZExtValue() != 1)
15617       return SDValue();
15618     if (!FValIsFalse && TVal->getZExtValue() != 0)
15619       return SDValue();
15620     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15621     if (needOppositeCond)
15622       CC = X86::GetOppositeBranchCondition(CC);
15623     return SetCC.getOperand(3);
15624   }
15625   }
15626
15627   return SDValue();
15628 }
15629
15630 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15631 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
15632                                   TargetLowering::DAGCombinerInfo &DCI,
15633                                   const X86Subtarget *Subtarget) {
15634   DebugLoc DL = N->getDebugLoc();
15635
15636   // If the flag operand isn't dead, don't touch this CMOV.
15637   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
15638     return SDValue();
15639
15640   SDValue FalseOp = N->getOperand(0);
15641   SDValue TrueOp = N->getOperand(1);
15642   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
15643   SDValue Cond = N->getOperand(3);
15644
15645   if (CC == X86::COND_E || CC == X86::COND_NE) {
15646     switch (Cond.getOpcode()) {
15647     default: break;
15648     case X86ISD::BSR:
15649     case X86ISD::BSF:
15650       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
15651       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
15652         return (CC == X86::COND_E) ? FalseOp : TrueOp;
15653     }
15654   }
15655
15656   SDValue Flags;
15657
15658   Flags = checkBoolTestSetCCCombine(Cond, CC);
15659   if (Flags.getNode() &&
15660       // Extra check as FCMOV only supports a subset of X86 cond.
15661       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
15662     SDValue Ops[] = { FalseOp, TrueOp,
15663                       DAG.getConstant(CC, MVT::i8), Flags };
15664     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
15665                        Ops, array_lengthof(Ops));
15666   }
15667
15668   // If this is a select between two integer constants, try to do some
15669   // optimizations.  Note that the operands are ordered the opposite of SELECT
15670   // operands.
15671   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
15672     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
15673       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
15674       // larger than FalseC (the false value).
15675       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
15676         CC = X86::GetOppositeBranchCondition(CC);
15677         std::swap(TrueC, FalseC);
15678         std::swap(TrueOp, FalseOp);
15679       }
15680
15681       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
15682       // This is efficient for any integer data type (including i8/i16) and
15683       // shift amount.
15684       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
15685         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15686                            DAG.getConstant(CC, MVT::i8), Cond);
15687
15688         // Zero extend the condition if needed.
15689         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
15690
15691         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15692         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
15693                            DAG.getConstant(ShAmt, MVT::i8));
15694         if (N->getNumValues() == 2)  // Dead flag value?
15695           return DCI.CombineTo(N, Cond, SDValue());
15696         return Cond;
15697       }
15698
15699       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
15700       // for any integer data type, including i8/i16.
15701       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15702         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15703                            DAG.getConstant(CC, MVT::i8), Cond);
15704
15705         // Zero extend the condition if needed.
15706         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15707                            FalseC->getValueType(0), Cond);
15708         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15709                            SDValue(FalseC, 0));
15710
15711         if (N->getNumValues() == 2)  // Dead flag value?
15712           return DCI.CombineTo(N, Cond, SDValue());
15713         return Cond;
15714       }
15715
15716       // Optimize cases that will turn into an LEA instruction.  This requires
15717       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15718       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15719         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15720         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15721
15722         bool isFastMultiplier = false;
15723         if (Diff < 10) {
15724           switch ((unsigned char)Diff) {
15725           default: break;
15726           case 1:  // result = add base, cond
15727           case 2:  // result = lea base(    , cond*2)
15728           case 3:  // result = lea base(cond, cond*2)
15729           case 4:  // result = lea base(    , cond*4)
15730           case 5:  // result = lea base(cond, cond*4)
15731           case 8:  // result = lea base(    , cond*8)
15732           case 9:  // result = lea base(cond, cond*8)
15733             isFastMultiplier = true;
15734             break;
15735           }
15736         }
15737
15738         if (isFastMultiplier) {
15739           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15740           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15741                              DAG.getConstant(CC, MVT::i8), Cond);
15742           // Zero extend the condition if needed.
15743           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15744                              Cond);
15745           // Scale the condition by the difference.
15746           if (Diff != 1)
15747             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15748                                DAG.getConstant(Diff, Cond.getValueType()));
15749
15750           // Add the base if non-zero.
15751           if (FalseC->getAPIntValue() != 0)
15752             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15753                                SDValue(FalseC, 0));
15754           if (N->getNumValues() == 2)  // Dead flag value?
15755             return DCI.CombineTo(N, Cond, SDValue());
15756           return Cond;
15757         }
15758       }
15759     }
15760   }
15761
15762   // Handle these cases:
15763   //   (select (x != c), e, c) -> select (x != c), e, x),
15764   //   (select (x == c), c, e) -> select (x == c), x, e)
15765   // where the c is an integer constant, and the "select" is the combination
15766   // of CMOV and CMP.
15767   //
15768   // The rationale for this change is that the conditional-move from a constant
15769   // needs two instructions, however, conditional-move from a register needs
15770   // only one instruction.
15771   //
15772   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
15773   //  some instruction-combining opportunities. This opt needs to be
15774   //  postponed as late as possible.
15775   //
15776   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
15777     // the DCI.xxxx conditions are provided to postpone the optimization as
15778     // late as possible.
15779
15780     ConstantSDNode *CmpAgainst = 0;
15781     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
15782         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
15783         !isa<ConstantSDNode>(Cond.getOperand(0))) {
15784
15785       if (CC == X86::COND_NE &&
15786           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
15787         CC = X86::GetOppositeBranchCondition(CC);
15788         std::swap(TrueOp, FalseOp);
15789       }
15790
15791       if (CC == X86::COND_E &&
15792           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
15793         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
15794                           DAG.getConstant(CC, MVT::i8), Cond };
15795         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
15796                            array_lengthof(Ops));
15797       }
15798     }
15799   }
15800
15801   return SDValue();
15802 }
15803
15804 /// PerformMulCombine - Optimize a single multiply with constant into two
15805 /// in order to implement it with two cheaper instructions, e.g.
15806 /// LEA + SHL, LEA + LEA.
15807 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
15808                                  TargetLowering::DAGCombinerInfo &DCI) {
15809   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15810     return SDValue();
15811
15812   EVT VT = N->getValueType(0);
15813   if (VT != MVT::i64)
15814     return SDValue();
15815
15816   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
15817   if (!C)
15818     return SDValue();
15819   uint64_t MulAmt = C->getZExtValue();
15820   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
15821     return SDValue();
15822
15823   uint64_t MulAmt1 = 0;
15824   uint64_t MulAmt2 = 0;
15825   if ((MulAmt % 9) == 0) {
15826     MulAmt1 = 9;
15827     MulAmt2 = MulAmt / 9;
15828   } else if ((MulAmt % 5) == 0) {
15829     MulAmt1 = 5;
15830     MulAmt2 = MulAmt / 5;
15831   } else if ((MulAmt % 3) == 0) {
15832     MulAmt1 = 3;
15833     MulAmt2 = MulAmt / 3;
15834   }
15835   if (MulAmt2 &&
15836       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
15837     DebugLoc DL = N->getDebugLoc();
15838
15839     if (isPowerOf2_64(MulAmt2) &&
15840         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
15841       // If second multiplifer is pow2, issue it first. We want the multiply by
15842       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
15843       // is an add.
15844       std::swap(MulAmt1, MulAmt2);
15845
15846     SDValue NewMul;
15847     if (isPowerOf2_64(MulAmt1))
15848       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15849                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
15850     else
15851       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
15852                            DAG.getConstant(MulAmt1, VT));
15853
15854     if (isPowerOf2_64(MulAmt2))
15855       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
15856                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
15857     else
15858       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
15859                            DAG.getConstant(MulAmt2, VT));
15860
15861     // Do not add new nodes to DAG combiner worklist.
15862     DCI.CombineTo(N, NewMul, false);
15863   }
15864   return SDValue();
15865 }
15866
15867 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
15868   SDValue N0 = N->getOperand(0);
15869   SDValue N1 = N->getOperand(1);
15870   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
15871   EVT VT = N0.getValueType();
15872
15873   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
15874   // since the result of setcc_c is all zero's or all ones.
15875   if (VT.isInteger() && !VT.isVector() &&
15876       N1C && N0.getOpcode() == ISD::AND &&
15877       N0.getOperand(1).getOpcode() == ISD::Constant) {
15878     SDValue N00 = N0.getOperand(0);
15879     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
15880         ((N00.getOpcode() == ISD::ANY_EXTEND ||
15881           N00.getOpcode() == ISD::ZERO_EXTEND) &&
15882          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
15883       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
15884       APInt ShAmt = N1C->getAPIntValue();
15885       Mask = Mask.shl(ShAmt);
15886       if (Mask != 0)
15887         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
15888                            N00, DAG.getConstant(Mask, VT));
15889     }
15890   }
15891
15892   // Hardware support for vector shifts is sparse which makes us scalarize the
15893   // vector operations in many cases. Also, on sandybridge ADD is faster than
15894   // shl.
15895   // (shl V, 1) -> add V,V
15896   if (isSplatVector(N1.getNode())) {
15897     assert(N0.getValueType().isVector() && "Invalid vector shift type");
15898     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
15899     // We shift all of the values by one. In many cases we do not have
15900     // hardware support for this operation. This is better expressed as an ADD
15901     // of two values.
15902     if (N1C && (1 == N1C->getZExtValue())) {
15903       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
15904     }
15905   }
15906
15907   return SDValue();
15908 }
15909
15910 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
15911 ///                       when possible.
15912 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
15913                                    TargetLowering::DAGCombinerInfo &DCI,
15914                                    const X86Subtarget *Subtarget) {
15915   EVT VT = N->getValueType(0);
15916   if (N->getOpcode() == ISD::SHL) {
15917     SDValue V = PerformSHLCombine(N, DAG);
15918     if (V.getNode()) return V;
15919   }
15920
15921   // On X86 with SSE2 support, we can transform this to a vector shift if
15922   // all elements are shifted by the same amount.  We can't do this in legalize
15923   // because the a constant vector is typically transformed to a constant pool
15924   // so we have no knowledge of the shift amount.
15925   if (!Subtarget->hasSSE2())
15926     return SDValue();
15927
15928   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
15929       (!Subtarget->hasInt256() ||
15930        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
15931     return SDValue();
15932
15933   SDValue ShAmtOp = N->getOperand(1);
15934   EVT EltVT = VT.getVectorElementType();
15935   DebugLoc DL = N->getDebugLoc();
15936   SDValue BaseShAmt = SDValue();
15937   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
15938     unsigned NumElts = VT.getVectorNumElements();
15939     unsigned i = 0;
15940     for (; i != NumElts; ++i) {
15941       SDValue Arg = ShAmtOp.getOperand(i);
15942       if (Arg.getOpcode() == ISD::UNDEF) continue;
15943       BaseShAmt = Arg;
15944       break;
15945     }
15946     // Handle the case where the build_vector is all undef
15947     // FIXME: Should DAG allow this?
15948     if (i == NumElts)
15949       return SDValue();
15950
15951     for (; i != NumElts; ++i) {
15952       SDValue Arg = ShAmtOp.getOperand(i);
15953       if (Arg.getOpcode() == ISD::UNDEF) continue;
15954       if (Arg != BaseShAmt) {
15955         return SDValue();
15956       }
15957     }
15958   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
15959              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
15960     SDValue InVec = ShAmtOp.getOperand(0);
15961     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15962       unsigned NumElts = InVec.getValueType().getVectorNumElements();
15963       unsigned i = 0;
15964       for (; i != NumElts; ++i) {
15965         SDValue Arg = InVec.getOperand(i);
15966         if (Arg.getOpcode() == ISD::UNDEF) continue;
15967         BaseShAmt = Arg;
15968         break;
15969       }
15970     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15971        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15972          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
15973          if (C->getZExtValue() == SplatIdx)
15974            BaseShAmt = InVec.getOperand(1);
15975        }
15976     }
15977     if (BaseShAmt.getNode() == 0) {
15978       // Don't create instructions with illegal types after legalize
15979       // types has run.
15980       if (!DAG.getTargetLoweringInfo().isTypeLegal(EltVT) &&
15981           !DCI.isBeforeLegalize())
15982         return SDValue();
15983
15984       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
15985                               DAG.getIntPtrConstant(0));
15986     }
15987   } else
15988     return SDValue();
15989
15990   // The shift amount is an i32.
15991   if (EltVT.bitsGT(MVT::i32))
15992     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
15993   else if (EltVT.bitsLT(MVT::i32))
15994     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
15995
15996   // The shift amount is identical so we can do a vector shift.
15997   SDValue  ValOp = N->getOperand(0);
15998   switch (N->getOpcode()) {
15999   default:
16000     llvm_unreachable("Unknown shift opcode!");
16001   case ISD::SHL:
16002     switch (VT.getSimpleVT().SimpleTy) {
16003     default: return SDValue();
16004     case MVT::v2i64:
16005     case MVT::v4i32:
16006     case MVT::v8i16:
16007     case MVT::v4i64:
16008     case MVT::v8i32:
16009     case MVT::v16i16:
16010       return getTargetVShiftNode(X86ISD::VSHLI, DL, VT, ValOp, BaseShAmt, DAG);
16011     }
16012   case ISD::SRA:
16013     switch (VT.getSimpleVT().SimpleTy) {
16014     default: return SDValue();
16015     case MVT::v4i32:
16016     case MVT::v8i16:
16017     case MVT::v8i32:
16018     case MVT::v16i16:
16019       return getTargetVShiftNode(X86ISD::VSRAI, DL, VT, ValOp, BaseShAmt, DAG);
16020     }
16021   case ISD::SRL:
16022     switch (VT.getSimpleVT().SimpleTy) {
16023     default: return SDValue();
16024     case MVT::v2i64:
16025     case MVT::v4i32:
16026     case MVT::v8i16:
16027     case MVT::v4i64:
16028     case MVT::v8i32:
16029     case MVT::v16i16:
16030       return getTargetVShiftNode(X86ISD::VSRLI, DL, VT, ValOp, BaseShAmt, DAG);
16031     }
16032   }
16033 }
16034
16035 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16036 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16037 // and friends.  Likewise for OR -> CMPNEQSS.
16038 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16039                             TargetLowering::DAGCombinerInfo &DCI,
16040                             const X86Subtarget *Subtarget) {
16041   unsigned opcode;
16042
16043   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16044   // we're requiring SSE2 for both.
16045   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16046     SDValue N0 = N->getOperand(0);
16047     SDValue N1 = N->getOperand(1);
16048     SDValue CMP0 = N0->getOperand(1);
16049     SDValue CMP1 = N1->getOperand(1);
16050     DebugLoc DL = N->getDebugLoc();
16051
16052     // The SETCCs should both refer to the same CMP.
16053     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16054       return SDValue();
16055
16056     SDValue CMP00 = CMP0->getOperand(0);
16057     SDValue CMP01 = CMP0->getOperand(1);
16058     EVT     VT    = CMP00.getValueType();
16059
16060     if (VT == MVT::f32 || VT == MVT::f64) {
16061       bool ExpectingFlags = false;
16062       // Check for any users that want flags:
16063       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16064            !ExpectingFlags && UI != UE; ++UI)
16065         switch (UI->getOpcode()) {
16066         default:
16067         case ISD::BR_CC:
16068         case ISD::BRCOND:
16069         case ISD::SELECT:
16070           ExpectingFlags = true;
16071           break;
16072         case ISD::CopyToReg:
16073         case ISD::SIGN_EXTEND:
16074         case ISD::ZERO_EXTEND:
16075         case ISD::ANY_EXTEND:
16076           break;
16077         }
16078
16079       if (!ExpectingFlags) {
16080         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16081         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16082
16083         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16084           X86::CondCode tmp = cc0;
16085           cc0 = cc1;
16086           cc1 = tmp;
16087         }
16088
16089         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16090             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16091           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16092           X86ISD::NodeType NTOperator = is64BitFP ?
16093             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16094           // FIXME: need symbolic constants for these magic numbers.
16095           // See X86ATTInstPrinter.cpp:printSSECC().
16096           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16097           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16098                                               DAG.getConstant(x86cc, MVT::i8));
16099           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16100                                               OnesOrZeroesF);
16101           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16102                                       DAG.getConstant(1, MVT::i32));
16103           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16104           return OneBitOfTruth;
16105         }
16106       }
16107     }
16108   }
16109   return SDValue();
16110 }
16111
16112 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16113 /// so it can be folded inside ANDNP.
16114 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16115   EVT VT = N->getValueType(0);
16116
16117   // Match direct AllOnes for 128 and 256-bit vectors
16118   if (ISD::isBuildVectorAllOnes(N))
16119     return true;
16120
16121   // Look through a bit convert.
16122   if (N->getOpcode() == ISD::BITCAST)
16123     N = N->getOperand(0).getNode();
16124
16125   // Sometimes the operand may come from a insert_subvector building a 256-bit
16126   // allones vector
16127   if (VT.is256BitVector() &&
16128       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16129     SDValue V1 = N->getOperand(0);
16130     SDValue V2 = N->getOperand(1);
16131
16132     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16133         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16134         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16135         ISD::isBuildVectorAllOnes(V2.getNode()))
16136       return true;
16137   }
16138
16139   return false;
16140 }
16141
16142 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16143 // register. In most cases we actually compare or select YMM-sized registers
16144 // and mixing the two types creates horrible code. This method optimizes
16145 // some of the transition sequences.
16146 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16147                                  TargetLowering::DAGCombinerInfo &DCI,
16148                                  const X86Subtarget *Subtarget) {
16149   EVT VT = N->getValueType(0);
16150   if (!VT.is256BitVector())
16151     return SDValue();
16152
16153   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16154           N->getOpcode() == ISD::ZERO_EXTEND ||
16155           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16156
16157   SDValue Narrow = N->getOperand(0);
16158   EVT NarrowVT = Narrow->getValueType(0);
16159   if (!NarrowVT.is128BitVector())
16160     return SDValue();
16161
16162   if (Narrow->getOpcode() != ISD::XOR &&
16163       Narrow->getOpcode() != ISD::AND &&
16164       Narrow->getOpcode() != ISD::OR)
16165     return SDValue();
16166
16167   SDValue N0  = Narrow->getOperand(0);
16168   SDValue N1  = Narrow->getOperand(1);
16169   DebugLoc DL = Narrow->getDebugLoc();
16170
16171   // The Left side has to be a trunc.
16172   if (N0.getOpcode() != ISD::TRUNCATE)
16173     return SDValue();
16174
16175   // The type of the truncated inputs.
16176   EVT WideVT = N0->getOperand(0)->getValueType(0);
16177   if (WideVT != VT)
16178     return SDValue();
16179
16180   // The right side has to be a 'trunc' or a constant vector.
16181   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16182   bool RHSConst = (isSplatVector(N1.getNode()) &&
16183                    isa<ConstantSDNode>(N1->getOperand(0)));
16184   if (!RHSTrunc && !RHSConst)
16185     return SDValue();
16186
16187   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16188
16189   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16190     return SDValue();
16191
16192   // Set N0 and N1 to hold the inputs to the new wide operation.
16193   N0 = N0->getOperand(0);
16194   if (RHSConst) {
16195     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16196                      N1->getOperand(0));
16197     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16198     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16199   } else if (RHSTrunc) {
16200     N1 = N1->getOperand(0);
16201   }
16202
16203   // Generate the wide operation.
16204   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16205   unsigned Opcode = N->getOpcode();
16206   switch (Opcode) {
16207   case ISD::ANY_EXTEND:
16208     return Op;
16209   case ISD::ZERO_EXTEND: {
16210     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16211     APInt Mask = APInt::getAllOnesValue(InBits);
16212     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16213     return DAG.getNode(ISD::AND, DL, VT,
16214                        Op, DAG.getConstant(Mask, VT));
16215   }
16216   case ISD::SIGN_EXTEND:
16217     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16218                        Op, DAG.getValueType(NarrowVT));
16219   default:
16220     llvm_unreachable("Unexpected opcode");
16221   }
16222 }
16223
16224 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16225                                  TargetLowering::DAGCombinerInfo &DCI,
16226                                  const X86Subtarget *Subtarget) {
16227   EVT VT = N->getValueType(0);
16228   if (DCI.isBeforeLegalizeOps())
16229     return SDValue();
16230
16231   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16232   if (R.getNode())
16233     return R;
16234
16235   // Create BLSI, and BLSR instructions
16236   // BLSI is X & (-X)
16237   // BLSR is X & (X-1)
16238   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16239     SDValue N0 = N->getOperand(0);
16240     SDValue N1 = N->getOperand(1);
16241     DebugLoc DL = N->getDebugLoc();
16242
16243     // Check LHS for neg
16244     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16245         isZero(N0.getOperand(0)))
16246       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16247
16248     // Check RHS for neg
16249     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16250         isZero(N1.getOperand(0)))
16251       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16252
16253     // Check LHS for X-1
16254     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16255         isAllOnes(N0.getOperand(1)))
16256       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16257
16258     // Check RHS for X-1
16259     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16260         isAllOnes(N1.getOperand(1)))
16261       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16262
16263     return SDValue();
16264   }
16265
16266   // Want to form ANDNP nodes:
16267   // 1) In the hopes of then easily combining them with OR and AND nodes
16268   //    to form PBLEND/PSIGN.
16269   // 2) To match ANDN packed intrinsics
16270   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16271     return SDValue();
16272
16273   SDValue N0 = N->getOperand(0);
16274   SDValue N1 = N->getOperand(1);
16275   DebugLoc DL = N->getDebugLoc();
16276
16277   // Check LHS for vnot
16278   if (N0.getOpcode() == ISD::XOR &&
16279       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16280       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16281     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16282
16283   // Check RHS for vnot
16284   if (N1.getOpcode() == ISD::XOR &&
16285       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16286       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16287     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16288
16289   return SDValue();
16290 }
16291
16292 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16293                                 TargetLowering::DAGCombinerInfo &DCI,
16294                                 const X86Subtarget *Subtarget) {
16295   EVT VT = N->getValueType(0);
16296   if (DCI.isBeforeLegalizeOps())
16297     return SDValue();
16298
16299   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16300   if (R.getNode())
16301     return R;
16302
16303   SDValue N0 = N->getOperand(0);
16304   SDValue N1 = N->getOperand(1);
16305
16306   // look for psign/blend
16307   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16308     if (!Subtarget->hasSSSE3() ||
16309         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16310       return SDValue();
16311
16312     // Canonicalize pandn to RHS
16313     if (N0.getOpcode() == X86ISD::ANDNP)
16314       std::swap(N0, N1);
16315     // or (and (m, y), (pandn m, x))
16316     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16317       SDValue Mask = N1.getOperand(0);
16318       SDValue X    = N1.getOperand(1);
16319       SDValue Y;
16320       if (N0.getOperand(0) == Mask)
16321         Y = N0.getOperand(1);
16322       if (N0.getOperand(1) == Mask)
16323         Y = N0.getOperand(0);
16324
16325       // Check to see if the mask appeared in both the AND and ANDNP and
16326       if (!Y.getNode())
16327         return SDValue();
16328
16329       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16330       // Look through mask bitcast.
16331       if (Mask.getOpcode() == ISD::BITCAST)
16332         Mask = Mask.getOperand(0);
16333       if (X.getOpcode() == ISD::BITCAST)
16334         X = X.getOperand(0);
16335       if (Y.getOpcode() == ISD::BITCAST)
16336         Y = Y.getOperand(0);
16337
16338       EVT MaskVT = Mask.getValueType();
16339
16340       // Validate that the Mask operand is a vector sra node.
16341       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16342       // there is no psrai.b
16343       if (Mask.getOpcode() != X86ISD::VSRAI)
16344         return SDValue();
16345
16346       // Check that the SRA is all signbits.
16347       SDValue SraC = Mask.getOperand(1);
16348       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16349       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16350       if ((SraAmt + 1) != EltBits)
16351         return SDValue();
16352
16353       DebugLoc DL = N->getDebugLoc();
16354
16355       // Now we know we at least have a plendvb with the mask val.  See if
16356       // we can form a psignb/w/d.
16357       // psign = x.type == y.type == mask.type && y = sub(0, x);
16358       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16359           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16360           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16361         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16362                "Unsupported VT for PSIGN");
16363         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16364         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16365       }
16366       // PBLENDVB only available on SSE 4.1
16367       if (!Subtarget->hasSSE41())
16368         return SDValue();
16369
16370       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16371
16372       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16373       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16374       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16375       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16376       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16377     }
16378   }
16379
16380   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16381     return SDValue();
16382
16383   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16384   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16385     std::swap(N0, N1);
16386   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16387     return SDValue();
16388   if (!N0.hasOneUse() || !N1.hasOneUse())
16389     return SDValue();
16390
16391   SDValue ShAmt0 = N0.getOperand(1);
16392   if (ShAmt0.getValueType() != MVT::i8)
16393     return SDValue();
16394   SDValue ShAmt1 = N1.getOperand(1);
16395   if (ShAmt1.getValueType() != MVT::i8)
16396     return SDValue();
16397   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16398     ShAmt0 = ShAmt0.getOperand(0);
16399   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16400     ShAmt1 = ShAmt1.getOperand(0);
16401
16402   DebugLoc DL = N->getDebugLoc();
16403   unsigned Opc = X86ISD::SHLD;
16404   SDValue Op0 = N0.getOperand(0);
16405   SDValue Op1 = N1.getOperand(0);
16406   if (ShAmt0.getOpcode() == ISD::SUB) {
16407     Opc = X86ISD::SHRD;
16408     std::swap(Op0, Op1);
16409     std::swap(ShAmt0, ShAmt1);
16410   }
16411
16412   unsigned Bits = VT.getSizeInBits();
16413   if (ShAmt1.getOpcode() == ISD::SUB) {
16414     SDValue Sum = ShAmt1.getOperand(0);
16415     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16416       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16417       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16418         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16419       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16420         return DAG.getNode(Opc, DL, VT,
16421                            Op0, Op1,
16422                            DAG.getNode(ISD::TRUNCATE, DL,
16423                                        MVT::i8, ShAmt0));
16424     }
16425   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16426     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16427     if (ShAmt0C &&
16428         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16429       return DAG.getNode(Opc, DL, VT,
16430                          N0.getOperand(0), N1.getOperand(0),
16431                          DAG.getNode(ISD::TRUNCATE, DL,
16432                                        MVT::i8, ShAmt0));
16433   }
16434
16435   return SDValue();
16436 }
16437
16438 // Generate NEG and CMOV for integer abs.
16439 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16440   EVT VT = N->getValueType(0);
16441
16442   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16443   // 8-bit integer abs to NEG and CMOV.
16444   if (VT.isInteger() && VT.getSizeInBits() == 8)
16445     return SDValue();
16446
16447   SDValue N0 = N->getOperand(0);
16448   SDValue N1 = N->getOperand(1);
16449   DebugLoc DL = N->getDebugLoc();
16450
16451   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16452   // and change it to SUB and CMOV.
16453   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16454       N0.getOpcode() == ISD::ADD &&
16455       N0.getOperand(1) == N1 &&
16456       N1.getOpcode() == ISD::SRA &&
16457       N1.getOperand(0) == N0.getOperand(0))
16458     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16459       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16460         // Generate SUB & CMOV.
16461         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16462                                   DAG.getConstant(0, VT), N0.getOperand(0));
16463
16464         SDValue Ops[] = { N0.getOperand(0), Neg,
16465                           DAG.getConstant(X86::COND_GE, MVT::i8),
16466                           SDValue(Neg.getNode(), 1) };
16467         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16468                            Ops, array_lengthof(Ops));
16469       }
16470   return SDValue();
16471 }
16472
16473 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16474 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16475                                  TargetLowering::DAGCombinerInfo &DCI,
16476                                  const X86Subtarget *Subtarget) {
16477   EVT VT = N->getValueType(0);
16478   if (DCI.isBeforeLegalizeOps())
16479     return SDValue();
16480
16481   if (Subtarget->hasCMov()) {
16482     SDValue RV = performIntegerAbsCombine(N, DAG);
16483     if (RV.getNode())
16484       return RV;
16485   }
16486
16487   // Try forming BMI if it is available.
16488   if (!Subtarget->hasBMI())
16489     return SDValue();
16490
16491   if (VT != MVT::i32 && VT != MVT::i64)
16492     return SDValue();
16493
16494   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16495
16496   // Create BLSMSK instructions by finding X ^ (X-1)
16497   SDValue N0 = N->getOperand(0);
16498   SDValue N1 = N->getOperand(1);
16499   DebugLoc DL = N->getDebugLoc();
16500
16501   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16502       isAllOnes(N0.getOperand(1)))
16503     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16504
16505   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16506       isAllOnes(N1.getOperand(1)))
16507     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16508
16509   return SDValue();
16510 }
16511
16512 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16513 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16514                                   TargetLowering::DAGCombinerInfo &DCI,
16515                                   const X86Subtarget *Subtarget) {
16516   LoadSDNode *Ld = cast<LoadSDNode>(N);
16517   EVT RegVT = Ld->getValueType(0);
16518   EVT MemVT = Ld->getMemoryVT();
16519   DebugLoc dl = Ld->getDebugLoc();
16520   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16521   unsigned RegSz = RegVT.getSizeInBits();
16522
16523   ISD::LoadExtType Ext = Ld->getExtensionType();
16524   unsigned Alignment = Ld->getAlignment();
16525   bool IsAligned = Alignment == 0 || Alignment == MemVT.getSizeInBits()/8;
16526
16527   // On Sandybridge unaligned 256bit loads are inefficient.
16528   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16529       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16530     unsigned NumElems = RegVT.getVectorNumElements();
16531     if (NumElems < 2)
16532       return SDValue();
16533
16534     SDValue Ptr = Ld->getBasePtr();
16535     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16536
16537     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16538                                   NumElems/2);
16539     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16540                                 Ld->getPointerInfo(), Ld->isVolatile(),
16541                                 Ld->isNonTemporal(), Ld->isInvariant(),
16542                                 Alignment);
16543     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16544     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16545                                 Ld->getPointerInfo(), Ld->isVolatile(),
16546                                 Ld->isNonTemporal(), Ld->isInvariant(),
16547                                 std::max(Alignment/2U, 1U));
16548     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16549                              Load1.getValue(1),
16550                              Load2.getValue(1));
16551
16552     SDValue NewVec = DAG.getUNDEF(RegVT);
16553     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16554     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16555     return DCI.CombineTo(N, NewVec, TF, true);
16556   }
16557
16558   // If this is a vector EXT Load then attempt to optimize it using a
16559   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16560   // expansion is still better than scalar code.
16561   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16562   // emit a shuffle and a arithmetic shift.
16563   // TODO: It is possible to support ZExt by zeroing the undef values
16564   // during the shuffle phase or after the shuffle.
16565   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16566       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16567     assert(MemVT != RegVT && "Cannot extend to the same type");
16568     assert(MemVT.isVector() && "Must load a vector from memory");
16569
16570     unsigned NumElems = RegVT.getVectorNumElements();
16571     unsigned MemSz = MemVT.getSizeInBits();
16572     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16573
16574     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16575       return SDValue();
16576
16577     // All sizes must be a power of two.
16578     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16579       return SDValue();
16580
16581     // Attempt to load the original value using scalar loads.
16582     // Find the largest scalar type that divides the total loaded size.
16583     MVT SclrLoadTy = MVT::i8;
16584     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16585          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16586       MVT Tp = (MVT::SimpleValueType)tp;
16587       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16588         SclrLoadTy = Tp;
16589       }
16590     }
16591
16592     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16593     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16594         (64 <= MemSz))
16595       SclrLoadTy = MVT::f64;
16596
16597     // Calculate the number of scalar loads that we need to perform
16598     // in order to load our vector from memory.
16599     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16600     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16601       return SDValue();
16602
16603     unsigned loadRegZize = RegSz;
16604     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16605       loadRegZize /= 2;
16606
16607     // Represent our vector as a sequence of elements which are the
16608     // largest scalar that we can load.
16609     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16610       loadRegZize/SclrLoadTy.getSizeInBits());
16611
16612     // Represent the data using the same element type that is stored in
16613     // memory. In practice, we ''widen'' MemVT.
16614     EVT WideVecVT =
16615           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16616                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16617
16618     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16619       "Invalid vector type");
16620
16621     // We can't shuffle using an illegal type.
16622     if (!TLI.isTypeLegal(WideVecVT))
16623       return SDValue();
16624
16625     SmallVector<SDValue, 8> Chains;
16626     SDValue Ptr = Ld->getBasePtr();
16627     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16628                                         TLI.getPointerTy());
16629     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16630
16631     for (unsigned i = 0; i < NumLoads; ++i) {
16632       // Perform a single load.
16633       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16634                                        Ptr, Ld->getPointerInfo(),
16635                                        Ld->isVolatile(), Ld->isNonTemporal(),
16636                                        Ld->isInvariant(), Ld->getAlignment());
16637       Chains.push_back(ScalarLoad.getValue(1));
16638       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16639       // another round of DAGCombining.
16640       if (i == 0)
16641         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16642       else
16643         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16644                           ScalarLoad, DAG.getIntPtrConstant(i));
16645
16646       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16647     }
16648
16649     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16650                                Chains.size());
16651
16652     // Bitcast the loaded value to a vector of the original element type, in
16653     // the size of the target vector type.
16654     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16655     unsigned SizeRatio = RegSz/MemSz;
16656
16657     if (Ext == ISD::SEXTLOAD) {
16658       // If we have SSE4.1 we can directly emit a VSEXT node.
16659       if (Subtarget->hasSSE41()) {
16660         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16661         return DCI.CombineTo(N, Sext, TF, true);
16662       }
16663
16664       // Otherwise we'll shuffle the small elements in the high bits of the
16665       // larger type and perform an arithmetic shift. If the shift is not legal
16666       // it's better to scalarize.
16667       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16668         return SDValue();
16669
16670       // Redistribute the loaded elements into the different locations.
16671       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16672       for (unsigned i = 0; i != NumElems; ++i)
16673         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16674
16675       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16676                                            DAG.getUNDEF(WideVecVT),
16677                                            &ShuffleVec[0]);
16678
16679       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16680
16681       // Build the arithmetic shift.
16682       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16683                      MemVT.getVectorElementType().getSizeInBits();
16684       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16685                           DAG.getConstant(Amt, RegVT));
16686
16687       return DCI.CombineTo(N, Shuff, TF, true);
16688     }
16689
16690     // Redistribute the loaded elements into the different locations.
16691     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16692     for (unsigned i = 0; i != NumElems; ++i)
16693       ShuffleVec[i*SizeRatio] = i;
16694
16695     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16696                                          DAG.getUNDEF(WideVecVT),
16697                                          &ShuffleVec[0]);
16698
16699     // Bitcast to the requested type.
16700     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16701     // Replace the original load with the new sequence
16702     // and return the new chain.
16703     return DCI.CombineTo(N, Shuff, TF, true);
16704   }
16705
16706   return SDValue();
16707 }
16708
16709 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16710 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16711                                    const X86Subtarget *Subtarget) {
16712   StoreSDNode *St = cast<StoreSDNode>(N);
16713   EVT VT = St->getValue().getValueType();
16714   EVT StVT = St->getMemoryVT();
16715   DebugLoc dl = St->getDebugLoc();
16716   SDValue StoredVal = St->getOperand(1);
16717   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16718   unsigned Alignment = St->getAlignment();
16719   bool IsAligned = Alignment == 0 || Alignment == VT.getSizeInBits()/8;
16720
16721   // If we are saving a concatenation of two XMM registers, perform two stores.
16722   // On Sandy Bridge, 256-bit memory operations are executed by two
16723   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16724   // memory  operation.
16725   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16726       StVT == VT && !IsAligned) {
16727     unsigned NumElems = VT.getVectorNumElements();
16728     if (NumElems < 2)
16729       return SDValue();
16730
16731     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16732     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16733
16734     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16735     SDValue Ptr0 = St->getBasePtr();
16736     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16737
16738     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16739                                 St->getPointerInfo(), St->isVolatile(),
16740                                 St->isNonTemporal(), Alignment);
16741     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
16742                                 St->getPointerInfo(), St->isVolatile(),
16743                                 St->isNonTemporal(),
16744                                 std::max(Alignment/2U, 1U));
16745     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
16746   }
16747
16748   // Optimize trunc store (of multiple scalars) to shuffle and store.
16749   // First, pack all of the elements in one place. Next, store to memory
16750   // in fewer chunks.
16751   if (St->isTruncatingStore() && VT.isVector()) {
16752     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16753     unsigned NumElems = VT.getVectorNumElements();
16754     assert(StVT != VT && "Cannot truncate to the same type");
16755     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
16756     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
16757
16758     // From, To sizes and ElemCount must be pow of two
16759     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
16760     // We are going to use the original vector elt for storing.
16761     // Accumulated smaller vector elements must be a multiple of the store size.
16762     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
16763
16764     unsigned SizeRatio  = FromSz / ToSz;
16765
16766     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
16767
16768     // Create a type on which we perform the shuffle
16769     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
16770             StVT.getScalarType(), NumElems*SizeRatio);
16771
16772     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
16773
16774     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
16775     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16776     for (unsigned i = 0; i != NumElems; ++i)
16777       ShuffleVec[i] = i * SizeRatio;
16778
16779     // Can't shuffle using an illegal type.
16780     if (!TLI.isTypeLegal(WideVecVT))
16781       return SDValue();
16782
16783     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
16784                                          DAG.getUNDEF(WideVecVT),
16785                                          &ShuffleVec[0]);
16786     // At this point all of the data is stored at the bottom of the
16787     // register. We now need to save it to mem.
16788
16789     // Find the largest store unit
16790     MVT StoreType = MVT::i8;
16791     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16792          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16793       MVT Tp = (MVT::SimpleValueType)tp;
16794       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
16795         StoreType = Tp;
16796     }
16797
16798     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16799     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
16800         (64 <= NumElems * ToSz))
16801       StoreType = MVT::f64;
16802
16803     // Bitcast the original vector into a vector of store-size units
16804     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
16805             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
16806     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
16807     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
16808     SmallVector<SDValue, 8> Chains;
16809     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
16810                                         TLI.getPointerTy());
16811     SDValue Ptr = St->getBasePtr();
16812
16813     // Perform one or more big stores into memory.
16814     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
16815       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
16816                                    StoreType, ShuffWide,
16817                                    DAG.getIntPtrConstant(i));
16818       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
16819                                 St->getPointerInfo(), St->isVolatile(),
16820                                 St->isNonTemporal(), St->getAlignment());
16821       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16822       Chains.push_back(Ch);
16823     }
16824
16825     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16826                                Chains.size());
16827   }
16828
16829   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
16830   // the FP state in cases where an emms may be missing.
16831   // A preferable solution to the general problem is to figure out the right
16832   // places to insert EMMS.  This qualifies as a quick hack.
16833
16834   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
16835   if (VT.getSizeInBits() != 64)
16836     return SDValue();
16837
16838   const Function *F = DAG.getMachineFunction().getFunction();
16839   bool NoImplicitFloatOps = F->getAttributes().
16840     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
16841   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
16842                      && Subtarget->hasSSE2();
16843   if ((VT.isVector() ||
16844        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
16845       isa<LoadSDNode>(St->getValue()) &&
16846       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
16847       St->getChain().hasOneUse() && !St->isVolatile()) {
16848     SDNode* LdVal = St->getValue().getNode();
16849     LoadSDNode *Ld = 0;
16850     int TokenFactorIndex = -1;
16851     SmallVector<SDValue, 8> Ops;
16852     SDNode* ChainVal = St->getChain().getNode();
16853     // Must be a store of a load.  We currently handle two cases:  the load
16854     // is a direct child, and it's under an intervening TokenFactor.  It is
16855     // possible to dig deeper under nested TokenFactors.
16856     if (ChainVal == LdVal)
16857       Ld = cast<LoadSDNode>(St->getChain());
16858     else if (St->getValue().hasOneUse() &&
16859              ChainVal->getOpcode() == ISD::TokenFactor) {
16860       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
16861         if (ChainVal->getOperand(i).getNode() == LdVal) {
16862           TokenFactorIndex = i;
16863           Ld = cast<LoadSDNode>(St->getValue());
16864         } else
16865           Ops.push_back(ChainVal->getOperand(i));
16866       }
16867     }
16868
16869     if (!Ld || !ISD::isNormalLoad(Ld))
16870       return SDValue();
16871
16872     // If this is not the MMX case, i.e. we are just turning i64 load/store
16873     // into f64 load/store, avoid the transformation if there are multiple
16874     // uses of the loaded value.
16875     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
16876       return SDValue();
16877
16878     DebugLoc LdDL = Ld->getDebugLoc();
16879     DebugLoc StDL = N->getDebugLoc();
16880     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
16881     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
16882     // pair instead.
16883     if (Subtarget->is64Bit() || F64IsLegal) {
16884       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
16885       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
16886                                   Ld->getPointerInfo(), Ld->isVolatile(),
16887                                   Ld->isNonTemporal(), Ld->isInvariant(),
16888                                   Ld->getAlignment());
16889       SDValue NewChain = NewLd.getValue(1);
16890       if (TokenFactorIndex != -1) {
16891         Ops.push_back(NewChain);
16892         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16893                                Ops.size());
16894       }
16895       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
16896                           St->getPointerInfo(),
16897                           St->isVolatile(), St->isNonTemporal(),
16898                           St->getAlignment());
16899     }
16900
16901     // Otherwise, lower to two pairs of 32-bit loads / stores.
16902     SDValue LoAddr = Ld->getBasePtr();
16903     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
16904                                  DAG.getConstant(4, MVT::i32));
16905
16906     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
16907                                Ld->getPointerInfo(),
16908                                Ld->isVolatile(), Ld->isNonTemporal(),
16909                                Ld->isInvariant(), Ld->getAlignment());
16910     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
16911                                Ld->getPointerInfo().getWithOffset(4),
16912                                Ld->isVolatile(), Ld->isNonTemporal(),
16913                                Ld->isInvariant(),
16914                                MinAlign(Ld->getAlignment(), 4));
16915
16916     SDValue NewChain = LoLd.getValue(1);
16917     if (TokenFactorIndex != -1) {
16918       Ops.push_back(LoLd);
16919       Ops.push_back(HiLd);
16920       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
16921                              Ops.size());
16922     }
16923
16924     LoAddr = St->getBasePtr();
16925     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
16926                          DAG.getConstant(4, MVT::i32));
16927
16928     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
16929                                 St->getPointerInfo(),
16930                                 St->isVolatile(), St->isNonTemporal(),
16931                                 St->getAlignment());
16932     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
16933                                 St->getPointerInfo().getWithOffset(4),
16934                                 St->isVolatile(),
16935                                 St->isNonTemporal(),
16936                                 MinAlign(St->getAlignment(), 4));
16937     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
16938   }
16939   return SDValue();
16940 }
16941
16942 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
16943 /// and return the operands for the horizontal operation in LHS and RHS.  A
16944 /// horizontal operation performs the binary operation on successive elements
16945 /// of its first operand, then on successive elements of its second operand,
16946 /// returning the resulting values in a vector.  For example, if
16947 ///   A = < float a0, float a1, float a2, float a3 >
16948 /// and
16949 ///   B = < float b0, float b1, float b2, float b3 >
16950 /// then the result of doing a horizontal operation on A and B is
16951 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
16952 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
16953 /// A horizontal-op B, for some already available A and B, and if so then LHS is
16954 /// set to A, RHS to B, and the routine returns 'true'.
16955 /// Note that the binary operation should have the property that if one of the
16956 /// operands is UNDEF then the result is UNDEF.
16957 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
16958   // Look for the following pattern: if
16959   //   A = < float a0, float a1, float a2, float a3 >
16960   //   B = < float b0, float b1, float b2, float b3 >
16961   // and
16962   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
16963   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
16964   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
16965   // which is A horizontal-op B.
16966
16967   // At least one of the operands should be a vector shuffle.
16968   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
16969       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
16970     return false;
16971
16972   EVT VT = LHS.getValueType();
16973
16974   assert((VT.is128BitVector() || VT.is256BitVector()) &&
16975          "Unsupported vector type for horizontal add/sub");
16976
16977   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
16978   // operate independently on 128-bit lanes.
16979   unsigned NumElts = VT.getVectorNumElements();
16980   unsigned NumLanes = VT.getSizeInBits()/128;
16981   unsigned NumLaneElts = NumElts / NumLanes;
16982   assert((NumLaneElts % 2 == 0) &&
16983          "Vector type should have an even number of elements in each lane");
16984   unsigned HalfLaneElts = NumLaneElts/2;
16985
16986   // View LHS in the form
16987   //   LHS = VECTOR_SHUFFLE A, B, LMask
16988   // If LHS is not a shuffle then pretend it is the shuffle
16989   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
16990   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
16991   // type VT.
16992   SDValue A, B;
16993   SmallVector<int, 16> LMask(NumElts);
16994   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
16995     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
16996       A = LHS.getOperand(0);
16997     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
16998       B = LHS.getOperand(1);
16999     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17000     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17001   } else {
17002     if (LHS.getOpcode() != ISD::UNDEF)
17003       A = LHS;
17004     for (unsigned i = 0; i != NumElts; ++i)
17005       LMask[i] = i;
17006   }
17007
17008   // Likewise, view RHS in the form
17009   //   RHS = VECTOR_SHUFFLE C, D, RMask
17010   SDValue C, D;
17011   SmallVector<int, 16> RMask(NumElts);
17012   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17013     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17014       C = RHS.getOperand(0);
17015     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17016       D = RHS.getOperand(1);
17017     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17018     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17019   } else {
17020     if (RHS.getOpcode() != ISD::UNDEF)
17021       C = RHS;
17022     for (unsigned i = 0; i != NumElts; ++i)
17023       RMask[i] = i;
17024   }
17025
17026   // Check that the shuffles are both shuffling the same vectors.
17027   if (!(A == C && B == D) && !(A == D && B == C))
17028     return false;
17029
17030   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17031   if (!A.getNode() && !B.getNode())
17032     return false;
17033
17034   // If A and B occur in reverse order in RHS, then "swap" them (which means
17035   // rewriting the mask).
17036   if (A != C)
17037     CommuteVectorShuffleMask(RMask, NumElts);
17038
17039   // At this point LHS and RHS are equivalent to
17040   //   LHS = VECTOR_SHUFFLE A, B, LMask
17041   //   RHS = VECTOR_SHUFFLE A, B, RMask
17042   // Check that the masks correspond to performing a horizontal operation.
17043   for (unsigned i = 0; i != NumElts; ++i) {
17044     int LIdx = LMask[i], RIdx = RMask[i];
17045
17046     // Ignore any UNDEF components.
17047     if (LIdx < 0 || RIdx < 0 ||
17048         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17049         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17050       continue;
17051
17052     // Check that successive elements are being operated on.  If not, this is
17053     // not a horizontal operation.
17054     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17055     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17056     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17057     if (!(LIdx == Index && RIdx == Index + 1) &&
17058         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17059       return false;
17060   }
17061
17062   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17063   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17064   return true;
17065 }
17066
17067 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17068 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17069                                   const X86Subtarget *Subtarget) {
17070   EVT VT = N->getValueType(0);
17071   SDValue LHS = N->getOperand(0);
17072   SDValue RHS = N->getOperand(1);
17073
17074   // Try to synthesize horizontal adds from adds of shuffles.
17075   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17076        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17077       isHorizontalBinOp(LHS, RHS, true))
17078     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17079   return SDValue();
17080 }
17081
17082 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17083 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17084                                   const X86Subtarget *Subtarget) {
17085   EVT VT = N->getValueType(0);
17086   SDValue LHS = N->getOperand(0);
17087   SDValue RHS = N->getOperand(1);
17088
17089   // Try to synthesize horizontal subs from subs of shuffles.
17090   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17091        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17092       isHorizontalBinOp(LHS, RHS, false))
17093     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17094   return SDValue();
17095 }
17096
17097 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17098 /// X86ISD::FXOR nodes.
17099 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17100   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17101   // F[X]OR(0.0, x) -> x
17102   // F[X]OR(x, 0.0) -> x
17103   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17104     if (C->getValueAPF().isPosZero())
17105       return N->getOperand(1);
17106   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17107     if (C->getValueAPF().isPosZero())
17108       return N->getOperand(0);
17109   return SDValue();
17110 }
17111
17112 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17113 /// X86ISD::FMAX nodes.
17114 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17115   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17116
17117   // Only perform optimizations if UnsafeMath is used.
17118   if (!DAG.getTarget().Options.UnsafeFPMath)
17119     return SDValue();
17120
17121   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17122   // into FMINC and FMAXC, which are Commutative operations.
17123   unsigned NewOp = 0;
17124   switch (N->getOpcode()) {
17125     default: llvm_unreachable("unknown opcode");
17126     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17127     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17128   }
17129
17130   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17131                      N->getOperand(0), N->getOperand(1));
17132 }
17133
17134 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17135 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17136   // FAND(0.0, x) -> 0.0
17137   // FAND(x, 0.0) -> 0.0
17138   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17139     if (C->getValueAPF().isPosZero())
17140       return N->getOperand(0);
17141   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17142     if (C->getValueAPF().isPosZero())
17143       return N->getOperand(1);
17144   return SDValue();
17145 }
17146
17147 static SDValue PerformBTCombine(SDNode *N,
17148                                 SelectionDAG &DAG,
17149                                 TargetLowering::DAGCombinerInfo &DCI) {
17150   // BT ignores high bits in the bit index operand.
17151   SDValue Op1 = N->getOperand(1);
17152   if (Op1.hasOneUse()) {
17153     unsigned BitWidth = Op1.getValueSizeInBits();
17154     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17155     APInt KnownZero, KnownOne;
17156     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17157                                           !DCI.isBeforeLegalizeOps());
17158     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17159     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17160         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17161       DCI.CommitTargetLoweringOpt(TLO);
17162   }
17163   return SDValue();
17164 }
17165
17166 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17167   SDValue Op = N->getOperand(0);
17168   if (Op.getOpcode() == ISD::BITCAST)
17169     Op = Op.getOperand(0);
17170   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17171   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17172       VT.getVectorElementType().getSizeInBits() ==
17173       OpVT.getVectorElementType().getSizeInBits()) {
17174     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17175   }
17176   return SDValue();
17177 }
17178
17179 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 
17180                                                const X86Subtarget *Subtarget) {
17181   EVT VT = N->getValueType(0);
17182   if (!VT.isVector())
17183     return SDValue();
17184
17185   SDValue N0 = N->getOperand(0);
17186   SDValue N1 = N->getOperand(1);
17187   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17188   DebugLoc dl = N->getDebugLoc();
17189
17190   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17191   // both SSE and AVX2 since there is no sign-extended shift right
17192   // operation on a vector with 64-bit elements.
17193   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17194   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17195   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17196       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17197     SDValue N00 = N0.getOperand(0);
17198
17199     // EXTLOAD has a better solution on AVX2, 
17200     // it may be replaced with X86ISD::VSEXT node.
17201     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17202       if (!ISD::isNormalLoad(N00.getNode()))
17203         return SDValue();
17204
17205     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17206         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 
17207                                   N00, N1);
17208       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17209     }
17210   }
17211   return SDValue();
17212 }
17213
17214 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17215                                   TargetLowering::DAGCombinerInfo &DCI,
17216                                   const X86Subtarget *Subtarget) {
17217   if (!DCI.isBeforeLegalizeOps())
17218     return SDValue();
17219
17220   if (!Subtarget->hasFp256())
17221     return SDValue();
17222
17223   EVT VT = N->getValueType(0);
17224   if (VT.isVector() && VT.getSizeInBits() == 256) {
17225     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17226     if (R.getNode())
17227       return R;
17228   }
17229
17230   return SDValue();
17231 }
17232
17233 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17234                                  const X86Subtarget* Subtarget) {
17235   DebugLoc dl = N->getDebugLoc();
17236   EVT VT = N->getValueType(0);
17237
17238   // Let legalize expand this if it isn't a legal type yet.
17239   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17240     return SDValue();
17241
17242   EVT ScalarVT = VT.getScalarType();
17243   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17244       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17245     return SDValue();
17246
17247   SDValue A = N->getOperand(0);
17248   SDValue B = N->getOperand(1);
17249   SDValue C = N->getOperand(2);
17250
17251   bool NegA = (A.getOpcode() == ISD::FNEG);
17252   bool NegB = (B.getOpcode() == ISD::FNEG);
17253   bool NegC = (C.getOpcode() == ISD::FNEG);
17254
17255   // Negative multiplication when NegA xor NegB
17256   bool NegMul = (NegA != NegB);
17257   if (NegA)
17258     A = A.getOperand(0);
17259   if (NegB)
17260     B = B.getOperand(0);
17261   if (NegC)
17262     C = C.getOperand(0);
17263
17264   unsigned Opcode;
17265   if (!NegMul)
17266     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17267   else
17268     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17269
17270   return DAG.getNode(Opcode, dl, VT, A, B, C);
17271 }
17272
17273 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17274                                   TargetLowering::DAGCombinerInfo &DCI,
17275                                   const X86Subtarget *Subtarget) {
17276   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17277   //           (and (i32 x86isd::setcc_carry), 1)
17278   // This eliminates the zext. This transformation is necessary because
17279   // ISD::SETCC is always legalized to i8.
17280   DebugLoc dl = N->getDebugLoc();
17281   SDValue N0 = N->getOperand(0);
17282   EVT VT = N->getValueType(0);
17283
17284   if (N0.getOpcode() == ISD::AND &&
17285       N0.hasOneUse() &&
17286       N0.getOperand(0).hasOneUse()) {
17287     SDValue N00 = N0.getOperand(0);
17288     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17289       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17290       if (!C || C->getZExtValue() != 1)
17291         return SDValue();
17292       return DAG.getNode(ISD::AND, dl, VT,
17293                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17294                                      N00.getOperand(0), N00.getOperand(1)),
17295                          DAG.getConstant(1, VT));
17296     }
17297   }
17298
17299   if (VT.is256BitVector()) {
17300     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17301     if (R.getNode())
17302       return R;
17303   }
17304
17305   return SDValue();
17306 }
17307
17308 // Optimize x == -y --> x+y == 0
17309 //          x != -y --> x+y != 0
17310 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17311   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17312   SDValue LHS = N->getOperand(0);
17313   SDValue RHS = N->getOperand(1);
17314
17315   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17316     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17317       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17318         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17319                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17320         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17321                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17322       }
17323   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17324     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17325       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17326         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17327                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17328         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17329                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17330       }
17331   return SDValue();
17332 }
17333
17334 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17335 // as "sbb reg,reg", since it can be extended without zext and produces
17336 // an all-ones bit which is more useful than 0/1 in some cases.
17337 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17338   return DAG.getNode(ISD::AND, DL, MVT::i8,
17339                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17340                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17341                      DAG.getConstant(1, MVT::i8));
17342 }
17343
17344 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17345 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17346                                    TargetLowering::DAGCombinerInfo &DCI,
17347                                    const X86Subtarget *Subtarget) {
17348   DebugLoc DL = N->getDebugLoc();
17349   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17350   SDValue EFLAGS = N->getOperand(1);
17351
17352   if (CC == X86::COND_A) {
17353     // Try to convert COND_A into COND_B in an attempt to facilitate
17354     // materializing "setb reg".
17355     //
17356     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17357     // cannot take an immediate as its first operand.
17358     //
17359     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17360         EFLAGS.getValueType().isInteger() &&
17361         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17362       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17363                                    EFLAGS.getNode()->getVTList(),
17364                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17365       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17366       return MaterializeSETB(DL, NewEFLAGS, DAG);
17367     }
17368   }
17369
17370   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17371   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17372   // cases.
17373   if (CC == X86::COND_B)
17374     return MaterializeSETB(DL, EFLAGS, DAG);
17375
17376   SDValue Flags;
17377
17378   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17379   if (Flags.getNode()) {
17380     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17381     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17382   }
17383
17384   return SDValue();
17385 }
17386
17387 // Optimize branch condition evaluation.
17388 //
17389 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17390                                     TargetLowering::DAGCombinerInfo &DCI,
17391                                     const X86Subtarget *Subtarget) {
17392   DebugLoc DL = N->getDebugLoc();
17393   SDValue Chain = N->getOperand(0);
17394   SDValue Dest = N->getOperand(1);
17395   SDValue EFLAGS = N->getOperand(3);
17396   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17397
17398   SDValue Flags;
17399
17400   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17401   if (Flags.getNode()) {
17402     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17403     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17404                        Flags);
17405   }
17406
17407   return SDValue();
17408 }
17409
17410 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17411                                         const X86TargetLowering *XTLI) {
17412   SDValue Op0 = N->getOperand(0);
17413   EVT InVT = Op0->getValueType(0);
17414
17415   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17416   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17417     DebugLoc dl = N->getDebugLoc();
17418     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17419     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17420     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17421   }
17422
17423   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17424   // a 32-bit target where SSE doesn't support i64->FP operations.
17425   if (Op0.getOpcode() == ISD::LOAD) {
17426     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17427     EVT VT = Ld->getValueType(0);
17428     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17429         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17430         !XTLI->getSubtarget()->is64Bit() &&
17431         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17432       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17433                                           Ld->getChain(), Op0, DAG);
17434       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17435       return FILDChain;
17436     }
17437   }
17438   return SDValue();
17439 }
17440
17441 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17442 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17443                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17444   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17445   // the result is either zero or one (depending on the input carry bit).
17446   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17447   if (X86::isZeroNode(N->getOperand(0)) &&
17448       X86::isZeroNode(N->getOperand(1)) &&
17449       // We don't have a good way to replace an EFLAGS use, so only do this when
17450       // dead right now.
17451       SDValue(N, 1).use_empty()) {
17452     DebugLoc DL = N->getDebugLoc();
17453     EVT VT = N->getValueType(0);
17454     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17455     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17456                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17457                                            DAG.getConstant(X86::COND_B,MVT::i8),
17458                                            N->getOperand(2)),
17459                                DAG.getConstant(1, VT));
17460     return DCI.CombineTo(N, Res1, CarryOut);
17461   }
17462
17463   return SDValue();
17464 }
17465
17466 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17467 //      (add Y, (setne X, 0)) -> sbb -1, Y
17468 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17469 //      (sub (setne X, 0), Y) -> adc -1, Y
17470 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17471   DebugLoc DL = N->getDebugLoc();
17472
17473   // Look through ZExts.
17474   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17475   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17476     return SDValue();
17477
17478   SDValue SetCC = Ext.getOperand(0);
17479   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17480     return SDValue();
17481
17482   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17483   if (CC != X86::COND_E && CC != X86::COND_NE)
17484     return SDValue();
17485
17486   SDValue Cmp = SetCC.getOperand(1);
17487   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17488       !X86::isZeroNode(Cmp.getOperand(1)) ||
17489       !Cmp.getOperand(0).getValueType().isInteger())
17490     return SDValue();
17491
17492   SDValue CmpOp0 = Cmp.getOperand(0);
17493   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17494                                DAG.getConstant(1, CmpOp0.getValueType()));
17495
17496   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17497   if (CC == X86::COND_NE)
17498     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17499                        DL, OtherVal.getValueType(), OtherVal,
17500                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17501   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17502                      DL, OtherVal.getValueType(), OtherVal,
17503                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17504 }
17505
17506 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17507 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17508                                  const X86Subtarget *Subtarget) {
17509   EVT VT = N->getValueType(0);
17510   SDValue Op0 = N->getOperand(0);
17511   SDValue Op1 = N->getOperand(1);
17512
17513   // Try to synthesize horizontal adds from adds of shuffles.
17514   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17515        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17516       isHorizontalBinOp(Op0, Op1, true))
17517     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17518
17519   return OptimizeConditionalInDecrement(N, DAG);
17520 }
17521
17522 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17523                                  const X86Subtarget *Subtarget) {
17524   SDValue Op0 = N->getOperand(0);
17525   SDValue Op1 = N->getOperand(1);
17526
17527   // X86 can't encode an immediate LHS of a sub. See if we can push the
17528   // negation into a preceding instruction.
17529   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17530     // If the RHS of the sub is a XOR with one use and a constant, invert the
17531     // immediate. Then add one to the LHS of the sub so we can turn
17532     // X-Y -> X+~Y+1, saving one register.
17533     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17534         isa<ConstantSDNode>(Op1.getOperand(1))) {
17535       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17536       EVT VT = Op0.getValueType();
17537       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17538                                    Op1.getOperand(0),
17539                                    DAG.getConstant(~XorC, VT));
17540       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17541                          DAG.getConstant(C->getAPIntValue()+1, VT));
17542     }
17543   }
17544
17545   // Try to synthesize horizontal adds from adds of shuffles.
17546   EVT VT = N->getValueType(0);
17547   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17548        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17549       isHorizontalBinOp(Op0, Op1, true))
17550     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17551
17552   return OptimizeConditionalInDecrement(N, DAG);
17553 }
17554
17555 /// performVZEXTCombine - Performs build vector combines
17556 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17557                                         TargetLowering::DAGCombinerInfo &DCI,
17558                                         const X86Subtarget *Subtarget) {
17559   // (vzext (bitcast (vzext (x)) -> (vzext x)
17560   SDValue In = N->getOperand(0);
17561   while (In.getOpcode() == ISD::BITCAST)
17562     In = In.getOperand(0);
17563
17564   if (In.getOpcode() != X86ISD::VZEXT)
17565     return SDValue();
17566
17567   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17568                      In.getOperand(0));
17569 }
17570
17571 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17572                                              DAGCombinerInfo &DCI) const {
17573   SelectionDAG &DAG = DCI.DAG;
17574   switch (N->getOpcode()) {
17575   default: break;
17576   case ISD::EXTRACT_VECTOR_ELT:
17577     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17578   case ISD::VSELECT:
17579   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17580   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17581   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17582   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17583   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17584   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17585   case ISD::SHL:
17586   case ISD::SRA:
17587   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17588   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17589   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17590   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17591   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17592   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17593   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17594   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17595   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17596   case X86ISD::FXOR:
17597   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17598   case X86ISD::FMIN:
17599   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17600   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17601   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17602   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17603   case ISD::ANY_EXTEND:
17604   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17605   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17606   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17607   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17608   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17609   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17610   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17611   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17612   case X86ISD::SHUFP:       // Handle all target specific shuffles
17613   case X86ISD::PALIGNR:
17614   case X86ISD::UNPCKH:
17615   case X86ISD::UNPCKL:
17616   case X86ISD::MOVHLPS:
17617   case X86ISD::MOVLHPS:
17618   case X86ISD::PSHUFD:
17619   case X86ISD::PSHUFHW:
17620   case X86ISD::PSHUFLW:
17621   case X86ISD::MOVSS:
17622   case X86ISD::MOVSD:
17623   case X86ISD::VPERMILP:
17624   case X86ISD::VPERM2X128:
17625   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17626   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17627   }
17628
17629   return SDValue();
17630 }
17631
17632 /// isTypeDesirableForOp - Return true if the target has native support for
17633 /// the specified value type and it is 'desirable' to use the type for the
17634 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17635 /// instruction encodings are longer and some i16 instructions are slow.
17636 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17637   if (!isTypeLegal(VT))
17638     return false;
17639   if (VT != MVT::i16)
17640     return true;
17641
17642   switch (Opc) {
17643   default:
17644     return true;
17645   case ISD::LOAD:
17646   case ISD::SIGN_EXTEND:
17647   case ISD::ZERO_EXTEND:
17648   case ISD::ANY_EXTEND:
17649   case ISD::SHL:
17650   case ISD::SRL:
17651   case ISD::SUB:
17652   case ISD::ADD:
17653   case ISD::MUL:
17654   case ISD::AND:
17655   case ISD::OR:
17656   case ISD::XOR:
17657     return false;
17658   }
17659 }
17660
17661 /// IsDesirableToPromoteOp - This method query the target whether it is
17662 /// beneficial for dag combiner to promote the specified node. If true, it
17663 /// should return the desired promotion type by reference.
17664 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17665   EVT VT = Op.getValueType();
17666   if (VT != MVT::i16)
17667     return false;
17668
17669   bool Promote = false;
17670   bool Commute = false;
17671   switch (Op.getOpcode()) {
17672   default: break;
17673   case ISD::LOAD: {
17674     LoadSDNode *LD = cast<LoadSDNode>(Op);
17675     // If the non-extending load has a single use and it's not live out, then it
17676     // might be folded.
17677     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17678                                                      Op.hasOneUse()*/) {
17679       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17680              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17681         // The only case where we'd want to promote LOAD (rather then it being
17682         // promoted as an operand is when it's only use is liveout.
17683         if (UI->getOpcode() != ISD::CopyToReg)
17684           return false;
17685       }
17686     }
17687     Promote = true;
17688     break;
17689   }
17690   case ISD::SIGN_EXTEND:
17691   case ISD::ZERO_EXTEND:
17692   case ISD::ANY_EXTEND:
17693     Promote = true;
17694     break;
17695   case ISD::SHL:
17696   case ISD::SRL: {
17697     SDValue N0 = Op.getOperand(0);
17698     // Look out for (store (shl (load), x)).
17699     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17700       return false;
17701     Promote = true;
17702     break;
17703   }
17704   case ISD::ADD:
17705   case ISD::MUL:
17706   case ISD::AND:
17707   case ISD::OR:
17708   case ISD::XOR:
17709     Commute = true;
17710     // fallthrough
17711   case ISD::SUB: {
17712     SDValue N0 = Op.getOperand(0);
17713     SDValue N1 = Op.getOperand(1);
17714     if (!Commute && MayFoldLoad(N1))
17715       return false;
17716     // Avoid disabling potential load folding opportunities.
17717     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17718       return false;
17719     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17720       return false;
17721     Promote = true;
17722   }
17723   }
17724
17725   PVT = MVT::i32;
17726   return Promote;
17727 }
17728
17729 //===----------------------------------------------------------------------===//
17730 //                           X86 Inline Assembly Support
17731 //===----------------------------------------------------------------------===//
17732
17733 namespace {
17734   // Helper to match a string separated by whitespace.
17735   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17736     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17737
17738     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17739       StringRef piece(*args[i]);
17740       if (!s.startswith(piece)) // Check if the piece matches.
17741         return false;
17742
17743       s = s.substr(piece.size());
17744       StringRef::size_type pos = s.find_first_not_of(" \t");
17745       if (pos == 0) // We matched a prefix.
17746         return false;
17747
17748       s = s.substr(pos);
17749     }
17750
17751     return s.empty();
17752   }
17753   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
17754 }
17755
17756 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
17757   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
17758
17759   std::string AsmStr = IA->getAsmString();
17760
17761   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17762   if (!Ty || Ty->getBitWidth() % 16 != 0)
17763     return false;
17764
17765   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
17766   SmallVector<StringRef, 4> AsmPieces;
17767   SplitString(AsmStr, AsmPieces, ";\n");
17768
17769   switch (AsmPieces.size()) {
17770   default: return false;
17771   case 1:
17772     // FIXME: this should verify that we are targeting a 486 or better.  If not,
17773     // we will turn this bswap into something that will be lowered to logical
17774     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
17775     // lower so don't worry about this.
17776     // bswap $0
17777     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
17778         matchAsm(AsmPieces[0], "bswapl", "$0") ||
17779         matchAsm(AsmPieces[0], "bswapq", "$0") ||
17780         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
17781         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
17782         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
17783       // No need to check constraints, nothing other than the equivalent of
17784       // "=r,0" would be valid here.
17785       return IntrinsicLowering::LowerToByteSwap(CI);
17786     }
17787
17788     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
17789     if (CI->getType()->isIntegerTy(16) &&
17790         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17791         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
17792          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
17793       AsmPieces.clear();
17794       const std::string &ConstraintsStr = IA->getConstraintString();
17795       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17796       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17797       if (AsmPieces.size() == 4 &&
17798           AsmPieces[0] == "~{cc}" &&
17799           AsmPieces[1] == "~{dirflag}" &&
17800           AsmPieces[2] == "~{flags}" &&
17801           AsmPieces[3] == "~{fpsr}")
17802       return IntrinsicLowering::LowerToByteSwap(CI);
17803     }
17804     break;
17805   case 3:
17806     if (CI->getType()->isIntegerTy(32) &&
17807         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
17808         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
17809         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
17810         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
17811       AsmPieces.clear();
17812       const std::string &ConstraintsStr = IA->getConstraintString();
17813       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
17814       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
17815       if (AsmPieces.size() == 4 &&
17816           AsmPieces[0] == "~{cc}" &&
17817           AsmPieces[1] == "~{dirflag}" &&
17818           AsmPieces[2] == "~{flags}" &&
17819           AsmPieces[3] == "~{fpsr}")
17820         return IntrinsicLowering::LowerToByteSwap(CI);
17821     }
17822
17823     if (CI->getType()->isIntegerTy(64)) {
17824       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
17825       if (Constraints.size() >= 2 &&
17826           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
17827           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
17828         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
17829         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
17830             matchAsm(AsmPieces[1], "bswap", "%edx") &&
17831             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
17832           return IntrinsicLowering::LowerToByteSwap(CI);
17833       }
17834     }
17835     break;
17836   }
17837   return false;
17838 }
17839
17840 /// getConstraintType - Given a constraint letter, return the type of
17841 /// constraint it is for this target.
17842 X86TargetLowering::ConstraintType
17843 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
17844   if (Constraint.size() == 1) {
17845     switch (Constraint[0]) {
17846     case 'R':
17847     case 'q':
17848     case 'Q':
17849     case 'f':
17850     case 't':
17851     case 'u':
17852     case 'y':
17853     case 'x':
17854     case 'Y':
17855     case 'l':
17856       return C_RegisterClass;
17857     case 'a':
17858     case 'b':
17859     case 'c':
17860     case 'd':
17861     case 'S':
17862     case 'D':
17863     case 'A':
17864       return C_Register;
17865     case 'I':
17866     case 'J':
17867     case 'K':
17868     case 'L':
17869     case 'M':
17870     case 'N':
17871     case 'G':
17872     case 'C':
17873     case 'e':
17874     case 'Z':
17875       return C_Other;
17876     default:
17877       break;
17878     }
17879   }
17880   return TargetLowering::getConstraintType(Constraint);
17881 }
17882
17883 /// Examine constraint type and operand type and determine a weight value.
17884 /// This object must already have been set up with the operand type
17885 /// and the current alternative constraint selected.
17886 TargetLowering::ConstraintWeight
17887   X86TargetLowering::getSingleConstraintMatchWeight(
17888     AsmOperandInfo &info, const char *constraint) const {
17889   ConstraintWeight weight = CW_Invalid;
17890   Value *CallOperandVal = info.CallOperandVal;
17891     // If we don't have a value, we can't do a match,
17892     // but allow it at the lowest weight.
17893   if (CallOperandVal == NULL)
17894     return CW_Default;
17895   Type *type = CallOperandVal->getType();
17896   // Look at the constraint type.
17897   switch (*constraint) {
17898   default:
17899     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17900   case 'R':
17901   case 'q':
17902   case 'Q':
17903   case 'a':
17904   case 'b':
17905   case 'c':
17906   case 'd':
17907   case 'S':
17908   case 'D':
17909   case 'A':
17910     if (CallOperandVal->getType()->isIntegerTy())
17911       weight = CW_SpecificReg;
17912     break;
17913   case 'f':
17914   case 't':
17915   case 'u':
17916     if (type->isFloatingPointTy())
17917       weight = CW_SpecificReg;
17918     break;
17919   case 'y':
17920     if (type->isX86_MMXTy() && Subtarget->hasMMX())
17921       weight = CW_SpecificReg;
17922     break;
17923   case 'x':
17924   case 'Y':
17925     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
17926         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
17927       weight = CW_Register;
17928     break;
17929   case 'I':
17930     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
17931       if (C->getZExtValue() <= 31)
17932         weight = CW_Constant;
17933     }
17934     break;
17935   case 'J':
17936     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17937       if (C->getZExtValue() <= 63)
17938         weight = CW_Constant;
17939     }
17940     break;
17941   case 'K':
17942     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17943       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
17944         weight = CW_Constant;
17945     }
17946     break;
17947   case 'L':
17948     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17949       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
17950         weight = CW_Constant;
17951     }
17952     break;
17953   case 'M':
17954     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17955       if (C->getZExtValue() <= 3)
17956         weight = CW_Constant;
17957     }
17958     break;
17959   case 'N':
17960     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17961       if (C->getZExtValue() <= 0xff)
17962         weight = CW_Constant;
17963     }
17964     break;
17965   case 'G':
17966   case 'C':
17967     if (dyn_cast<ConstantFP>(CallOperandVal)) {
17968       weight = CW_Constant;
17969     }
17970     break;
17971   case 'e':
17972     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17973       if ((C->getSExtValue() >= -0x80000000LL) &&
17974           (C->getSExtValue() <= 0x7fffffffLL))
17975         weight = CW_Constant;
17976     }
17977     break;
17978   case 'Z':
17979     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
17980       if (C->getZExtValue() <= 0xffffffff)
17981         weight = CW_Constant;
17982     }
17983     break;
17984   }
17985   return weight;
17986 }
17987
17988 /// LowerXConstraint - try to replace an X constraint, which matches anything,
17989 /// with another that has more specific requirements based on the type of the
17990 /// corresponding operand.
17991 const char *X86TargetLowering::
17992 LowerXConstraint(EVT ConstraintVT) const {
17993   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
17994   // 'f' like normal targets.
17995   if (ConstraintVT.isFloatingPoint()) {
17996     if (Subtarget->hasSSE2())
17997       return "Y";
17998     if (Subtarget->hasSSE1())
17999       return "x";
18000   }
18001
18002   return TargetLowering::LowerXConstraint(ConstraintVT);
18003 }
18004
18005 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18006 /// vector.  If it is invalid, don't add anything to Ops.
18007 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18008                                                      std::string &Constraint,
18009                                                      std::vector<SDValue>&Ops,
18010                                                      SelectionDAG &DAG) const {
18011   SDValue Result(0, 0);
18012
18013   // Only support length 1 constraints for now.
18014   if (Constraint.length() > 1) return;
18015
18016   char ConstraintLetter = Constraint[0];
18017   switch (ConstraintLetter) {
18018   default: break;
18019   case 'I':
18020     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18021       if (C->getZExtValue() <= 31) {
18022         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18023         break;
18024       }
18025     }
18026     return;
18027   case 'J':
18028     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18029       if (C->getZExtValue() <= 63) {
18030         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18031         break;
18032       }
18033     }
18034     return;
18035   case 'K':
18036     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18037       if (isInt<8>(C->getSExtValue())) {
18038         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18039         break;
18040       }
18041     }
18042     return;
18043   case 'N':
18044     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18045       if (C->getZExtValue() <= 255) {
18046         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18047         break;
18048       }
18049     }
18050     return;
18051   case 'e': {
18052     // 32-bit signed value
18053     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18054       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18055                                            C->getSExtValue())) {
18056         // Widen to 64 bits here to get it sign extended.
18057         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18058         break;
18059       }
18060     // FIXME gcc accepts some relocatable values here too, but only in certain
18061     // memory models; it's complicated.
18062     }
18063     return;
18064   }
18065   case 'Z': {
18066     // 32-bit unsigned value
18067     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18068       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18069                                            C->getZExtValue())) {
18070         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18071         break;
18072       }
18073     }
18074     // FIXME gcc accepts some relocatable values here too, but only in certain
18075     // memory models; it's complicated.
18076     return;
18077   }
18078   case 'i': {
18079     // Literal immediates are always ok.
18080     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18081       // Widen to 64 bits here to get it sign extended.
18082       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18083       break;
18084     }
18085
18086     // In any sort of PIC mode addresses need to be computed at runtime by
18087     // adding in a register or some sort of table lookup.  These can't
18088     // be used as immediates.
18089     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18090       return;
18091
18092     // If we are in non-pic codegen mode, we allow the address of a global (with
18093     // an optional displacement) to be used with 'i'.
18094     GlobalAddressSDNode *GA = 0;
18095     int64_t Offset = 0;
18096
18097     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18098     while (1) {
18099       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18100         Offset += GA->getOffset();
18101         break;
18102       } else if (Op.getOpcode() == ISD::ADD) {
18103         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18104           Offset += C->getZExtValue();
18105           Op = Op.getOperand(0);
18106           continue;
18107         }
18108       } else if (Op.getOpcode() == ISD::SUB) {
18109         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18110           Offset += -C->getZExtValue();
18111           Op = Op.getOperand(0);
18112           continue;
18113         }
18114       }
18115
18116       // Otherwise, this isn't something we can handle, reject it.
18117       return;
18118     }
18119
18120     const GlobalValue *GV = GA->getGlobal();
18121     // If we require an extra load to get this address, as in PIC mode, we
18122     // can't accept it.
18123     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18124                                                         getTargetMachine())))
18125       return;
18126
18127     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18128                                         GA->getValueType(0), Offset);
18129     break;
18130   }
18131   }
18132
18133   if (Result.getNode()) {
18134     Ops.push_back(Result);
18135     return;
18136   }
18137   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18138 }
18139
18140 std::pair<unsigned, const TargetRegisterClass*>
18141 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18142                                                 EVT VT) const {
18143   // First, see if this is a constraint that directly corresponds to an LLVM
18144   // register class.
18145   if (Constraint.size() == 1) {
18146     // GCC Constraint Letters
18147     switch (Constraint[0]) {
18148     default: break;
18149       // TODO: Slight differences here in allocation order and leaving
18150       // RIP in the class. Do they matter any more here than they do
18151       // in the normal allocation?
18152     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18153       if (Subtarget->is64Bit()) {
18154         if (VT == MVT::i32 || VT == MVT::f32)
18155           return std::make_pair(0U, &X86::GR32RegClass);
18156         if (VT == MVT::i16)
18157           return std::make_pair(0U, &X86::GR16RegClass);
18158         if (VT == MVT::i8 || VT == MVT::i1)
18159           return std::make_pair(0U, &X86::GR8RegClass);
18160         if (VT == MVT::i64 || VT == MVT::f64)
18161           return std::make_pair(0U, &X86::GR64RegClass);
18162         break;
18163       }
18164       // 32-bit fallthrough
18165     case 'Q':   // Q_REGS
18166       if (VT == MVT::i32 || VT == MVT::f32)
18167         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18168       if (VT == MVT::i16)
18169         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18170       if (VT == MVT::i8 || VT == MVT::i1)
18171         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18172       if (VT == MVT::i64)
18173         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18174       break;
18175     case 'r':   // GENERAL_REGS
18176     case 'l':   // INDEX_REGS
18177       if (VT == MVT::i8 || VT == MVT::i1)
18178         return std::make_pair(0U, &X86::GR8RegClass);
18179       if (VT == MVT::i16)
18180         return std::make_pair(0U, &X86::GR16RegClass);
18181       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18182         return std::make_pair(0U, &X86::GR32RegClass);
18183       return std::make_pair(0U, &X86::GR64RegClass);
18184     case 'R':   // LEGACY_REGS
18185       if (VT == MVT::i8 || VT == MVT::i1)
18186         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18187       if (VT == MVT::i16)
18188         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18189       if (VT == MVT::i32 || !Subtarget->is64Bit())
18190         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18191       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18192     case 'f':  // FP Stack registers.
18193       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18194       // value to the correct fpstack register class.
18195       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18196         return std::make_pair(0U, &X86::RFP32RegClass);
18197       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18198         return std::make_pair(0U, &X86::RFP64RegClass);
18199       return std::make_pair(0U, &X86::RFP80RegClass);
18200     case 'y':   // MMX_REGS if MMX allowed.
18201       if (!Subtarget->hasMMX()) break;
18202       return std::make_pair(0U, &X86::VR64RegClass);
18203     case 'Y':   // SSE_REGS if SSE2 allowed
18204       if (!Subtarget->hasSSE2()) break;
18205       // FALL THROUGH.
18206     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18207       if (!Subtarget->hasSSE1()) break;
18208
18209       switch (VT.getSimpleVT().SimpleTy) {
18210       default: break;
18211       // Scalar SSE types.
18212       case MVT::f32:
18213       case MVT::i32:
18214         return std::make_pair(0U, &X86::FR32RegClass);
18215       case MVT::f64:
18216       case MVT::i64:
18217         return std::make_pair(0U, &X86::FR64RegClass);
18218       // Vector types.
18219       case MVT::v16i8:
18220       case MVT::v8i16:
18221       case MVT::v4i32:
18222       case MVT::v2i64:
18223       case MVT::v4f32:
18224       case MVT::v2f64:
18225         return std::make_pair(0U, &X86::VR128RegClass);
18226       // AVX types.
18227       case MVT::v32i8:
18228       case MVT::v16i16:
18229       case MVT::v8i32:
18230       case MVT::v4i64:
18231       case MVT::v8f32:
18232       case MVT::v4f64:
18233         return std::make_pair(0U, &X86::VR256RegClass);
18234       }
18235       break;
18236     }
18237   }
18238
18239   // Use the default implementation in TargetLowering to convert the register
18240   // constraint into a member of a register class.
18241   std::pair<unsigned, const TargetRegisterClass*> Res;
18242   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18243
18244   // Not found as a standard register?
18245   if (Res.second == 0) {
18246     // Map st(0) -> st(7) -> ST0
18247     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18248         tolower(Constraint[1]) == 's' &&
18249         tolower(Constraint[2]) == 't' &&
18250         Constraint[3] == '(' &&
18251         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18252         Constraint[5] == ')' &&
18253         Constraint[6] == '}') {
18254
18255       Res.first = X86::ST0+Constraint[4]-'0';
18256       Res.second = &X86::RFP80RegClass;
18257       return Res;
18258     }
18259
18260     // GCC allows "st(0)" to be called just plain "st".
18261     if (StringRef("{st}").equals_lower(Constraint)) {
18262       Res.first = X86::ST0;
18263       Res.second = &X86::RFP80RegClass;
18264       return Res;
18265     }
18266
18267     // flags -> EFLAGS
18268     if (StringRef("{flags}").equals_lower(Constraint)) {
18269       Res.first = X86::EFLAGS;
18270       Res.second = &X86::CCRRegClass;
18271       return Res;
18272     }
18273
18274     // 'A' means EAX + EDX.
18275     if (Constraint == "A") {
18276       Res.first = X86::EAX;
18277       Res.second = &X86::GR32_ADRegClass;
18278       return Res;
18279     }
18280     return Res;
18281   }
18282
18283   // Otherwise, check to see if this is a register class of the wrong value
18284   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18285   // turn into {ax},{dx}.
18286   if (Res.second->hasType(VT))
18287     return Res;   // Correct type already, nothing to do.
18288
18289   // All of the single-register GCC register classes map their values onto
18290   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18291   // really want an 8-bit or 32-bit register, map to the appropriate register
18292   // class and return the appropriate register.
18293   if (Res.second == &X86::GR16RegClass) {
18294     if (VT == MVT::i8 || VT == MVT::i1) {
18295       unsigned DestReg = 0;
18296       switch (Res.first) {
18297       default: break;
18298       case X86::AX: DestReg = X86::AL; break;
18299       case X86::DX: DestReg = X86::DL; break;
18300       case X86::CX: DestReg = X86::CL; break;
18301       case X86::BX: DestReg = X86::BL; break;
18302       }
18303       if (DestReg) {
18304         Res.first = DestReg;
18305         Res.second = &X86::GR8RegClass;
18306       }
18307     } else if (VT == MVT::i32 || VT == MVT::f32) {
18308       unsigned DestReg = 0;
18309       switch (Res.first) {
18310       default: break;
18311       case X86::AX: DestReg = X86::EAX; break;
18312       case X86::DX: DestReg = X86::EDX; break;
18313       case X86::CX: DestReg = X86::ECX; break;
18314       case X86::BX: DestReg = X86::EBX; break;
18315       case X86::SI: DestReg = X86::ESI; break;
18316       case X86::DI: DestReg = X86::EDI; break;
18317       case X86::BP: DestReg = X86::EBP; break;
18318       case X86::SP: DestReg = X86::ESP; break;
18319       }
18320       if (DestReg) {
18321         Res.first = DestReg;
18322         Res.second = &X86::GR32RegClass;
18323       }
18324     } else if (VT == MVT::i64 || VT == MVT::f64) {
18325       unsigned DestReg = 0;
18326       switch (Res.first) {
18327       default: break;
18328       case X86::AX: DestReg = X86::RAX; break;
18329       case X86::DX: DestReg = X86::RDX; break;
18330       case X86::CX: DestReg = X86::RCX; break;
18331       case X86::BX: DestReg = X86::RBX; break;
18332       case X86::SI: DestReg = X86::RSI; break;
18333       case X86::DI: DestReg = X86::RDI; break;
18334       case X86::BP: DestReg = X86::RBP; break;
18335       case X86::SP: DestReg = X86::RSP; break;
18336       }
18337       if (DestReg) {
18338         Res.first = DestReg;
18339         Res.second = &X86::GR64RegClass;
18340       }
18341     }
18342   } else if (Res.second == &X86::FR32RegClass ||
18343              Res.second == &X86::FR64RegClass ||
18344              Res.second == &X86::VR128RegClass) {
18345     // Handle references to XMM physical registers that got mapped into the
18346     // wrong class.  This can happen with constraints like {xmm0} where the
18347     // target independent register mapper will just pick the first match it can
18348     // find, ignoring the required type.
18349
18350     if (VT == MVT::f32 || VT == MVT::i32)
18351       Res.second = &X86::FR32RegClass;
18352     else if (VT == MVT::f64 || VT == MVT::i64)
18353       Res.second = &X86::FR64RegClass;
18354     else if (X86::VR128RegClass.hasType(VT))
18355       Res.second = &X86::VR128RegClass;
18356     else if (X86::VR256RegClass.hasType(VT))
18357       Res.second = &X86::VR256RegClass;
18358   }
18359
18360   return Res;
18361 }