6d53a8f74aa054a146f305b5fa5d9a7f6e98d35c
[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   RegInfo = TM.getRegisterInfo();
167   TD = getDataLayout();
168
169   resetOperationActions();
170 }
171
172 void X86TargetLowering::resetOperationActions() {
173   const TargetMachine &TM = getTargetMachine();
174   static bool FirstTimeThrough = true;
175
176   // If none of the target options have changed, then we don't need to reset the
177   // operation actions.
178   if (!FirstTimeThrough && TO == TM.Options) return;
179
180   if (!FirstTimeThrough) {
181     // Reinitialize the actions.
182     initActions();
183     FirstTimeThrough = false;
184   }
185
186   TO = TM.Options;
187
188   // Set up the TargetLowering object.
189   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
190
191   // X86 is weird, it always uses i8 for shift amounts and setcc results.
192   setBooleanContents(ZeroOrOneBooleanContent);
193   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
194   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
195
196   // For 64-bit since we have so many registers use the ILP scheduler, for
197   // 32-bit code use the register pressure specific scheduling.
198   // For Atom, always use ILP scheduling.
199   if (Subtarget->isAtom())
200     setSchedulingPreference(Sched::ILP);
201   else if (Subtarget->is64Bit())
202     setSchedulingPreference(Sched::ILP);
203   else
204     setSchedulingPreference(Sched::RegPressure);
205   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
206
207   // Bypass expensive divides on Atom when compiling with O2
208   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
209     addBypassSlowDiv(32, 8);
210     if (Subtarget->is64Bit())
211       addBypassSlowDiv(64, 16);
212   }
213
214   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
215     // Setup Windows compiler runtime calls.
216     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
217     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
218     setLibcallName(RTLIB::SREM_I64, "_allrem");
219     setLibcallName(RTLIB::UREM_I64, "_aullrem");
220     setLibcallName(RTLIB::MUL_I64, "_allmul");
221     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
222     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
223     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
224     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
225     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
226
227     // The _ftol2 runtime function has an unusual calling conv, which
228     // is modeled by a special pseudo-instruction.
229     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
230     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
231     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
232     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
233   }
234
235   if (Subtarget->isTargetDarwin()) {
236     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
237     setUseUnderscoreSetJmp(false);
238     setUseUnderscoreLongJmp(false);
239   } else if (Subtarget->isTargetMingw()) {
240     // MS runtime is weird: it exports _setjmp, but longjmp!
241     setUseUnderscoreSetJmp(true);
242     setUseUnderscoreLongJmp(false);
243   } else {
244     setUseUnderscoreSetJmp(true);
245     setUseUnderscoreLongJmp(true);
246   }
247
248   // Set up the register classes.
249   addRegisterClass(MVT::i8, &X86::GR8RegClass);
250   addRegisterClass(MVT::i16, &X86::GR16RegClass);
251   addRegisterClass(MVT::i32, &X86::GR32RegClass);
252   if (Subtarget->is64Bit())
253     addRegisterClass(MVT::i64, &X86::GR64RegClass);
254
255   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
256
257   // We don't accept any truncstore of integer registers.
258   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
259   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
260   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
261   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
262   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
263   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
264
265   // SETOEQ and SETUNE require checking two conditions.
266   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
267   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
268   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
269   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
270   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
271   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
272
273   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
274   // operation.
275   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
276   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
277   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
278
279   if (Subtarget->is64Bit()) {
280     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
281     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
282   } else if (!TM.Options.UseSoftFloat) {
283     // We have an algorithm for SSE2->double, and we turn this into a
284     // 64-bit FILD followed by conditional FADD for other targets.
285     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
286     // We have an algorithm for SSE2, and we turn this into a 64-bit
287     // FILD for other targets.
288     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
289   }
290
291   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
292   // this operation.
293   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
294   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
295
296   if (!TM.Options.UseSoftFloat) {
297     // SSE has no i16 to fp conversion, only i32
298     if (X86ScalarSSEf32) {
299       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
300       // f32 and f64 cases are Legal, f80 case is not
301       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
302     } else {
303       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
304       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
305     }
306   } else {
307     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
308     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
309   }
310
311   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
312   // are Legal, f80 is custom lowered.
313   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
314   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
315
316   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
317   // this operation.
318   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
319   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
320
321   if (X86ScalarSSEf32) {
322     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
323     // f32 and f64 cases are Legal, f80 case is not
324     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
325   } else {
326     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
327     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
328   }
329
330   // Handle FP_TO_UINT by promoting the destination to a larger signed
331   // conversion.
332   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
333   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
334   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
335
336   if (Subtarget->is64Bit()) {
337     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
338     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
339   } else if (!TM.Options.UseSoftFloat) {
340     // Since AVX is a superset of SSE3, only check for SSE here.
341     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
342       // Expand FP_TO_UINT into a select.
343       // FIXME: We would like to use a Custom expander here eventually to do
344       // the optimal thing for SSE vs. the default expansion in the legalizer.
345       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
346     else
347       // With SSE3 we can use fisttpll to convert to a signed i64; without
348       // SSE, we're stuck with a fistpll.
349       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
350   }
351
352   if (isTargetFTOL()) {
353     // Use the _ftol2 runtime function, which has a pseudo-instruction
354     // to handle its weird calling convention.
355     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
356   }
357
358   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
359   if (!X86ScalarSSEf64) {
360     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
361     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
362     if (Subtarget->is64Bit()) {
363       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
364       // Without SSE, i64->f64 goes through memory.
365       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
366     }
367   }
368
369   // Scalar integer divide and remainder are lowered to use operations that
370   // produce two results, to match the available instructions. This exposes
371   // the two-result form to trivial CSE, which is able to combine x/y and x%y
372   // into a single instruction.
373   //
374   // Scalar integer multiply-high is also lowered to use two-result
375   // operations, to match the available instructions. However, plain multiply
376   // (low) operations are left as Legal, as there are single-result
377   // instructions for this in x86. Using the two-result multiply instructions
378   // when both high and low results are needed must be arranged by dagcombine.
379   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
380     MVT VT = IntVTs[i];
381     setOperationAction(ISD::MULHS, VT, Expand);
382     setOperationAction(ISD::MULHU, VT, Expand);
383     setOperationAction(ISD::SDIV, VT, Expand);
384     setOperationAction(ISD::UDIV, VT, Expand);
385     setOperationAction(ISD::SREM, VT, Expand);
386     setOperationAction(ISD::UREM, VT, Expand);
387
388     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
389     setOperationAction(ISD::ADDC, VT, Custom);
390     setOperationAction(ISD::ADDE, VT, Custom);
391     setOperationAction(ISD::SUBC, VT, Custom);
392     setOperationAction(ISD::SUBE, VT, Custom);
393   }
394
395   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
396   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
397   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
398   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
399   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
400   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
401   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
402   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
403   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
404   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
405   if (Subtarget->is64Bit())
406     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
408   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
409   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
410   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
411   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
412   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
413   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
414   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
415
416   // Promote the i8 variants and force them on up to i32 which has a shorter
417   // encoding.
418   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
419   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
420   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
421   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
422   if (Subtarget->hasBMI()) {
423     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
424     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
425     if (Subtarget->is64Bit())
426       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
427   } else {
428     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
429     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
430     if (Subtarget->is64Bit())
431       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
432   }
433
434   if (Subtarget->hasLZCNT()) {
435     // When promoting the i8 variants, force them to i32 for a shorter
436     // encoding.
437     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
438     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
439     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
440     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
441     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
442     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
443     if (Subtarget->is64Bit())
444       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
445   } else {
446     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
447     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
448     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
449     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
450     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
451     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
452     if (Subtarget->is64Bit()) {
453       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
454       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
455     }
456   }
457
458   if (Subtarget->hasPOPCNT()) {
459     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
460   } else {
461     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
462     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
463     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
464     if (Subtarget->is64Bit())
465       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
466   }
467
468   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
469   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
470
471   // These should be promoted to a larger select which is supported.
472   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
473   // X86 wants to expand cmov itself.
474   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
475   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
476   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
477   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
478   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
479   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
480   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
481   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
482   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
483   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
484   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
485   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
486   if (Subtarget->is64Bit()) {
487     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
488     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
489   }
490   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
491   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
492   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
493   // support continuation, user-level threading, and etc.. As a result, no
494   // other SjLj exception interfaces are implemented and please don't build
495   // your own exception handling based on them.
496   // LLVM/Clang supports zero-cost DWARF exception handling.
497   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
498   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
499
500   // Darwin ABI issue.
501   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
502   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
503   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
504   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
505   if (Subtarget->is64Bit())
506     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
507   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
508   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
509   if (Subtarget->is64Bit()) {
510     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
511     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
512     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
513     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
514     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
515   }
516   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
517   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
518   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
519   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
520   if (Subtarget->is64Bit()) {
521     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
522     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
523     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
524   }
525
526   if (Subtarget->hasSSE1())
527     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
528
529   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
530
531   // Expand certain atomics
532   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
533     MVT VT = IntVTs[i];
534     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
535     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
536     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
537   }
538
539   if (!Subtarget->is64Bit()) {
540     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
541     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
542     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
543     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
544     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
545     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
546     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
547     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
548     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
549     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
550     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
551     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
552   }
553
554   if (Subtarget->hasCmpxchg16b()) {
555     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
556   }
557
558   // FIXME - use subtarget debug flags
559   if (!Subtarget->isTargetDarwin() &&
560       !Subtarget->isTargetELF() &&
561       !Subtarget->isTargetCygMing()) {
562     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
563   }
564
565   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
566   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
567   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
568   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
569   if (Subtarget->is64Bit()) {
570     setExceptionPointerRegister(X86::RAX);
571     setExceptionSelectorRegister(X86::RDX);
572   } else {
573     setExceptionPointerRegister(X86::EAX);
574     setExceptionSelectorRegister(X86::EDX);
575   }
576   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
577   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
578
579   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
580   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
581
582   setOperationAction(ISD::TRAP, MVT::Other, Legal);
583   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
584
585   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
586   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
587   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
588   if (Subtarget->is64Bit()) {
589     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
590     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
591   } else {
592     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
593     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
594   }
595
596   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
597   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
598
599   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
600     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
601                        MVT::i64 : MVT::i32, Custom);
602   else if (TM.Options.EnableSegmentedStacks)
603     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
604                        MVT::i64 : MVT::i32, Custom);
605   else
606     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
607                        MVT::i64 : MVT::i32, Expand);
608
609   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
610     // f32 and f64 use SSE.
611     // Set up the FP register classes.
612     addRegisterClass(MVT::f32, &X86::FR32RegClass);
613     addRegisterClass(MVT::f64, &X86::FR64RegClass);
614
615     // Use ANDPD to simulate FABS.
616     setOperationAction(ISD::FABS , MVT::f64, Custom);
617     setOperationAction(ISD::FABS , MVT::f32, Custom);
618
619     // Use XORP to simulate FNEG.
620     setOperationAction(ISD::FNEG , MVT::f64, Custom);
621     setOperationAction(ISD::FNEG , MVT::f32, Custom);
622
623     // Use ANDPD and ORPD to simulate FCOPYSIGN.
624     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
625     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
626
627     // Lower this to FGETSIGNx86 plus an AND.
628     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
629     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
630
631     // We don't support sin/cos/fmod
632     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
633     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
634     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
635     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
636     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
637     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
638
639     // Expand FP immediates into loads from the stack, except for the special
640     // cases we handle.
641     addLegalFPImmediate(APFloat(+0.0)); // xorpd
642     addLegalFPImmediate(APFloat(+0.0f)); // xorps
643   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
644     // Use SSE for f32, x87 for f64.
645     // Set up the FP register classes.
646     addRegisterClass(MVT::f32, &X86::FR32RegClass);
647     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
648
649     // Use ANDPS to simulate FABS.
650     setOperationAction(ISD::FABS , MVT::f32, Custom);
651
652     // Use XORP to simulate FNEG.
653     setOperationAction(ISD::FNEG , MVT::f32, Custom);
654
655     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
656
657     // Use ANDPS and ORPS to simulate FCOPYSIGN.
658     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
659     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
660
661     // We don't support sin/cos/fmod
662     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
663     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
664     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
665
666     // Special cases we handle for FP constants.
667     addLegalFPImmediate(APFloat(+0.0f)); // xorps
668     addLegalFPImmediate(APFloat(+0.0)); // FLD0
669     addLegalFPImmediate(APFloat(+1.0)); // FLD1
670     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
671     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
672
673     if (!TM.Options.UnsafeFPMath) {
674       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
675       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
676       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
677     }
678   } else if (!TM.Options.UseSoftFloat) {
679     // f32 and f64 in x87.
680     // Set up the FP register classes.
681     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
682     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
683
684     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
685     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
686     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
687     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
688
689     if (!TM.Options.UnsafeFPMath) {
690       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
691       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
693       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
694       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
695       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
696     }
697     addLegalFPImmediate(APFloat(+0.0)); // FLD0
698     addLegalFPImmediate(APFloat(+1.0)); // FLD1
699     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
700     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
701     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
702     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
703     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
704     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
705   }
706
707   // We don't support FMA.
708   setOperationAction(ISD::FMA, MVT::f64, Expand);
709   setOperationAction(ISD::FMA, MVT::f32, Expand);
710
711   // Long double always uses X87.
712   if (!TM.Options.UseSoftFloat) {
713     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
714     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
716     {
717       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
718       addLegalFPImmediate(TmpFlt);  // FLD0
719       TmpFlt.changeSign();
720       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
721
722       bool ignored;
723       APFloat TmpFlt2(+1.0);
724       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
725                       &ignored);
726       addLegalFPImmediate(TmpFlt2);  // FLD1
727       TmpFlt2.changeSign();
728       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
729     }
730
731     if (!TM.Options.UnsafeFPMath) {
732       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
733       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
734       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
735     }
736
737     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
738     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
739     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
740     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
741     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
742     setOperationAction(ISD::FMA, MVT::f80, Expand);
743   }
744
745   // Always use a library call for pow.
746   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
747   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
748   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
749
750   setOperationAction(ISD::FLOG, MVT::f80, Expand);
751   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
752   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
753   setOperationAction(ISD::FEXP, MVT::f80, Expand);
754   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
755
756   // First set operation action for all vector types to either promote
757   // (for widening) or expand (for scalarization). Then we will selectively
758   // turn on ones that can be effectively codegen'd.
759   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
760            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
761     MVT VT = (MVT::SimpleValueType)i;
762     setOperationAction(ISD::ADD , VT, Expand);
763     setOperationAction(ISD::SUB , VT, Expand);
764     setOperationAction(ISD::FADD, VT, Expand);
765     setOperationAction(ISD::FNEG, VT, Expand);
766     setOperationAction(ISD::FSUB, VT, Expand);
767     setOperationAction(ISD::MUL , VT, Expand);
768     setOperationAction(ISD::FMUL, VT, Expand);
769     setOperationAction(ISD::SDIV, VT, Expand);
770     setOperationAction(ISD::UDIV, VT, Expand);
771     setOperationAction(ISD::FDIV, VT, Expand);
772     setOperationAction(ISD::SREM, VT, Expand);
773     setOperationAction(ISD::UREM, VT, Expand);
774     setOperationAction(ISD::LOAD, VT, Expand);
775     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
776     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
777     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
778     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
779     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
780     setOperationAction(ISD::FABS, VT, Expand);
781     setOperationAction(ISD::FSIN, VT, Expand);
782     setOperationAction(ISD::FSINCOS, VT, Expand);
783     setOperationAction(ISD::FCOS, VT, Expand);
784     setOperationAction(ISD::FSINCOS, VT, Expand);
785     setOperationAction(ISD::FREM, VT, Expand);
786     setOperationAction(ISD::FMA,  VT, Expand);
787     setOperationAction(ISD::FPOWI, VT, Expand);
788     setOperationAction(ISD::FSQRT, VT, Expand);
789     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
790     setOperationAction(ISD::FFLOOR, VT, Expand);
791     setOperationAction(ISD::FCEIL, VT, Expand);
792     setOperationAction(ISD::FTRUNC, VT, Expand);
793     setOperationAction(ISD::FRINT, VT, Expand);
794     setOperationAction(ISD::FNEARBYINT, VT, Expand);
795     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
796     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
797     setOperationAction(ISD::SDIVREM, VT, Expand);
798     setOperationAction(ISD::UDIVREM, VT, Expand);
799     setOperationAction(ISD::FPOW, VT, Expand);
800     setOperationAction(ISD::CTPOP, VT, Expand);
801     setOperationAction(ISD::CTTZ, VT, Expand);
802     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
803     setOperationAction(ISD::CTLZ, VT, Expand);
804     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
805     setOperationAction(ISD::SHL, VT, Expand);
806     setOperationAction(ISD::SRA, VT, Expand);
807     setOperationAction(ISD::SRL, VT, Expand);
808     setOperationAction(ISD::ROTL, VT, Expand);
809     setOperationAction(ISD::ROTR, VT, Expand);
810     setOperationAction(ISD::BSWAP, VT, Expand);
811     setOperationAction(ISD::SETCC, VT, Expand);
812     setOperationAction(ISD::FLOG, VT, Expand);
813     setOperationAction(ISD::FLOG2, VT, Expand);
814     setOperationAction(ISD::FLOG10, VT, Expand);
815     setOperationAction(ISD::FEXP, VT, Expand);
816     setOperationAction(ISD::FEXP2, VT, Expand);
817     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
818     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
819     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
820     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
821     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
822     setOperationAction(ISD::TRUNCATE, VT, Expand);
823     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
824     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
825     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
826     setOperationAction(ISD::VSELECT, VT, Expand);
827     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
828              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
829       setTruncStoreAction(VT,
830                           (MVT::SimpleValueType)InnerVT, Expand);
831     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
832     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
833     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
834   }
835
836   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
837   // with -msoft-float, disable use of MMX as well.
838   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
839     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
840     // No operations on x86mmx supported, everything uses intrinsics.
841   }
842
843   // MMX-sized vectors (other than x86mmx) are expected to be expanded
844   // into smaller operations.
845   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
846   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
847   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
848   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
849   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
850   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
851   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
852   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
853   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
854   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
855   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
856   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
857   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
858   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
859   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
860   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
861   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
862   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
863   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
864   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
865   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
866   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
867   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
868   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
869   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
870   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
871   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
872   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
873   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
874
875   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
876     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
877
878     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
879     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
880     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
881     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
882     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
883     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
884     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
885     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
886     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
887     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
888     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
889     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
890   }
891
892   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
893     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
894
895     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
896     // registers cannot be used even for integer operations.
897     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
898     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
899     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
900     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
901
902     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
903     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
904     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
905     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
906     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
907     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
908     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
909     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
910     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
911     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
912     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
913     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
914     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
915     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
916     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
917     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
918     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
919     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
920
921     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
922     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
923     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
924     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
925
926     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
927     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
928     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
929     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
930     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
931
932     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
933     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
934       MVT VT = (MVT::SimpleValueType)i;
935       // Do not attempt to custom lower non-power-of-2 vectors
936       if (!isPowerOf2_32(VT.getVectorNumElements()))
937         continue;
938       // Do not attempt to custom lower non-128-bit vectors
939       if (!VT.is128BitVector())
940         continue;
941       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
942       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
943       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
944     }
945
946     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
947     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
948     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
949     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
950     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
951     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
952
953     if (Subtarget->is64Bit()) {
954       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
955       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
956     }
957
958     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
959     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
960       MVT VT = (MVT::SimpleValueType)i;
961
962       // Do not attempt to promote non-128-bit vectors
963       if (!VT.is128BitVector())
964         continue;
965
966       setOperationAction(ISD::AND,    VT, Promote);
967       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
968       setOperationAction(ISD::OR,     VT, Promote);
969       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
970       setOperationAction(ISD::XOR,    VT, Promote);
971       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
972       setOperationAction(ISD::LOAD,   VT, Promote);
973       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
974       setOperationAction(ISD::SELECT, VT, Promote);
975       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
976     }
977
978     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
979
980     // Custom lower v2i64 and v2f64 selects.
981     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
983     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
984     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
985
986     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
987     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
988
989     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
990     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
991     // As there is no 64-bit GPR available, we need build a special custom
992     // sequence to convert from v2i32 to v2f32.
993     if (!Subtarget->is64Bit())
994       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
995
996     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
997     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
998
999     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1000   }
1001
1002   if (Subtarget->hasSSE41()) {
1003     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1004     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1005     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1006     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1007     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1008     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1009     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1010     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1011     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1012     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1013
1014     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1015     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1016     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1017     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1018     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1019     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1020     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1021     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1022     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1023     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1024
1025     // FIXME: Do we need to handle scalar-to-vector here?
1026     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1027
1028     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1029     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1030     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1031     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1032     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1033
1034     // i8 and i16 vectors are custom , because the source register and source
1035     // source memory operand types are not the same width.  f32 vectors are
1036     // custom since the immediate controlling the insert encodes additional
1037     // information.
1038     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1039     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1040     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1041     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1042
1043     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1044     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1045     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1046     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1047
1048     // FIXME: these should be Legal but thats only for the case where
1049     // the index is constant.  For now custom expand to deal with that.
1050     if (Subtarget->is64Bit()) {
1051       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1052       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1053     }
1054   }
1055
1056   if (Subtarget->hasSSE2()) {
1057     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1058     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1059
1060     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1061     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1062
1063     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1064     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1065
1066     // In the customized shift lowering, the legal cases in AVX2 will be
1067     // recognized.
1068     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1069     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1070
1071     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1072     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1073
1074     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1075
1076     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1077     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1078   }
1079
1080   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1081     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1082     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1083     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1084     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1085     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1086     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1087
1088     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1089     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1090     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1091
1092     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1093     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1094     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1095     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1096     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1097     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1098     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1099     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1100     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1101     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1102     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1103     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1104
1105     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1106     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1107     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1108     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1109     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1110     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1111     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1112     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1113     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1114     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1115     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1116     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1117
1118     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1119     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1120
1121     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1122
1123     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1124     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1125     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1126     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1127
1128     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1129     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1130     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1131
1132     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1133
1134     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1135     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1136
1137     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1138     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1139
1140     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1141     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1142
1143     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1144
1145     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1146     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1147     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1148     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1149
1150     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1151     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1152     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1153
1154     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1155     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1156     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1157     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1158
1159     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1160     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1161     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1162     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1163     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1164     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1165
1166     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1167       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1169       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1170       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1171       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1172       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1173     }
1174
1175     if (Subtarget->hasInt256()) {
1176       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1178       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1179       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1180
1181       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1183       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1184       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1185
1186       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1187       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1188       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1189       // Don't lower v32i8 because there is no 128-bit byte mul
1190
1191       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1192
1193       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1194     } else {
1195       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1197       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1198       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1199
1200       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1202       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1203       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1204
1205       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1206       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1207       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1208       // Don't lower v32i8 because there is no 128-bit byte mul
1209     }
1210
1211     // In the customized shift lowering, the legal cases in AVX2 will be
1212     // recognized.
1213     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1214     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1215
1216     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1217     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1218
1219     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1220
1221     // Custom lower several nodes for 256-bit types.
1222     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1223              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1224       MVT VT = (MVT::SimpleValueType)i;
1225
1226       // Extract subvector is special because the value type
1227       // (result) is 128-bit but the source is 256-bit wide.
1228       if (VT.is128BitVector())
1229         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1230
1231       // Do not attempt to custom lower other non-256-bit vectors
1232       if (!VT.is256BitVector())
1233         continue;
1234
1235       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1236       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1237       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1238       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1239       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1240       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1241       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1242     }
1243
1244     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1245     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1246       MVT VT = (MVT::SimpleValueType)i;
1247
1248       // Do not attempt to promote non-256-bit vectors
1249       if (!VT.is256BitVector())
1250         continue;
1251
1252       setOperationAction(ISD::AND,    VT, Promote);
1253       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1254       setOperationAction(ISD::OR,     VT, Promote);
1255       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1256       setOperationAction(ISD::XOR,    VT, Promote);
1257       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1258       setOperationAction(ISD::LOAD,   VT, Promote);
1259       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1260       setOperationAction(ISD::SELECT, VT, Promote);
1261       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1262     }
1263   }
1264
1265   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1266   // of this type with custom code.
1267   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1268            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1269     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1270                        Custom);
1271   }
1272
1273   // We want to custom lower some of our intrinsics.
1274   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1275   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1276
1277   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1278   // handle type legalization for these operations here.
1279   //
1280   // FIXME: We really should do custom legalization for addition and
1281   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1282   // than generic legalization for 64-bit multiplication-with-overflow, though.
1283   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1284     // Add/Sub/Mul with overflow operations are custom lowered.
1285     MVT VT = IntVTs[i];
1286     setOperationAction(ISD::SADDO, VT, Custom);
1287     setOperationAction(ISD::UADDO, VT, Custom);
1288     setOperationAction(ISD::SSUBO, VT, Custom);
1289     setOperationAction(ISD::USUBO, VT, Custom);
1290     setOperationAction(ISD::SMULO, VT, Custom);
1291     setOperationAction(ISD::UMULO, VT, Custom);
1292   }
1293
1294   // There are no 8-bit 3-address imul/mul instructions
1295   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1296   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1297
1298   if (!Subtarget->is64Bit()) {
1299     // These libcalls are not available in 32-bit.
1300     setLibcallName(RTLIB::SHL_I128, 0);
1301     setLibcallName(RTLIB::SRL_I128, 0);
1302     setLibcallName(RTLIB::SRA_I128, 0);
1303   }
1304
1305   // Combine sin / cos into one node or libcall if possible.
1306   if (Subtarget->hasSinCos()) {
1307     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1308     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1309     if (Subtarget->isTargetDarwin()) {
1310       // For MacOSX, we don't want to the normal expansion of a libcall to
1311       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1312       // traffic.
1313       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1314       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1315     }
1316   }
1317
1318   // We have target-specific dag combine patterns for the following nodes:
1319   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1320   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1321   setTargetDAGCombine(ISD::VSELECT);
1322   setTargetDAGCombine(ISD::SELECT);
1323   setTargetDAGCombine(ISD::SHL);
1324   setTargetDAGCombine(ISD::SRA);
1325   setTargetDAGCombine(ISD::SRL);
1326   setTargetDAGCombine(ISD::OR);
1327   setTargetDAGCombine(ISD::AND);
1328   setTargetDAGCombine(ISD::ADD);
1329   setTargetDAGCombine(ISD::FADD);
1330   setTargetDAGCombine(ISD::FSUB);
1331   setTargetDAGCombine(ISD::FMA);
1332   setTargetDAGCombine(ISD::SUB);
1333   setTargetDAGCombine(ISD::LOAD);
1334   setTargetDAGCombine(ISD::STORE);
1335   setTargetDAGCombine(ISD::ZERO_EXTEND);
1336   setTargetDAGCombine(ISD::ANY_EXTEND);
1337   setTargetDAGCombine(ISD::SIGN_EXTEND);
1338   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1339   setTargetDAGCombine(ISD::TRUNCATE);
1340   setTargetDAGCombine(ISD::SINT_TO_FP);
1341   setTargetDAGCombine(ISD::SETCC);
1342   if (Subtarget->is64Bit())
1343     setTargetDAGCombine(ISD::MUL);
1344   setTargetDAGCombine(ISD::XOR);
1345
1346   computeRegisterProperties();
1347
1348   // On Darwin, -Os means optimize for size without hurting performance,
1349   // do not reduce the limit.
1350   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1351   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1352   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1353   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1354   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1355   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1356   setPrefLoopAlignment(4); // 2^4 bytes.
1357
1358   // Predictable cmov don't hurt on atom because it's in-order.
1359   PredictableSelectIsExpensive = !Subtarget->isAtom();
1360
1361   setPrefFunctionAlignment(4); // 2^4 bytes.
1362 }
1363
1364 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1365   if (!VT.isVector()) return MVT::i8;
1366   return VT.changeVectorElementTypeToInteger();
1367 }
1368
1369 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1370 /// the desired ByVal argument alignment.
1371 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1372   if (MaxAlign == 16)
1373     return;
1374   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1375     if (VTy->getBitWidth() == 128)
1376       MaxAlign = 16;
1377   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1378     unsigned EltAlign = 0;
1379     getMaxByValAlign(ATy->getElementType(), EltAlign);
1380     if (EltAlign > MaxAlign)
1381       MaxAlign = EltAlign;
1382   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1383     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1384       unsigned EltAlign = 0;
1385       getMaxByValAlign(STy->getElementType(i), EltAlign);
1386       if (EltAlign > MaxAlign)
1387         MaxAlign = EltAlign;
1388       if (MaxAlign == 16)
1389         break;
1390     }
1391   }
1392 }
1393
1394 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1395 /// function arguments in the caller parameter area. For X86, aggregates
1396 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1397 /// are at 4-byte boundaries.
1398 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1399   if (Subtarget->is64Bit()) {
1400     // Max of 8 and alignment of type.
1401     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1402     if (TyAlign > 8)
1403       return TyAlign;
1404     return 8;
1405   }
1406
1407   unsigned Align = 4;
1408   if (Subtarget->hasSSE1())
1409     getMaxByValAlign(Ty, Align);
1410   return Align;
1411 }
1412
1413 /// getOptimalMemOpType - Returns the target specific optimal type for load
1414 /// and store operations as a result of memset, memcpy, and memmove
1415 /// lowering. If DstAlign is zero that means it's safe to destination
1416 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1417 /// means there isn't a need to check it against alignment requirement,
1418 /// probably because the source does not need to be loaded. If 'IsMemset' is
1419 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1420 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1421 /// source is constant so it does not need to be loaded.
1422 /// It returns EVT::Other if the type should be determined using generic
1423 /// target-independent logic.
1424 EVT
1425 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1426                                        unsigned DstAlign, unsigned SrcAlign,
1427                                        bool IsMemset, bool ZeroMemset,
1428                                        bool MemcpyStrSrc,
1429                                        MachineFunction &MF) const {
1430   const Function *F = MF.getFunction();
1431   if ((!IsMemset || ZeroMemset) &&
1432       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1433                                        Attribute::NoImplicitFloat)) {
1434     if (Size >= 16 &&
1435         (Subtarget->isUnalignedMemAccessFast() ||
1436          ((DstAlign == 0 || DstAlign >= 16) &&
1437           (SrcAlign == 0 || SrcAlign >= 16)))) {
1438       if (Size >= 32) {
1439         if (Subtarget->hasInt256())
1440           return MVT::v8i32;
1441         if (Subtarget->hasFp256())
1442           return MVT::v8f32;
1443       }
1444       if (Subtarget->hasSSE2())
1445         return MVT::v4i32;
1446       if (Subtarget->hasSSE1())
1447         return MVT::v4f32;
1448     } else if (!MemcpyStrSrc && Size >= 8 &&
1449                !Subtarget->is64Bit() &&
1450                Subtarget->hasSSE2()) {
1451       // Do not use f64 to lower memcpy if source is string constant. It's
1452       // better to use i32 to avoid the loads.
1453       return MVT::f64;
1454     }
1455   }
1456   if (Subtarget->is64Bit() && Size >= 8)
1457     return MVT::i64;
1458   return MVT::i32;
1459 }
1460
1461 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1462   if (VT == MVT::f32)
1463     return X86ScalarSSEf32;
1464   else if (VT == MVT::f64)
1465     return X86ScalarSSEf64;
1466   return true;
1467 }
1468
1469 bool
1470 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1471   if (Fast)
1472     *Fast = Subtarget->isUnalignedMemAccessFast();
1473   return true;
1474 }
1475
1476 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1477 /// current function.  The returned value is a member of the
1478 /// MachineJumpTableInfo::JTEntryKind enum.
1479 unsigned X86TargetLowering::getJumpTableEncoding() const {
1480   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1481   // symbol.
1482   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1483       Subtarget->isPICStyleGOT())
1484     return MachineJumpTableInfo::EK_Custom32;
1485
1486   // Otherwise, use the normal jump table encoding heuristics.
1487   return TargetLowering::getJumpTableEncoding();
1488 }
1489
1490 const MCExpr *
1491 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1492                                              const MachineBasicBlock *MBB,
1493                                              unsigned uid,MCContext &Ctx) const{
1494   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1495          Subtarget->isPICStyleGOT());
1496   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1497   // entries.
1498   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1499                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1500 }
1501
1502 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1503 /// jumptable.
1504 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1505                                                     SelectionDAG &DAG) const {
1506   if (!Subtarget->is64Bit())
1507     // This doesn't have DebugLoc associated with it, but is not really the
1508     // same as a Register.
1509     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1510   return Table;
1511 }
1512
1513 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1514 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1515 /// MCExpr.
1516 const MCExpr *X86TargetLowering::
1517 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1518                              MCContext &Ctx) const {
1519   // X86-64 uses RIP relative addressing based on the jump table label.
1520   if (Subtarget->isPICStyleRIPRel())
1521     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1522
1523   // Otherwise, the reference is relative to the PIC base.
1524   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1525 }
1526
1527 // FIXME: Why this routine is here? Move to RegInfo!
1528 std::pair<const TargetRegisterClass*, uint8_t>
1529 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1530   const TargetRegisterClass *RRC = 0;
1531   uint8_t Cost = 1;
1532   switch (VT.SimpleTy) {
1533   default:
1534     return TargetLowering::findRepresentativeClass(VT);
1535   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1536     RRC = Subtarget->is64Bit() ?
1537       (const TargetRegisterClass*)&X86::GR64RegClass :
1538       (const TargetRegisterClass*)&X86::GR32RegClass;
1539     break;
1540   case MVT::x86mmx:
1541     RRC = &X86::VR64RegClass;
1542     break;
1543   case MVT::f32: case MVT::f64:
1544   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1545   case MVT::v4f32: case MVT::v2f64:
1546   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1547   case MVT::v4f64:
1548     RRC = &X86::VR128RegClass;
1549     break;
1550   }
1551   return std::make_pair(RRC, Cost);
1552 }
1553
1554 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1555                                                unsigned &Offset) const {
1556   if (!Subtarget->isTargetLinux())
1557     return false;
1558
1559   if (Subtarget->is64Bit()) {
1560     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1561     Offset = 0x28;
1562     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1563       AddressSpace = 256;
1564     else
1565       AddressSpace = 257;
1566   } else {
1567     // %gs:0x14 on i386
1568     Offset = 0x14;
1569     AddressSpace = 256;
1570   }
1571   return true;
1572 }
1573
1574 //===----------------------------------------------------------------------===//
1575 //               Return Value Calling Convention Implementation
1576 //===----------------------------------------------------------------------===//
1577
1578 #include "X86GenCallingConv.inc"
1579
1580 bool
1581 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1582                                   MachineFunction &MF, bool isVarArg,
1583                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1584                         LLVMContext &Context) const {
1585   SmallVector<CCValAssign, 16> RVLocs;
1586   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1587                  RVLocs, Context);
1588   return CCInfo.CheckReturn(Outs, RetCC_X86);
1589 }
1590
1591 SDValue
1592 X86TargetLowering::LowerReturn(SDValue Chain,
1593                                CallingConv::ID CallConv, bool isVarArg,
1594                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1595                                const SmallVectorImpl<SDValue> &OutVals,
1596                                DebugLoc dl, SelectionDAG &DAG) const {
1597   MachineFunction &MF = DAG.getMachineFunction();
1598   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1599
1600   SmallVector<CCValAssign, 16> RVLocs;
1601   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1602                  RVLocs, *DAG.getContext());
1603   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1604
1605   SDValue Flag;
1606   SmallVector<SDValue, 6> RetOps;
1607   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1608   // Operand #1 = Bytes To Pop
1609   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1610                    MVT::i16));
1611
1612   // Copy the result values into the output registers.
1613   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1614     CCValAssign &VA = RVLocs[i];
1615     assert(VA.isRegLoc() && "Can only return in registers!");
1616     SDValue ValToCopy = OutVals[i];
1617     EVT ValVT = ValToCopy.getValueType();
1618
1619     // Promote values to the appropriate types
1620     if (VA.getLocInfo() == CCValAssign::SExt)
1621       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1622     else if (VA.getLocInfo() == CCValAssign::ZExt)
1623       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1624     else if (VA.getLocInfo() == CCValAssign::AExt)
1625       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1626     else if (VA.getLocInfo() == CCValAssign::BCvt)
1627       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1628
1629     // If this is x86-64, and we disabled SSE, we can't return FP values,
1630     // or SSE or MMX vectors.
1631     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1632          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1633           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1634       report_fatal_error("SSE register return with SSE disabled");
1635     }
1636     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1637     // llvm-gcc has never done it right and no one has noticed, so this
1638     // should be OK for now.
1639     if (ValVT == MVT::f64 &&
1640         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1641       report_fatal_error("SSE2 register return with SSE2 disabled");
1642
1643     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1644     // the RET instruction and handled by the FP Stackifier.
1645     if (VA.getLocReg() == X86::ST0 ||
1646         VA.getLocReg() == X86::ST1) {
1647       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1648       // change the value to the FP stack register class.
1649       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1650         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1651       RetOps.push_back(ValToCopy);
1652       // Don't emit a copytoreg.
1653       continue;
1654     }
1655
1656     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1657     // which is returned in RAX / RDX.
1658     if (Subtarget->is64Bit()) {
1659       if (ValVT == MVT::x86mmx) {
1660         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1661           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1662           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1663                                   ValToCopy);
1664           // If we don't have SSE2 available, convert to v4f32 so the generated
1665           // register is legal.
1666           if (!Subtarget->hasSSE2())
1667             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1668         }
1669       }
1670     }
1671
1672     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1673     Flag = Chain.getValue(1);
1674     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1675   }
1676
1677   // The x86-64 ABIs require that for returning structs by value we copy
1678   // the sret argument into %rax/%eax (depending on ABI) for the return.
1679   // Win32 requires us to put the sret argument to %eax as well.
1680   // We saved the argument into a virtual register in the entry block,
1681   // so now we copy the value out and into %rax/%eax.
1682   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1683       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1684     MachineFunction &MF = DAG.getMachineFunction();
1685     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1686     unsigned Reg = FuncInfo->getSRetReturnReg();
1687     assert(Reg &&
1688            "SRetReturnReg should have been set in LowerFormalArguments().");
1689     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1690
1691     unsigned RetValReg
1692         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1693           X86::RAX : X86::EAX;
1694     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1695     Flag = Chain.getValue(1);
1696
1697     // RAX/EAX now acts like a return value.
1698     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1699   }
1700
1701   RetOps[0] = Chain;  // Update chain.
1702
1703   // Add the flag if we have it.
1704   if (Flag.getNode())
1705     RetOps.push_back(Flag);
1706
1707   return DAG.getNode(X86ISD::RET_FLAG, dl,
1708                      MVT::Other, &RetOps[0], RetOps.size());
1709 }
1710
1711 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1712   if (N->getNumValues() != 1)
1713     return false;
1714   if (!N->hasNUsesOfValue(1, 0))
1715     return false;
1716
1717   SDValue TCChain = Chain;
1718   SDNode *Copy = *N->use_begin();
1719   if (Copy->getOpcode() == ISD::CopyToReg) {
1720     // If the copy has a glue operand, we conservatively assume it isn't safe to
1721     // perform a tail call.
1722     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1723       return false;
1724     TCChain = Copy->getOperand(0);
1725   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1726     return false;
1727
1728   bool HasRet = false;
1729   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1730        UI != UE; ++UI) {
1731     if (UI->getOpcode() != X86ISD::RET_FLAG)
1732       return false;
1733     HasRet = true;
1734   }
1735
1736   if (!HasRet)
1737     return false;
1738
1739   Chain = TCChain;
1740   return true;
1741 }
1742
1743 MVT
1744 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1745                                             ISD::NodeType ExtendKind) const {
1746   MVT ReturnMVT;
1747   // TODO: Is this also valid on 32-bit?
1748   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1749     ReturnMVT = MVT::i8;
1750   else
1751     ReturnMVT = MVT::i32;
1752
1753   MVT MinVT = getRegisterType(ReturnMVT);
1754   return VT.bitsLT(MinVT) ? MinVT : VT;
1755 }
1756
1757 /// LowerCallResult - Lower the result values of a call into the
1758 /// appropriate copies out of appropriate physical registers.
1759 ///
1760 SDValue
1761 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1762                                    CallingConv::ID CallConv, bool isVarArg,
1763                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1764                                    DebugLoc dl, SelectionDAG &DAG,
1765                                    SmallVectorImpl<SDValue> &InVals) const {
1766
1767   // Assign locations to each value returned by this call.
1768   SmallVector<CCValAssign, 16> RVLocs;
1769   bool Is64Bit = Subtarget->is64Bit();
1770   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1771                  getTargetMachine(), RVLocs, *DAG.getContext());
1772   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1773
1774   // Copy all of the result registers out of their specified physreg.
1775   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1776     CCValAssign &VA = RVLocs[i];
1777     EVT CopyVT = VA.getValVT();
1778
1779     // If this is x86-64, and we disabled SSE, we can't return FP values
1780     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1781         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1782       report_fatal_error("SSE register return with SSE disabled");
1783     }
1784
1785     SDValue Val;
1786
1787     // If this is a call to a function that returns an fp value on the floating
1788     // point stack, we must guarantee the value is popped from the stack, so
1789     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1790     // if the return value is not used. We use the FpPOP_RETVAL instruction
1791     // instead.
1792     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1793       // If we prefer to use the value in xmm registers, copy it out as f80 and
1794       // use a truncate to move it from fp stack reg to xmm reg.
1795       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1796       SDValue Ops[] = { Chain, InFlag };
1797       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1798                                          MVT::Other, MVT::Glue, Ops), 1);
1799       Val = Chain.getValue(0);
1800
1801       // Round the f80 to the right size, which also moves it to the appropriate
1802       // xmm register.
1803       if (CopyVT != VA.getValVT())
1804         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1805                           // This truncation won't change the value.
1806                           DAG.getIntPtrConstant(1));
1807     } else {
1808       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1809                                  CopyVT, InFlag).getValue(1);
1810       Val = Chain.getValue(0);
1811     }
1812     InFlag = Chain.getValue(2);
1813     InVals.push_back(Val);
1814   }
1815
1816   return Chain;
1817 }
1818
1819 //===----------------------------------------------------------------------===//
1820 //                C & StdCall & Fast Calling Convention implementation
1821 //===----------------------------------------------------------------------===//
1822 //  StdCall calling convention seems to be standard for many Windows' API
1823 //  routines and around. It differs from C calling convention just a little:
1824 //  callee should clean up the stack, not caller. Symbols should be also
1825 //  decorated in some fancy way :) It doesn't support any vector arguments.
1826 //  For info on fast calling convention see Fast Calling Convention (tail call)
1827 //  implementation LowerX86_32FastCCCallTo.
1828
1829 /// CallIsStructReturn - Determines whether a call uses struct return
1830 /// semantics.
1831 enum StructReturnType {
1832   NotStructReturn,
1833   RegStructReturn,
1834   StackStructReturn
1835 };
1836 static StructReturnType
1837 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1838   if (Outs.empty())
1839     return NotStructReturn;
1840
1841   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1842   if (!Flags.isSRet())
1843     return NotStructReturn;
1844   if (Flags.isInReg())
1845     return RegStructReturn;
1846   return StackStructReturn;
1847 }
1848
1849 /// ArgsAreStructReturn - Determines whether a function uses struct
1850 /// return semantics.
1851 static StructReturnType
1852 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1853   if (Ins.empty())
1854     return NotStructReturn;
1855
1856   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1857   if (!Flags.isSRet())
1858     return NotStructReturn;
1859   if (Flags.isInReg())
1860     return RegStructReturn;
1861   return StackStructReturn;
1862 }
1863
1864 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1865 /// by "Src" to address "Dst" with size and alignment information specified by
1866 /// the specific parameter attribute. The copy will be passed as a byval
1867 /// function parameter.
1868 static SDValue
1869 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1870                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1871                           DebugLoc dl) {
1872   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1873
1874   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1875                        /*isVolatile*/false, /*AlwaysInline=*/true,
1876                        MachinePointerInfo(), MachinePointerInfo());
1877 }
1878
1879 /// IsTailCallConvention - Return true if the calling convention is one that
1880 /// supports tail call optimization.
1881 static bool IsTailCallConvention(CallingConv::ID CC) {
1882   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1883           CC == CallingConv::HiPE);
1884 }
1885
1886 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1887   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1888     return false;
1889
1890   CallSite CS(CI);
1891   CallingConv::ID CalleeCC = CS.getCallingConv();
1892   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1893     return false;
1894
1895   return true;
1896 }
1897
1898 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1899 /// a tailcall target by changing its ABI.
1900 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1901                                    bool GuaranteedTailCallOpt) {
1902   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1903 }
1904
1905 SDValue
1906 X86TargetLowering::LowerMemArgument(SDValue Chain,
1907                                     CallingConv::ID CallConv,
1908                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1909                                     DebugLoc dl, SelectionDAG &DAG,
1910                                     const CCValAssign &VA,
1911                                     MachineFrameInfo *MFI,
1912                                     unsigned i) const {
1913   // Create the nodes corresponding to a load from this parameter slot.
1914   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1915   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1916                               getTargetMachine().Options.GuaranteedTailCallOpt);
1917   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1918   EVT ValVT;
1919
1920   // If value is passed by pointer we have address passed instead of the value
1921   // itself.
1922   if (VA.getLocInfo() == CCValAssign::Indirect)
1923     ValVT = VA.getLocVT();
1924   else
1925     ValVT = VA.getValVT();
1926
1927   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1928   // changed with more analysis.
1929   // In case of tail call optimization mark all arguments mutable. Since they
1930   // could be overwritten by lowering of arguments in case of a tail call.
1931   if (Flags.isByVal()) {
1932     unsigned Bytes = Flags.getByValSize();
1933     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1934     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1935     return DAG.getFrameIndex(FI, getPointerTy());
1936   } else {
1937     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1938                                     VA.getLocMemOffset(), isImmutable);
1939     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1940     return DAG.getLoad(ValVT, dl, Chain, FIN,
1941                        MachinePointerInfo::getFixedStack(FI),
1942                        false, false, false, 0);
1943   }
1944 }
1945
1946 SDValue
1947 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1948                                         CallingConv::ID CallConv,
1949                                         bool isVarArg,
1950                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1951                                         DebugLoc dl,
1952                                         SelectionDAG &DAG,
1953                                         SmallVectorImpl<SDValue> &InVals)
1954                                           const {
1955   MachineFunction &MF = DAG.getMachineFunction();
1956   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1957
1958   const Function* Fn = MF.getFunction();
1959   if (Fn->hasExternalLinkage() &&
1960       Subtarget->isTargetCygMing() &&
1961       Fn->getName() == "main")
1962     FuncInfo->setForceFramePointer(true);
1963
1964   MachineFrameInfo *MFI = MF.getFrameInfo();
1965   bool Is64Bit = Subtarget->is64Bit();
1966   bool IsWindows = Subtarget->isTargetWindows();
1967   bool IsWin64 = Subtarget->isTargetWin64();
1968
1969   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1970          "Var args not supported with calling convention fastcc, ghc or hipe");
1971
1972   // Assign locations to all of the incoming arguments.
1973   SmallVector<CCValAssign, 16> ArgLocs;
1974   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1975                  ArgLocs, *DAG.getContext());
1976
1977   // Allocate shadow area for Win64
1978   if (IsWin64) {
1979     CCInfo.AllocateStack(32, 8);
1980   }
1981
1982   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1983
1984   unsigned LastVal = ~0U;
1985   SDValue ArgValue;
1986   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1987     CCValAssign &VA = ArgLocs[i];
1988     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1989     // places.
1990     assert(VA.getValNo() != LastVal &&
1991            "Don't support value assigned to multiple locs yet");
1992     (void)LastVal;
1993     LastVal = VA.getValNo();
1994
1995     if (VA.isRegLoc()) {
1996       EVT RegVT = VA.getLocVT();
1997       const TargetRegisterClass *RC;
1998       if (RegVT == MVT::i32)
1999         RC = &X86::GR32RegClass;
2000       else if (Is64Bit && RegVT == MVT::i64)
2001         RC = &X86::GR64RegClass;
2002       else if (RegVT == MVT::f32)
2003         RC = &X86::FR32RegClass;
2004       else if (RegVT == MVT::f64)
2005         RC = &X86::FR64RegClass;
2006       else if (RegVT.is256BitVector())
2007         RC = &X86::VR256RegClass;
2008       else if (RegVT.is128BitVector())
2009         RC = &X86::VR128RegClass;
2010       else if (RegVT == MVT::x86mmx)
2011         RC = &X86::VR64RegClass;
2012       else
2013         llvm_unreachable("Unknown argument type!");
2014
2015       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2016       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2017
2018       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2019       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2020       // right size.
2021       if (VA.getLocInfo() == CCValAssign::SExt)
2022         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2023                                DAG.getValueType(VA.getValVT()));
2024       else if (VA.getLocInfo() == CCValAssign::ZExt)
2025         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2026                                DAG.getValueType(VA.getValVT()));
2027       else if (VA.getLocInfo() == CCValAssign::BCvt)
2028         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2029
2030       if (VA.isExtInLoc()) {
2031         // Handle MMX values passed in XMM regs.
2032         if (RegVT.isVector())
2033           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2034         else
2035           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2036       }
2037     } else {
2038       assert(VA.isMemLoc());
2039       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2040     }
2041
2042     // If value is passed via pointer - do a load.
2043     if (VA.getLocInfo() == CCValAssign::Indirect)
2044       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2045                              MachinePointerInfo(), false, false, false, 0);
2046
2047     InVals.push_back(ArgValue);
2048   }
2049
2050   // The x86-64 ABIs require that for returning structs by value we copy
2051   // the sret argument into %rax/%eax (depending on ABI) for the return.
2052   // Win32 requires us to put the sret argument to %eax as well.
2053   // Save the argument into a virtual register so that we can access it
2054   // from the return points.
2055   if (MF.getFunction()->hasStructRetAttr() &&
2056       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2057     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2058     unsigned Reg = FuncInfo->getSRetReturnReg();
2059     if (!Reg) {
2060       MVT PtrTy = getPointerTy();
2061       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2062       FuncInfo->setSRetReturnReg(Reg);
2063     }
2064     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2065     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2066   }
2067
2068   unsigned StackSize = CCInfo.getNextStackOffset();
2069   // Align stack specially for tail calls.
2070   if (FuncIsMadeTailCallSafe(CallConv,
2071                              MF.getTarget().Options.GuaranteedTailCallOpt))
2072     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2073
2074   // If the function takes variable number of arguments, make a frame index for
2075   // the start of the first vararg value... for expansion of llvm.va_start.
2076   if (isVarArg) {
2077     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2078                     CallConv != CallingConv::X86_ThisCall)) {
2079       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2080     }
2081     if (Is64Bit) {
2082       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2083
2084       // FIXME: We should really autogenerate these arrays
2085       static const uint16_t GPR64ArgRegsWin64[] = {
2086         X86::RCX, X86::RDX, X86::R8,  X86::R9
2087       };
2088       static const uint16_t GPR64ArgRegs64Bit[] = {
2089         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2090       };
2091       static const uint16_t XMMArgRegs64Bit[] = {
2092         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2093         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2094       };
2095       const uint16_t *GPR64ArgRegs;
2096       unsigned NumXMMRegs = 0;
2097
2098       if (IsWin64) {
2099         // The XMM registers which might contain var arg parameters are shadowed
2100         // in their paired GPR.  So we only need to save the GPR to their home
2101         // slots.
2102         TotalNumIntRegs = 4;
2103         GPR64ArgRegs = GPR64ArgRegsWin64;
2104       } else {
2105         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2106         GPR64ArgRegs = GPR64ArgRegs64Bit;
2107
2108         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2109                                                 TotalNumXMMRegs);
2110       }
2111       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2112                                                        TotalNumIntRegs);
2113
2114       bool NoImplicitFloatOps = Fn->getAttributes().
2115         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2116       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2117              "SSE register cannot be used when SSE is disabled!");
2118       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2119                NoImplicitFloatOps) &&
2120              "SSE register cannot be used when SSE is disabled!");
2121       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2122           !Subtarget->hasSSE1())
2123         // Kernel mode asks for SSE to be disabled, so don't push them
2124         // on the stack.
2125         TotalNumXMMRegs = 0;
2126
2127       if (IsWin64) {
2128         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2129         // Get to the caller-allocated home save location.  Add 8 to account
2130         // for the return address.
2131         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2132         FuncInfo->setRegSaveFrameIndex(
2133           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2134         // Fixup to set vararg frame on shadow area (4 x i64).
2135         if (NumIntRegs < 4)
2136           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2137       } else {
2138         // For X86-64, if there are vararg parameters that are passed via
2139         // registers, then we must store them to their spots on the stack so
2140         // they may be loaded by deferencing the result of va_next.
2141         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2142         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2143         FuncInfo->setRegSaveFrameIndex(
2144           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2145                                false));
2146       }
2147
2148       // Store the integer parameter registers.
2149       SmallVector<SDValue, 8> MemOps;
2150       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2151                                         getPointerTy());
2152       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2153       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2154         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2155                                   DAG.getIntPtrConstant(Offset));
2156         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2157                                      &X86::GR64RegClass);
2158         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2159         SDValue Store =
2160           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2161                        MachinePointerInfo::getFixedStack(
2162                          FuncInfo->getRegSaveFrameIndex(), Offset),
2163                        false, false, 0);
2164         MemOps.push_back(Store);
2165         Offset += 8;
2166       }
2167
2168       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2169         // Now store the XMM (fp + vector) parameter registers.
2170         SmallVector<SDValue, 11> SaveXMMOps;
2171         SaveXMMOps.push_back(Chain);
2172
2173         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2174         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2175         SaveXMMOps.push_back(ALVal);
2176
2177         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2178                                FuncInfo->getRegSaveFrameIndex()));
2179         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2180                                FuncInfo->getVarArgsFPOffset()));
2181
2182         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2183           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2184                                        &X86::VR128RegClass);
2185           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2186           SaveXMMOps.push_back(Val);
2187         }
2188         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2189                                      MVT::Other,
2190                                      &SaveXMMOps[0], SaveXMMOps.size()));
2191       }
2192
2193       if (!MemOps.empty())
2194         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2195                             &MemOps[0], MemOps.size());
2196     }
2197   }
2198
2199   // Some CCs need callee pop.
2200   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2201                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2202     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2203   } else {
2204     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2205     // If this is an sret function, the return should pop the hidden pointer.
2206     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2207         argsAreStructReturn(Ins) == StackStructReturn)
2208       FuncInfo->setBytesToPopOnReturn(4);
2209   }
2210
2211   if (!Is64Bit) {
2212     // RegSaveFrameIndex is X86-64 only.
2213     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2214     if (CallConv == CallingConv::X86_FastCall ||
2215         CallConv == CallingConv::X86_ThisCall)
2216       // fastcc functions can't have varargs.
2217       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2218   }
2219
2220   FuncInfo->setArgumentStackSize(StackSize);
2221
2222   return Chain;
2223 }
2224
2225 SDValue
2226 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2227                                     SDValue StackPtr, SDValue Arg,
2228                                     DebugLoc dl, SelectionDAG &DAG,
2229                                     const CCValAssign &VA,
2230                                     ISD::ArgFlagsTy Flags) const {
2231   unsigned LocMemOffset = VA.getLocMemOffset();
2232   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2233   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2234   if (Flags.isByVal())
2235     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2236
2237   return DAG.getStore(Chain, dl, Arg, PtrOff,
2238                       MachinePointerInfo::getStack(LocMemOffset),
2239                       false, false, 0);
2240 }
2241
2242 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2243 /// optimization is performed and it is required.
2244 SDValue
2245 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2246                                            SDValue &OutRetAddr, SDValue Chain,
2247                                            bool IsTailCall, bool Is64Bit,
2248                                            int FPDiff, DebugLoc dl) const {
2249   // Adjust the Return address stack slot.
2250   EVT VT = getPointerTy();
2251   OutRetAddr = getReturnAddressFrameIndex(DAG);
2252
2253   // Load the "old" Return address.
2254   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2255                            false, false, false, 0);
2256   return SDValue(OutRetAddr.getNode(), 1);
2257 }
2258
2259 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2260 /// optimization is performed and it is required (FPDiff!=0).
2261 static SDValue
2262 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2263                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2264                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2265   // Store the return address to the appropriate stack slot.
2266   if (!FPDiff) return Chain;
2267   // Calculate the new stack slot for the return address.
2268   int NewReturnAddrFI =
2269     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2270   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2271   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2272                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2273                        false, false, 0);
2274   return Chain;
2275 }
2276
2277 SDValue
2278 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2279                              SmallVectorImpl<SDValue> &InVals) const {
2280   SelectionDAG &DAG                     = CLI.DAG;
2281   DebugLoc &dl                          = CLI.DL;
2282   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2283   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2284   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2285   SDValue Chain                         = CLI.Chain;
2286   SDValue Callee                        = CLI.Callee;
2287   CallingConv::ID CallConv              = CLI.CallConv;
2288   bool &isTailCall                      = CLI.IsTailCall;
2289   bool isVarArg                         = CLI.IsVarArg;
2290
2291   MachineFunction &MF = DAG.getMachineFunction();
2292   bool Is64Bit        = Subtarget->is64Bit();
2293   bool IsWin64        = Subtarget->isTargetWin64();
2294   bool IsWindows      = Subtarget->isTargetWindows();
2295   StructReturnType SR = callIsStructReturn(Outs);
2296   bool IsSibcall      = false;
2297
2298   if (MF.getTarget().Options.DisableTailCalls)
2299     isTailCall = false;
2300
2301   if (isTailCall) {
2302     // Check if it's really possible to do a tail call.
2303     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2304                     isVarArg, SR != NotStructReturn,
2305                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2306                     Outs, OutVals, Ins, DAG);
2307
2308     // Sibcalls are automatically detected tailcalls which do not require
2309     // ABI changes.
2310     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2311       IsSibcall = true;
2312
2313     if (isTailCall)
2314       ++NumTailCalls;
2315   }
2316
2317   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2318          "Var args not supported with calling convention fastcc, ghc or hipe");
2319
2320   // Analyze operands of the call, assigning locations to each operand.
2321   SmallVector<CCValAssign, 16> ArgLocs;
2322   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2323                  ArgLocs, *DAG.getContext());
2324
2325   // Allocate shadow area for Win64
2326   if (IsWin64) {
2327     CCInfo.AllocateStack(32, 8);
2328   }
2329
2330   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2331
2332   // Get a count of how many bytes are to be pushed on the stack.
2333   unsigned NumBytes = CCInfo.getNextStackOffset();
2334   if (IsSibcall)
2335     // This is a sibcall. The memory operands are available in caller's
2336     // own caller's stack.
2337     NumBytes = 0;
2338   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2339            IsTailCallConvention(CallConv))
2340     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2341
2342   int FPDiff = 0;
2343   if (isTailCall && !IsSibcall) {
2344     // Lower arguments at fp - stackoffset + fpdiff.
2345     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2346     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2347
2348     FPDiff = NumBytesCallerPushed - NumBytes;
2349
2350     // Set the delta of movement of the returnaddr stackslot.
2351     // But only set if delta is greater than previous delta.
2352     if (FPDiff < X86Info->getTCReturnAddrDelta())
2353       X86Info->setTCReturnAddrDelta(FPDiff);
2354   }
2355
2356   if (!IsSibcall)
2357     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2358
2359   SDValue RetAddrFrIdx;
2360   // Load return address for tail calls.
2361   if (isTailCall && FPDiff)
2362     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2363                                     Is64Bit, FPDiff, dl);
2364
2365   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2366   SmallVector<SDValue, 8> MemOpChains;
2367   SDValue StackPtr;
2368
2369   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2370   // of tail call optimization arguments are handle later.
2371   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2372     CCValAssign &VA = ArgLocs[i];
2373     EVT RegVT = VA.getLocVT();
2374     SDValue Arg = OutVals[i];
2375     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2376     bool isByVal = Flags.isByVal();
2377
2378     // Promote the value if needed.
2379     switch (VA.getLocInfo()) {
2380     default: llvm_unreachable("Unknown loc info!");
2381     case CCValAssign::Full: break;
2382     case CCValAssign::SExt:
2383       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2384       break;
2385     case CCValAssign::ZExt:
2386       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2387       break;
2388     case CCValAssign::AExt:
2389       if (RegVT.is128BitVector()) {
2390         // Special case: passing MMX values in XMM registers.
2391         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2392         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2393         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2394       } else
2395         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2396       break;
2397     case CCValAssign::BCvt:
2398       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2399       break;
2400     case CCValAssign::Indirect: {
2401       // Store the argument.
2402       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2403       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2404       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2405                            MachinePointerInfo::getFixedStack(FI),
2406                            false, false, 0);
2407       Arg = SpillSlot;
2408       break;
2409     }
2410     }
2411
2412     if (VA.isRegLoc()) {
2413       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2414       if (isVarArg && IsWin64) {
2415         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2416         // shadow reg if callee is a varargs function.
2417         unsigned ShadowReg = 0;
2418         switch (VA.getLocReg()) {
2419         case X86::XMM0: ShadowReg = X86::RCX; break;
2420         case X86::XMM1: ShadowReg = X86::RDX; break;
2421         case X86::XMM2: ShadowReg = X86::R8; break;
2422         case X86::XMM3: ShadowReg = X86::R9; break;
2423         }
2424         if (ShadowReg)
2425           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2426       }
2427     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2428       assert(VA.isMemLoc());
2429       if (StackPtr.getNode() == 0)
2430         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2431                                       getPointerTy());
2432       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2433                                              dl, DAG, VA, Flags));
2434     }
2435   }
2436
2437   if (!MemOpChains.empty())
2438     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2439                         &MemOpChains[0], MemOpChains.size());
2440
2441   if (Subtarget->isPICStyleGOT()) {
2442     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2443     // GOT pointer.
2444     if (!isTailCall) {
2445       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2446                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2447     } else {
2448       // If we are tail calling and generating PIC/GOT style code load the
2449       // address of the callee into ECX. The value in ecx is used as target of
2450       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2451       // for tail calls on PIC/GOT architectures. Normally we would just put the
2452       // address of GOT into ebx and then call target@PLT. But for tail calls
2453       // ebx would be restored (since ebx is callee saved) before jumping to the
2454       // target@PLT.
2455
2456       // Note: The actual moving to ECX is done further down.
2457       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2458       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2459           !G->getGlobal()->hasProtectedVisibility())
2460         Callee = LowerGlobalAddress(Callee, DAG);
2461       else if (isa<ExternalSymbolSDNode>(Callee))
2462         Callee = LowerExternalSymbol(Callee, DAG);
2463     }
2464   }
2465
2466   if (Is64Bit && isVarArg && !IsWin64) {
2467     // From AMD64 ABI document:
2468     // For calls that may call functions that use varargs or stdargs
2469     // (prototype-less calls or calls to functions containing ellipsis (...) in
2470     // the declaration) %al is used as hidden argument to specify the number
2471     // of SSE registers used. The contents of %al do not need to match exactly
2472     // the number of registers, but must be an ubound on the number of SSE
2473     // registers used and is in the range 0 - 8 inclusive.
2474
2475     // Count the number of XMM registers allocated.
2476     static const uint16_t XMMArgRegs[] = {
2477       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2478       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2479     };
2480     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2481     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2482            && "SSE registers cannot be used when SSE is disabled");
2483
2484     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2485                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2486   }
2487
2488   // For tail calls lower the arguments to the 'real' stack slot.
2489   if (isTailCall) {
2490     // Force all the incoming stack arguments to be loaded from the stack
2491     // before any new outgoing arguments are stored to the stack, because the
2492     // outgoing stack slots may alias the incoming argument stack slots, and
2493     // the alias isn't otherwise explicit. This is slightly more conservative
2494     // than necessary, because it means that each store effectively depends
2495     // on every argument instead of just those arguments it would clobber.
2496     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2497
2498     SmallVector<SDValue, 8> MemOpChains2;
2499     SDValue FIN;
2500     int FI = 0;
2501     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2502       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2503         CCValAssign &VA = ArgLocs[i];
2504         if (VA.isRegLoc())
2505           continue;
2506         assert(VA.isMemLoc());
2507         SDValue Arg = OutVals[i];
2508         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2509         // Create frame index.
2510         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2511         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2512         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2513         FIN = DAG.getFrameIndex(FI, getPointerTy());
2514
2515         if (Flags.isByVal()) {
2516           // Copy relative to framepointer.
2517           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2518           if (StackPtr.getNode() == 0)
2519             StackPtr = DAG.getCopyFromReg(Chain, dl,
2520                                           RegInfo->getStackRegister(),
2521                                           getPointerTy());
2522           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2523
2524           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2525                                                            ArgChain,
2526                                                            Flags, DAG, dl));
2527         } else {
2528           // Store relative to framepointer.
2529           MemOpChains2.push_back(
2530             DAG.getStore(ArgChain, dl, Arg, FIN,
2531                          MachinePointerInfo::getFixedStack(FI),
2532                          false, false, 0));
2533         }
2534       }
2535     }
2536
2537     if (!MemOpChains2.empty())
2538       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2539                           &MemOpChains2[0], MemOpChains2.size());
2540
2541     // Store the return address to the appropriate stack slot.
2542     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2543                                      getPointerTy(), RegInfo->getSlotSize(),
2544                                      FPDiff, dl);
2545   }
2546
2547   // Build a sequence of copy-to-reg nodes chained together with token chain
2548   // and flag operands which copy the outgoing args into registers.
2549   SDValue InFlag;
2550   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2551     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2552                              RegsToPass[i].second, InFlag);
2553     InFlag = Chain.getValue(1);
2554   }
2555
2556   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2557     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2558     // In the 64-bit large code model, we have to make all calls
2559     // through a register, since the call instruction's 32-bit
2560     // pc-relative offset may not be large enough to hold the whole
2561     // address.
2562   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2563     // If the callee is a GlobalAddress node (quite common, every direct call
2564     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2565     // it.
2566
2567     // We should use extra load for direct calls to dllimported functions in
2568     // non-JIT mode.
2569     const GlobalValue *GV = G->getGlobal();
2570     if (!GV->hasDLLImportLinkage()) {
2571       unsigned char OpFlags = 0;
2572       bool ExtraLoad = false;
2573       unsigned WrapperKind = ISD::DELETED_NODE;
2574
2575       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2576       // external symbols most go through the PLT in PIC mode.  If the symbol
2577       // has hidden or protected visibility, or if it is static or local, then
2578       // we don't need to use the PLT - we can directly call it.
2579       if (Subtarget->isTargetELF() &&
2580           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2581           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2582         OpFlags = X86II::MO_PLT;
2583       } else if (Subtarget->isPICStyleStubAny() &&
2584                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2585                  (!Subtarget->getTargetTriple().isMacOSX() ||
2586                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2587         // PC-relative references to external symbols should go through $stub,
2588         // unless we're building with the leopard linker or later, which
2589         // automatically synthesizes these stubs.
2590         OpFlags = X86II::MO_DARWIN_STUB;
2591       } else if (Subtarget->isPICStyleRIPRel() &&
2592                  isa<Function>(GV) &&
2593                  cast<Function>(GV)->getAttributes().
2594                    hasAttribute(AttributeSet::FunctionIndex,
2595                                 Attribute::NonLazyBind)) {
2596         // If the function is marked as non-lazy, generate an indirect call
2597         // which loads from the GOT directly. This avoids runtime overhead
2598         // at the cost of eager binding (and one extra byte of encoding).
2599         OpFlags = X86II::MO_GOTPCREL;
2600         WrapperKind = X86ISD::WrapperRIP;
2601         ExtraLoad = true;
2602       }
2603
2604       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2605                                           G->getOffset(), OpFlags);
2606
2607       // Add a wrapper if needed.
2608       if (WrapperKind != ISD::DELETED_NODE)
2609         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2610       // Add extra indirection if needed.
2611       if (ExtraLoad)
2612         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2613                              MachinePointerInfo::getGOT(),
2614                              false, false, false, 0);
2615     }
2616   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2617     unsigned char OpFlags = 0;
2618
2619     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2620     // external symbols should go through the PLT.
2621     if (Subtarget->isTargetELF() &&
2622         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2623       OpFlags = X86II::MO_PLT;
2624     } else if (Subtarget->isPICStyleStubAny() &&
2625                (!Subtarget->getTargetTriple().isMacOSX() ||
2626                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2627       // PC-relative references to external symbols should go through $stub,
2628       // unless we're building with the leopard linker or later, which
2629       // automatically synthesizes these stubs.
2630       OpFlags = X86II::MO_DARWIN_STUB;
2631     }
2632
2633     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2634                                          OpFlags);
2635   }
2636
2637   // Returns a chain & a flag for retval copy to use.
2638   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2639   SmallVector<SDValue, 8> Ops;
2640
2641   if (!IsSibcall && isTailCall) {
2642     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2643                            DAG.getIntPtrConstant(0, true), InFlag);
2644     InFlag = Chain.getValue(1);
2645   }
2646
2647   Ops.push_back(Chain);
2648   Ops.push_back(Callee);
2649
2650   if (isTailCall)
2651     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2652
2653   // Add argument registers to the end of the list so that they are known live
2654   // into the call.
2655   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2656     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2657                                   RegsToPass[i].second.getValueType()));
2658
2659   // Add a register mask operand representing the call-preserved registers.
2660   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2661   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2662   assert(Mask && "Missing call preserved mask for calling convention");
2663   Ops.push_back(DAG.getRegisterMask(Mask));
2664
2665   if (InFlag.getNode())
2666     Ops.push_back(InFlag);
2667
2668   if (isTailCall) {
2669     // We used to do:
2670     //// If this is the first return lowered for this function, add the regs
2671     //// to the liveout set for the function.
2672     // This isn't right, although it's probably harmless on x86; liveouts
2673     // should be computed from returns not tail calls.  Consider a void
2674     // function making a tail call to a function returning int.
2675     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2676   }
2677
2678   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2679   InFlag = Chain.getValue(1);
2680
2681   // Create the CALLSEQ_END node.
2682   unsigned NumBytesForCalleeToPush;
2683   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2684                        getTargetMachine().Options.GuaranteedTailCallOpt))
2685     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2686   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2687            SR == StackStructReturn)
2688     // If this is a call to a struct-return function, the callee
2689     // pops the hidden struct pointer, so we have to push it back.
2690     // This is common for Darwin/X86, Linux & Mingw32 targets.
2691     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2692     NumBytesForCalleeToPush = 4;
2693   else
2694     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2695
2696   // Returns a flag for retval copy to use.
2697   if (!IsSibcall) {
2698     Chain = DAG.getCALLSEQ_END(Chain,
2699                                DAG.getIntPtrConstant(NumBytes, true),
2700                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2701                                                      true),
2702                                InFlag);
2703     InFlag = Chain.getValue(1);
2704   }
2705
2706   // Handle result values, copying them out of physregs into vregs that we
2707   // return.
2708   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2709                          Ins, dl, DAG, InVals);
2710 }
2711
2712 //===----------------------------------------------------------------------===//
2713 //                Fast Calling Convention (tail call) implementation
2714 //===----------------------------------------------------------------------===//
2715
2716 //  Like std call, callee cleans arguments, convention except that ECX is
2717 //  reserved for storing the tail called function address. Only 2 registers are
2718 //  free for argument passing (inreg). Tail call optimization is performed
2719 //  provided:
2720 //                * tailcallopt is enabled
2721 //                * caller/callee are fastcc
2722 //  On X86_64 architecture with GOT-style position independent code only local
2723 //  (within module) calls are supported at the moment.
2724 //  To keep the stack aligned according to platform abi the function
2725 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2726 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2727 //  If a tail called function callee has more arguments than the caller the
2728 //  caller needs to make sure that there is room to move the RETADDR to. This is
2729 //  achieved by reserving an area the size of the argument delta right after the
2730 //  original REtADDR, but before the saved framepointer or the spilled registers
2731 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2732 //  stack layout:
2733 //    arg1
2734 //    arg2
2735 //    RETADDR
2736 //    [ new RETADDR
2737 //      move area ]
2738 //    (possible EBP)
2739 //    ESI
2740 //    EDI
2741 //    local1 ..
2742
2743 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2744 /// for a 16 byte align requirement.
2745 unsigned
2746 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2747                                                SelectionDAG& DAG) const {
2748   MachineFunction &MF = DAG.getMachineFunction();
2749   const TargetMachine &TM = MF.getTarget();
2750   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2751   unsigned StackAlignment = TFI.getStackAlignment();
2752   uint64_t AlignMask = StackAlignment - 1;
2753   int64_t Offset = StackSize;
2754   unsigned SlotSize = RegInfo->getSlotSize();
2755   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2756     // Number smaller than 12 so just add the difference.
2757     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2758   } else {
2759     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2760     Offset = ((~AlignMask) & Offset) + StackAlignment +
2761       (StackAlignment-SlotSize);
2762   }
2763   return Offset;
2764 }
2765
2766 /// MatchingStackOffset - Return true if the given stack call argument is
2767 /// already available in the same position (relatively) of the caller's
2768 /// incoming argument stack.
2769 static
2770 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2771                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2772                          const X86InstrInfo *TII) {
2773   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2774   int FI = INT_MAX;
2775   if (Arg.getOpcode() == ISD::CopyFromReg) {
2776     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2777     if (!TargetRegisterInfo::isVirtualRegister(VR))
2778       return false;
2779     MachineInstr *Def = MRI->getVRegDef(VR);
2780     if (!Def)
2781       return false;
2782     if (!Flags.isByVal()) {
2783       if (!TII->isLoadFromStackSlot(Def, FI))
2784         return false;
2785     } else {
2786       unsigned Opcode = Def->getOpcode();
2787       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2788           Def->getOperand(1).isFI()) {
2789         FI = Def->getOperand(1).getIndex();
2790         Bytes = Flags.getByValSize();
2791       } else
2792         return false;
2793     }
2794   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2795     if (Flags.isByVal())
2796       // ByVal argument is passed in as a pointer but it's now being
2797       // dereferenced. e.g.
2798       // define @foo(%struct.X* %A) {
2799       //   tail call @bar(%struct.X* byval %A)
2800       // }
2801       return false;
2802     SDValue Ptr = Ld->getBasePtr();
2803     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2804     if (!FINode)
2805       return false;
2806     FI = FINode->getIndex();
2807   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2808     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2809     FI = FINode->getIndex();
2810     Bytes = Flags.getByValSize();
2811   } else
2812     return false;
2813
2814   assert(FI != INT_MAX);
2815   if (!MFI->isFixedObjectIndex(FI))
2816     return false;
2817   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2818 }
2819
2820 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2821 /// for tail call optimization. Targets which want to do tail call
2822 /// optimization should implement this function.
2823 bool
2824 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2825                                                      CallingConv::ID CalleeCC,
2826                                                      bool isVarArg,
2827                                                      bool isCalleeStructRet,
2828                                                      bool isCallerStructRet,
2829                                                      Type *RetTy,
2830                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2831                                     const SmallVectorImpl<SDValue> &OutVals,
2832                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2833                                                      SelectionDAG &DAG) const {
2834   if (!IsTailCallConvention(CalleeCC) &&
2835       CalleeCC != CallingConv::C)
2836     return false;
2837
2838   // If -tailcallopt is specified, make fastcc functions tail-callable.
2839   const MachineFunction &MF = DAG.getMachineFunction();
2840   const Function *CallerF = DAG.getMachineFunction().getFunction();
2841
2842   // If the function return type is x86_fp80 and the callee return type is not,
2843   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2844   // perform a tailcall optimization here.
2845   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2846     return false;
2847
2848   CallingConv::ID CallerCC = CallerF->getCallingConv();
2849   bool CCMatch = CallerCC == CalleeCC;
2850
2851   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2852     if (IsTailCallConvention(CalleeCC) && CCMatch)
2853       return true;
2854     return false;
2855   }
2856
2857   // Look for obvious safe cases to perform tail call optimization that do not
2858   // require ABI changes. This is what gcc calls sibcall.
2859
2860   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2861   // emit a special epilogue.
2862   if (RegInfo->needsStackRealignment(MF))
2863     return false;
2864
2865   // Also avoid sibcall optimization if either caller or callee uses struct
2866   // return semantics.
2867   if (isCalleeStructRet || isCallerStructRet)
2868     return false;
2869
2870   // An stdcall caller is expected to clean up its arguments; the callee
2871   // isn't going to do that.
2872   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2873     return false;
2874
2875   // Do not sibcall optimize vararg calls unless all arguments are passed via
2876   // registers.
2877   if (isVarArg && !Outs.empty()) {
2878
2879     // Optimizing for varargs on Win64 is unlikely to be safe without
2880     // additional testing.
2881     if (Subtarget->isTargetWin64())
2882       return false;
2883
2884     SmallVector<CCValAssign, 16> ArgLocs;
2885     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2886                    getTargetMachine(), ArgLocs, *DAG.getContext());
2887
2888     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2889     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2890       if (!ArgLocs[i].isRegLoc())
2891         return false;
2892   }
2893
2894   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2895   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2896   // this into a sibcall.
2897   bool Unused = false;
2898   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2899     if (!Ins[i].Used) {
2900       Unused = true;
2901       break;
2902     }
2903   }
2904   if (Unused) {
2905     SmallVector<CCValAssign, 16> RVLocs;
2906     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2907                    getTargetMachine(), RVLocs, *DAG.getContext());
2908     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2909     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2910       CCValAssign &VA = RVLocs[i];
2911       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2912         return false;
2913     }
2914   }
2915
2916   // If the calling conventions do not match, then we'd better make sure the
2917   // results are returned in the same way as what the caller expects.
2918   if (!CCMatch) {
2919     SmallVector<CCValAssign, 16> RVLocs1;
2920     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2921                     getTargetMachine(), RVLocs1, *DAG.getContext());
2922     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2923
2924     SmallVector<CCValAssign, 16> RVLocs2;
2925     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2926                     getTargetMachine(), RVLocs2, *DAG.getContext());
2927     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2928
2929     if (RVLocs1.size() != RVLocs2.size())
2930       return false;
2931     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2932       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2933         return false;
2934       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2935         return false;
2936       if (RVLocs1[i].isRegLoc()) {
2937         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2938           return false;
2939       } else {
2940         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2941           return false;
2942       }
2943     }
2944   }
2945
2946   // If the callee takes no arguments then go on to check the results of the
2947   // call.
2948   if (!Outs.empty()) {
2949     // Check if stack adjustment is needed. For now, do not do this if any
2950     // argument is passed on the stack.
2951     SmallVector<CCValAssign, 16> ArgLocs;
2952     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2953                    getTargetMachine(), ArgLocs, *DAG.getContext());
2954
2955     // Allocate shadow area for Win64
2956     if (Subtarget->isTargetWin64()) {
2957       CCInfo.AllocateStack(32, 8);
2958     }
2959
2960     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2961     if (CCInfo.getNextStackOffset()) {
2962       MachineFunction &MF = DAG.getMachineFunction();
2963       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2964         return false;
2965
2966       // Check if the arguments are already laid out in the right way as
2967       // the caller's fixed stack objects.
2968       MachineFrameInfo *MFI = MF.getFrameInfo();
2969       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2970       const X86InstrInfo *TII =
2971         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2972       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2973         CCValAssign &VA = ArgLocs[i];
2974         SDValue Arg = OutVals[i];
2975         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2976         if (VA.getLocInfo() == CCValAssign::Indirect)
2977           return false;
2978         if (!VA.isRegLoc()) {
2979           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2980                                    MFI, MRI, TII))
2981             return false;
2982         }
2983       }
2984     }
2985
2986     // If the tailcall address may be in a register, then make sure it's
2987     // possible to register allocate for it. In 32-bit, the call address can
2988     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2989     // callee-saved registers are restored. These happen to be the same
2990     // registers used to pass 'inreg' arguments so watch out for those.
2991     if (!Subtarget->is64Bit() &&
2992         ((!isa<GlobalAddressSDNode>(Callee) &&
2993           !isa<ExternalSymbolSDNode>(Callee)) ||
2994          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
2995       unsigned NumInRegs = 0;
2996       // In PIC we need an extra register to formulate the address computation
2997       // for the callee.
2998       unsigned MaxInRegs =
2999           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3000
3001       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3002         CCValAssign &VA = ArgLocs[i];
3003         if (!VA.isRegLoc())
3004           continue;
3005         unsigned Reg = VA.getLocReg();
3006         switch (Reg) {
3007         default: break;
3008         case X86::EAX: case X86::EDX: case X86::ECX:
3009           if (++NumInRegs == MaxInRegs)
3010             return false;
3011           break;
3012         }
3013       }
3014     }
3015   }
3016
3017   return true;
3018 }
3019
3020 FastISel *
3021 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3022                                   const TargetLibraryInfo *libInfo) const {
3023   return X86::createFastISel(funcInfo, libInfo);
3024 }
3025
3026 //===----------------------------------------------------------------------===//
3027 //                           Other Lowering Hooks
3028 //===----------------------------------------------------------------------===//
3029
3030 static bool MayFoldLoad(SDValue Op) {
3031   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3032 }
3033
3034 static bool MayFoldIntoStore(SDValue Op) {
3035   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3036 }
3037
3038 static bool isTargetShuffle(unsigned Opcode) {
3039   switch(Opcode) {
3040   default: return false;
3041   case X86ISD::PSHUFD:
3042   case X86ISD::PSHUFHW:
3043   case X86ISD::PSHUFLW:
3044   case X86ISD::SHUFP:
3045   case X86ISD::PALIGNR:
3046   case X86ISD::MOVLHPS:
3047   case X86ISD::MOVLHPD:
3048   case X86ISD::MOVHLPS:
3049   case X86ISD::MOVLPS:
3050   case X86ISD::MOVLPD:
3051   case X86ISD::MOVSHDUP:
3052   case X86ISD::MOVSLDUP:
3053   case X86ISD::MOVDDUP:
3054   case X86ISD::MOVSS:
3055   case X86ISD::MOVSD:
3056   case X86ISD::UNPCKL:
3057   case X86ISD::UNPCKH:
3058   case X86ISD::VPERMILP:
3059   case X86ISD::VPERM2X128:
3060   case X86ISD::VPERMI:
3061     return true;
3062   }
3063 }
3064
3065 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3066                                     SDValue V1, SelectionDAG &DAG) {
3067   switch(Opc) {
3068   default: llvm_unreachable("Unknown x86 shuffle node");
3069   case X86ISD::MOVSHDUP:
3070   case X86ISD::MOVSLDUP:
3071   case X86ISD::MOVDDUP:
3072     return DAG.getNode(Opc, dl, VT, V1);
3073   }
3074 }
3075
3076 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3077                                     SDValue V1, unsigned TargetMask,
3078                                     SelectionDAG &DAG) {
3079   switch(Opc) {
3080   default: llvm_unreachable("Unknown x86 shuffle node");
3081   case X86ISD::PSHUFD:
3082   case X86ISD::PSHUFHW:
3083   case X86ISD::PSHUFLW:
3084   case X86ISD::VPERMILP:
3085   case X86ISD::VPERMI:
3086     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3087   }
3088 }
3089
3090 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3091                                     SDValue V1, SDValue V2, unsigned TargetMask,
3092                                     SelectionDAG &DAG) {
3093   switch(Opc) {
3094   default: llvm_unreachable("Unknown x86 shuffle node");
3095   case X86ISD::PALIGNR:
3096   case X86ISD::SHUFP:
3097   case X86ISD::VPERM2X128:
3098     return DAG.getNode(Opc, dl, VT, V1, V2,
3099                        DAG.getConstant(TargetMask, MVT::i8));
3100   }
3101 }
3102
3103 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3104                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3105   switch(Opc) {
3106   default: llvm_unreachable("Unknown x86 shuffle node");
3107   case X86ISD::MOVLHPS:
3108   case X86ISD::MOVLHPD:
3109   case X86ISD::MOVHLPS:
3110   case X86ISD::MOVLPS:
3111   case X86ISD::MOVLPD:
3112   case X86ISD::MOVSS:
3113   case X86ISD::MOVSD:
3114   case X86ISD::UNPCKL:
3115   case X86ISD::UNPCKH:
3116     return DAG.getNode(Opc, dl, VT, V1, V2);
3117   }
3118 }
3119
3120 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3121   MachineFunction &MF = DAG.getMachineFunction();
3122   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3123   int ReturnAddrIndex = FuncInfo->getRAIndex();
3124
3125   if (ReturnAddrIndex == 0) {
3126     // Set up a frame object for the return address.
3127     unsigned SlotSize = RegInfo->getSlotSize();
3128     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3129                                                            false);
3130     FuncInfo->setRAIndex(ReturnAddrIndex);
3131   }
3132
3133   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3134 }
3135
3136 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3137                                        bool hasSymbolicDisplacement) {
3138   // Offset should fit into 32 bit immediate field.
3139   if (!isInt<32>(Offset))
3140     return false;
3141
3142   // If we don't have a symbolic displacement - we don't have any extra
3143   // restrictions.
3144   if (!hasSymbolicDisplacement)
3145     return true;
3146
3147   // FIXME: Some tweaks might be needed for medium code model.
3148   if (M != CodeModel::Small && M != CodeModel::Kernel)
3149     return false;
3150
3151   // For small code model we assume that latest object is 16MB before end of 31
3152   // bits boundary. We may also accept pretty large negative constants knowing
3153   // that all objects are in the positive half of address space.
3154   if (M == CodeModel::Small && Offset < 16*1024*1024)
3155     return true;
3156
3157   // For kernel code model we know that all object resist in the negative half
3158   // of 32bits address space. We may not accept negative offsets, since they may
3159   // be just off and we may accept pretty large positive ones.
3160   if (M == CodeModel::Kernel && Offset > 0)
3161     return true;
3162
3163   return false;
3164 }
3165
3166 /// isCalleePop - Determines whether the callee is required to pop its
3167 /// own arguments. Callee pop is necessary to support tail calls.
3168 bool X86::isCalleePop(CallingConv::ID CallingConv,
3169                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3170   if (IsVarArg)
3171     return false;
3172
3173   switch (CallingConv) {
3174   default:
3175     return false;
3176   case CallingConv::X86_StdCall:
3177     return !is64Bit;
3178   case CallingConv::X86_FastCall:
3179     return !is64Bit;
3180   case CallingConv::X86_ThisCall:
3181     return !is64Bit;
3182   case CallingConv::Fast:
3183     return TailCallOpt;
3184   case CallingConv::GHC:
3185     return TailCallOpt;
3186   case CallingConv::HiPE:
3187     return TailCallOpt;
3188   }
3189 }
3190
3191 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3192 /// specific condition code, returning the condition code and the LHS/RHS of the
3193 /// comparison to make.
3194 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3195                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3196   if (!isFP) {
3197     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3198       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3199         // X > -1   -> X == 0, jump !sign.
3200         RHS = DAG.getConstant(0, RHS.getValueType());
3201         return X86::COND_NS;
3202       }
3203       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3204         // X < 0   -> X == 0, jump on sign.
3205         return X86::COND_S;
3206       }
3207       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3208         // X < 1   -> X <= 0
3209         RHS = DAG.getConstant(0, RHS.getValueType());
3210         return X86::COND_LE;
3211       }
3212     }
3213
3214     switch (SetCCOpcode) {
3215     default: llvm_unreachable("Invalid integer condition!");
3216     case ISD::SETEQ:  return X86::COND_E;
3217     case ISD::SETGT:  return X86::COND_G;
3218     case ISD::SETGE:  return X86::COND_GE;
3219     case ISD::SETLT:  return X86::COND_L;
3220     case ISD::SETLE:  return X86::COND_LE;
3221     case ISD::SETNE:  return X86::COND_NE;
3222     case ISD::SETULT: return X86::COND_B;
3223     case ISD::SETUGT: return X86::COND_A;
3224     case ISD::SETULE: return X86::COND_BE;
3225     case ISD::SETUGE: return X86::COND_AE;
3226     }
3227   }
3228
3229   // First determine if it is required or is profitable to flip the operands.
3230
3231   // If LHS is a foldable load, but RHS is not, flip the condition.
3232   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3233       !ISD::isNON_EXTLoad(RHS.getNode())) {
3234     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3235     std::swap(LHS, RHS);
3236   }
3237
3238   switch (SetCCOpcode) {
3239   default: break;
3240   case ISD::SETOLT:
3241   case ISD::SETOLE:
3242   case ISD::SETUGT:
3243   case ISD::SETUGE:
3244     std::swap(LHS, RHS);
3245     break;
3246   }
3247
3248   // On a floating point condition, the flags are set as follows:
3249   // ZF  PF  CF   op
3250   //  0 | 0 | 0 | X > Y
3251   //  0 | 0 | 1 | X < Y
3252   //  1 | 0 | 0 | X == Y
3253   //  1 | 1 | 1 | unordered
3254   switch (SetCCOpcode) {
3255   default: llvm_unreachable("Condcode should be pre-legalized away");
3256   case ISD::SETUEQ:
3257   case ISD::SETEQ:   return X86::COND_E;
3258   case ISD::SETOLT:              // flipped
3259   case ISD::SETOGT:
3260   case ISD::SETGT:   return X86::COND_A;
3261   case ISD::SETOLE:              // flipped
3262   case ISD::SETOGE:
3263   case ISD::SETGE:   return X86::COND_AE;
3264   case ISD::SETUGT:              // flipped
3265   case ISD::SETULT:
3266   case ISD::SETLT:   return X86::COND_B;
3267   case ISD::SETUGE:              // flipped
3268   case ISD::SETULE:
3269   case ISD::SETLE:   return X86::COND_BE;
3270   case ISD::SETONE:
3271   case ISD::SETNE:   return X86::COND_NE;
3272   case ISD::SETUO:   return X86::COND_P;
3273   case ISD::SETO:    return X86::COND_NP;
3274   case ISD::SETOEQ:
3275   case ISD::SETUNE:  return X86::COND_INVALID;
3276   }
3277 }
3278
3279 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3280 /// code. Current x86 isa includes the following FP cmov instructions:
3281 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3282 static bool hasFPCMov(unsigned X86CC) {
3283   switch (X86CC) {
3284   default:
3285     return false;
3286   case X86::COND_B:
3287   case X86::COND_BE:
3288   case X86::COND_E:
3289   case X86::COND_P:
3290   case X86::COND_A:
3291   case X86::COND_AE:
3292   case X86::COND_NE:
3293   case X86::COND_NP:
3294     return true;
3295   }
3296 }
3297
3298 /// isFPImmLegal - Returns true if the target can instruction select the
3299 /// specified FP immediate natively. If false, the legalizer will
3300 /// materialize the FP immediate as a load from a constant pool.
3301 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3302   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3303     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3304       return true;
3305   }
3306   return false;
3307 }
3308
3309 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3310 /// the specified range (L, H].
3311 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3312   return (Val < 0) || (Val >= Low && Val < Hi);
3313 }
3314
3315 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3316 /// specified value.
3317 static bool isUndefOrEqual(int Val, int CmpVal) {
3318   return (Val < 0 || Val == CmpVal);
3319 }
3320
3321 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3322 /// from position Pos and ending in Pos+Size, falls within the specified
3323 /// sequential range (L, L+Pos]. or is undef.
3324 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3325                                        unsigned Pos, unsigned Size, int Low) {
3326   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3327     if (!isUndefOrEqual(Mask[i], Low))
3328       return false;
3329   return true;
3330 }
3331
3332 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3333 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3334 /// the second operand.
3335 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3336   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3337     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3338   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3339     return (Mask[0] < 2 && Mask[1] < 2);
3340   return false;
3341 }
3342
3343 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3344 /// is suitable for input to PSHUFHW.
3345 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3346   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3347     return false;
3348
3349   // Lower quadword copied in order or undef.
3350   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3351     return false;
3352
3353   // Upper quadword shuffled.
3354   for (unsigned i = 4; i != 8; ++i)
3355     if (!isUndefOrInRange(Mask[i], 4, 8))
3356       return false;
3357
3358   if (VT == MVT::v16i16) {
3359     // Lower quadword copied in order or undef.
3360     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3361       return false;
3362
3363     // Upper quadword shuffled.
3364     for (unsigned i = 12; i != 16; ++i)
3365       if (!isUndefOrInRange(Mask[i], 12, 16))
3366         return false;
3367   }
3368
3369   return true;
3370 }
3371
3372 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3373 /// is suitable for input to PSHUFLW.
3374 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3375   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3376     return false;
3377
3378   // Upper quadword copied in order.
3379   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3380     return false;
3381
3382   // Lower quadword shuffled.
3383   for (unsigned i = 0; i != 4; ++i)
3384     if (!isUndefOrInRange(Mask[i], 0, 4))
3385       return false;
3386
3387   if (VT == MVT::v16i16) {
3388     // Upper quadword copied in order.
3389     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3390       return false;
3391
3392     // Lower quadword shuffled.
3393     for (unsigned i = 8; i != 12; ++i)
3394       if (!isUndefOrInRange(Mask[i], 8, 12))
3395         return false;
3396   }
3397
3398   return true;
3399 }
3400
3401 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3402 /// is suitable for input to PALIGNR.
3403 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3404                           const X86Subtarget *Subtarget) {
3405   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3406       (VT.is256BitVector() && !Subtarget->hasInt256()))
3407     return false;
3408
3409   unsigned NumElts = VT.getVectorNumElements();
3410   unsigned NumLanes = VT.getSizeInBits()/128;
3411   unsigned NumLaneElts = NumElts/NumLanes;
3412
3413   // Do not handle 64-bit element shuffles with palignr.
3414   if (NumLaneElts == 2)
3415     return false;
3416
3417   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3418     unsigned i;
3419     for (i = 0; i != NumLaneElts; ++i) {
3420       if (Mask[i+l] >= 0)
3421         break;
3422     }
3423
3424     // Lane is all undef, go to next lane
3425     if (i == NumLaneElts)
3426       continue;
3427
3428     int Start = Mask[i+l];
3429
3430     // Make sure its in this lane in one of the sources
3431     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3432         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3433       return false;
3434
3435     // If not lane 0, then we must match lane 0
3436     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3437       return false;
3438
3439     // Correct second source to be contiguous with first source
3440     if (Start >= (int)NumElts)
3441       Start -= NumElts - NumLaneElts;
3442
3443     // Make sure we're shifting in the right direction.
3444     if (Start <= (int)(i+l))
3445       return false;
3446
3447     Start -= i;
3448
3449     // Check the rest of the elements to see if they are consecutive.
3450     for (++i; i != NumLaneElts; ++i) {
3451       int Idx = Mask[i+l];
3452
3453       // Make sure its in this lane
3454       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3455           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3456         return false;
3457
3458       // If not lane 0, then we must match lane 0
3459       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3460         return false;
3461
3462       if (Idx >= (int)NumElts)
3463         Idx -= NumElts - NumLaneElts;
3464
3465       if (!isUndefOrEqual(Idx, Start+i))
3466         return false;
3467
3468     }
3469   }
3470
3471   return true;
3472 }
3473
3474 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3475 /// the two vector operands have swapped position.
3476 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3477                                      unsigned NumElems) {
3478   for (unsigned i = 0; i != NumElems; ++i) {
3479     int idx = Mask[i];
3480     if (idx < 0)
3481       continue;
3482     else if (idx < (int)NumElems)
3483       Mask[i] = idx + NumElems;
3484     else
3485       Mask[i] = idx - NumElems;
3486   }
3487 }
3488
3489 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3490 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3491 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3492 /// reverse of what x86 shuffles want.
3493 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3494                         bool Commuted = false) {
3495   if (!HasFp256 && VT.is256BitVector())
3496     return false;
3497
3498   unsigned NumElems = VT.getVectorNumElements();
3499   unsigned NumLanes = VT.getSizeInBits()/128;
3500   unsigned NumLaneElems = NumElems/NumLanes;
3501
3502   if (NumLaneElems != 2 && NumLaneElems != 4)
3503     return false;
3504
3505   // VSHUFPSY divides the resulting vector into 4 chunks.
3506   // The sources are also splitted into 4 chunks, and each destination
3507   // chunk must come from a different source chunk.
3508   //
3509   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3510   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3511   //
3512   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3513   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3514   //
3515   // VSHUFPDY divides the resulting vector into 4 chunks.
3516   // The sources are also splitted into 4 chunks, and each destination
3517   // chunk must come from a different source chunk.
3518   //
3519   //  SRC1 =>      X3       X2       X1       X0
3520   //  SRC2 =>      Y3       Y2       Y1       Y0
3521   //
3522   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3523   //
3524   unsigned HalfLaneElems = NumLaneElems/2;
3525   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3526     for (unsigned i = 0; i != NumLaneElems; ++i) {
3527       int Idx = Mask[i+l];
3528       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3529       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3530         return false;
3531       // For VSHUFPSY, the mask of the second half must be the same as the
3532       // first but with the appropriate offsets. This works in the same way as
3533       // VPERMILPS works with masks.
3534       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3535         continue;
3536       if (!isUndefOrEqual(Idx, Mask[i]+l))
3537         return false;
3538     }
3539   }
3540
3541   return true;
3542 }
3543
3544 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3545 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3546 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3547   if (!VT.is128BitVector())
3548     return false;
3549
3550   unsigned NumElems = VT.getVectorNumElements();
3551
3552   if (NumElems != 4)
3553     return false;
3554
3555   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3556   return isUndefOrEqual(Mask[0], 6) &&
3557          isUndefOrEqual(Mask[1], 7) &&
3558          isUndefOrEqual(Mask[2], 2) &&
3559          isUndefOrEqual(Mask[3], 3);
3560 }
3561
3562 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3563 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3564 /// <2, 3, 2, 3>
3565 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3566   if (!VT.is128BitVector())
3567     return false;
3568
3569   unsigned NumElems = VT.getVectorNumElements();
3570
3571   if (NumElems != 4)
3572     return false;
3573
3574   return isUndefOrEqual(Mask[0], 2) &&
3575          isUndefOrEqual(Mask[1], 3) &&
3576          isUndefOrEqual(Mask[2], 2) &&
3577          isUndefOrEqual(Mask[3], 3);
3578 }
3579
3580 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3581 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3582 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3583   if (!VT.is128BitVector())
3584     return false;
3585
3586   unsigned NumElems = VT.getVectorNumElements();
3587
3588   if (NumElems != 2 && NumElems != 4)
3589     return false;
3590
3591   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3592     if (!isUndefOrEqual(Mask[i], i + NumElems))
3593       return false;
3594
3595   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3596     if (!isUndefOrEqual(Mask[i], i))
3597       return false;
3598
3599   return true;
3600 }
3601
3602 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3603 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3604 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3605   if (!VT.is128BitVector())
3606     return false;
3607
3608   unsigned NumElems = VT.getVectorNumElements();
3609
3610   if (NumElems != 2 && NumElems != 4)
3611     return false;
3612
3613   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3614     if (!isUndefOrEqual(Mask[i], i))
3615       return false;
3616
3617   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3618     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3619       return false;
3620
3621   return true;
3622 }
3623
3624 //
3625 // Some special combinations that can be optimized.
3626 //
3627 static
3628 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3629                                SelectionDAG &DAG) {
3630   MVT VT = SVOp->getValueType(0).getSimpleVT();
3631   DebugLoc dl = SVOp->getDebugLoc();
3632
3633   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3634     return SDValue();
3635
3636   ArrayRef<int> Mask = SVOp->getMask();
3637
3638   // These are the special masks that may be optimized.
3639   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3640   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3641   bool MatchEvenMask = true;
3642   bool MatchOddMask  = true;
3643   for (int i=0; i<8; ++i) {
3644     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3645       MatchEvenMask = false;
3646     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3647       MatchOddMask = false;
3648   }
3649
3650   if (!MatchEvenMask && !MatchOddMask)
3651     return SDValue();
3652
3653   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3654
3655   SDValue Op0 = SVOp->getOperand(0);
3656   SDValue Op1 = SVOp->getOperand(1);
3657
3658   if (MatchEvenMask) {
3659     // Shift the second operand right to 32 bits.
3660     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3661     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3662   } else {
3663     // Shift the first operand left to 32 bits.
3664     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3665     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3666   }
3667   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3668   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3669 }
3670
3671 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3672 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3673 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3674                          bool HasInt256, bool V2IsSplat = false) {
3675   unsigned NumElts = VT.getVectorNumElements();
3676
3677   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3678          "Unsupported vector type for unpckh");
3679
3680   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3681       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3682     return false;
3683
3684   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3685   // independently on 128-bit lanes.
3686   unsigned NumLanes = VT.getSizeInBits()/128;
3687   unsigned NumLaneElts = NumElts/NumLanes;
3688
3689   for (unsigned l = 0; l != NumLanes; ++l) {
3690     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3691          i != (l+1)*NumLaneElts;
3692          i += 2, ++j) {
3693       int BitI  = Mask[i];
3694       int BitI1 = Mask[i+1];
3695       if (!isUndefOrEqual(BitI, j))
3696         return false;
3697       if (V2IsSplat) {
3698         if (!isUndefOrEqual(BitI1, NumElts))
3699           return false;
3700       } else {
3701         if (!isUndefOrEqual(BitI1, j + NumElts))
3702           return false;
3703       }
3704     }
3705   }
3706
3707   return true;
3708 }
3709
3710 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3711 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3712 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3713                          bool HasInt256, bool V2IsSplat = false) {
3714   unsigned NumElts = VT.getVectorNumElements();
3715
3716   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3717          "Unsupported vector type for unpckh");
3718
3719   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3720       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3721     return false;
3722
3723   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3724   // independently on 128-bit lanes.
3725   unsigned NumLanes = VT.getSizeInBits()/128;
3726   unsigned NumLaneElts = NumElts/NumLanes;
3727
3728   for (unsigned l = 0; l != NumLanes; ++l) {
3729     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3730          i != (l+1)*NumLaneElts; i += 2, ++j) {
3731       int BitI  = Mask[i];
3732       int BitI1 = Mask[i+1];
3733       if (!isUndefOrEqual(BitI, j))
3734         return false;
3735       if (V2IsSplat) {
3736         if (isUndefOrEqual(BitI1, NumElts))
3737           return false;
3738       } else {
3739         if (!isUndefOrEqual(BitI1, j+NumElts))
3740           return false;
3741       }
3742     }
3743   }
3744   return true;
3745 }
3746
3747 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3748 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3749 /// <0, 0, 1, 1>
3750 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3751   unsigned NumElts = VT.getVectorNumElements();
3752   bool Is256BitVec = VT.is256BitVector();
3753
3754   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3755          "Unsupported vector type for unpckh");
3756
3757   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3758       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3759     return false;
3760
3761   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3762   // FIXME: Need a better way to get rid of this, there's no latency difference
3763   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3764   // the former later. We should also remove the "_undef" special mask.
3765   if (NumElts == 4 && Is256BitVec)
3766     return false;
3767
3768   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3769   // independently on 128-bit lanes.
3770   unsigned NumLanes = VT.getSizeInBits()/128;
3771   unsigned NumLaneElts = NumElts/NumLanes;
3772
3773   for (unsigned l = 0; l != NumLanes; ++l) {
3774     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3775          i != (l+1)*NumLaneElts;
3776          i += 2, ++j) {
3777       int BitI  = Mask[i];
3778       int BitI1 = Mask[i+1];
3779
3780       if (!isUndefOrEqual(BitI, j))
3781         return false;
3782       if (!isUndefOrEqual(BitI1, j))
3783         return false;
3784     }
3785   }
3786
3787   return true;
3788 }
3789
3790 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3791 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3792 /// <2, 2, 3, 3>
3793 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3794   unsigned NumElts = VT.getVectorNumElements();
3795
3796   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3797          "Unsupported vector type for unpckh");
3798
3799   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3800       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3801     return false;
3802
3803   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3804   // independently on 128-bit lanes.
3805   unsigned NumLanes = VT.getSizeInBits()/128;
3806   unsigned NumLaneElts = NumElts/NumLanes;
3807
3808   for (unsigned l = 0; l != NumLanes; ++l) {
3809     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3810          i != (l+1)*NumLaneElts; i += 2, ++j) {
3811       int BitI  = Mask[i];
3812       int BitI1 = Mask[i+1];
3813       if (!isUndefOrEqual(BitI, j))
3814         return false;
3815       if (!isUndefOrEqual(BitI1, j))
3816         return false;
3817     }
3818   }
3819   return true;
3820 }
3821
3822 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3823 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3824 /// MOVSD, and MOVD, i.e. setting the lowest element.
3825 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3826   if (VT.getVectorElementType().getSizeInBits() < 32)
3827     return false;
3828   if (!VT.is128BitVector())
3829     return false;
3830
3831   unsigned NumElts = VT.getVectorNumElements();
3832
3833   if (!isUndefOrEqual(Mask[0], NumElts))
3834     return false;
3835
3836   for (unsigned i = 1; i != NumElts; ++i)
3837     if (!isUndefOrEqual(Mask[i], i))
3838       return false;
3839
3840   return true;
3841 }
3842
3843 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3844 /// as permutations between 128-bit chunks or halves. As an example: this
3845 /// shuffle bellow:
3846 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3847 /// The first half comes from the second half of V1 and the second half from the
3848 /// the second half of V2.
3849 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3850   if (!HasFp256 || !VT.is256BitVector())
3851     return false;
3852
3853   // The shuffle result is divided into half A and half B. In total the two
3854   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3855   // B must come from C, D, E or F.
3856   unsigned HalfSize = VT.getVectorNumElements()/2;
3857   bool MatchA = false, MatchB = false;
3858
3859   // Check if A comes from one of C, D, E, F.
3860   for (unsigned Half = 0; Half != 4; ++Half) {
3861     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3862       MatchA = true;
3863       break;
3864     }
3865   }
3866
3867   // Check if B comes from one of C, D, E, F.
3868   for (unsigned Half = 0; Half != 4; ++Half) {
3869     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3870       MatchB = true;
3871       break;
3872     }
3873   }
3874
3875   return MatchA && MatchB;
3876 }
3877
3878 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3879 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3880 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3881   MVT VT = SVOp->getValueType(0).getSimpleVT();
3882
3883   unsigned HalfSize = VT.getVectorNumElements()/2;
3884
3885   unsigned FstHalf = 0, SndHalf = 0;
3886   for (unsigned i = 0; i < HalfSize; ++i) {
3887     if (SVOp->getMaskElt(i) > 0) {
3888       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3889       break;
3890     }
3891   }
3892   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3893     if (SVOp->getMaskElt(i) > 0) {
3894       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3895       break;
3896     }
3897   }
3898
3899   return (FstHalf | (SndHalf << 4));
3900 }
3901
3902 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3903 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3904 /// Note that VPERMIL mask matching is different depending whether theunderlying
3905 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3906 /// to the same elements of the low, but to the higher half of the source.
3907 /// In VPERMILPD the two lanes could be shuffled independently of each other
3908 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3909 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3910   if (!HasFp256)
3911     return false;
3912
3913   unsigned NumElts = VT.getVectorNumElements();
3914   // Only match 256-bit with 32/64-bit types
3915   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3916     return false;
3917
3918   unsigned NumLanes = VT.getSizeInBits()/128;
3919   unsigned LaneSize = NumElts/NumLanes;
3920   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3921     for (unsigned i = 0; i != LaneSize; ++i) {
3922       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3923         return false;
3924       if (NumElts != 8 || l == 0)
3925         continue;
3926       // VPERMILPS handling
3927       if (Mask[i] < 0)
3928         continue;
3929       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3930         return false;
3931     }
3932   }
3933
3934   return true;
3935 }
3936
3937 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3938 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3939 /// element of vector 2 and the other elements to come from vector 1 in order.
3940 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3941                                bool V2IsSplat = false, bool V2IsUndef = false) {
3942   if (!VT.is128BitVector())
3943     return false;
3944
3945   unsigned NumOps = VT.getVectorNumElements();
3946   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3947     return false;
3948
3949   if (!isUndefOrEqual(Mask[0], 0))
3950     return false;
3951
3952   for (unsigned i = 1; i != NumOps; ++i)
3953     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3954           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3955           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3956       return false;
3957
3958   return true;
3959 }
3960
3961 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3962 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3963 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3964 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3965                            const X86Subtarget *Subtarget) {
3966   if (!Subtarget->hasSSE3())
3967     return false;
3968
3969   unsigned NumElems = VT.getVectorNumElements();
3970
3971   if ((VT.is128BitVector() && NumElems != 4) ||
3972       (VT.is256BitVector() && NumElems != 8))
3973     return false;
3974
3975   // "i+1" is the value the indexed mask element must have
3976   for (unsigned i = 0; i != NumElems; i += 2)
3977     if (!isUndefOrEqual(Mask[i], i+1) ||
3978         !isUndefOrEqual(Mask[i+1], i+1))
3979       return false;
3980
3981   return true;
3982 }
3983
3984 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3985 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3986 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3987 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3988                            const X86Subtarget *Subtarget) {
3989   if (!Subtarget->hasSSE3())
3990     return false;
3991
3992   unsigned NumElems = VT.getVectorNumElements();
3993
3994   if ((VT.is128BitVector() && NumElems != 4) ||
3995       (VT.is256BitVector() && NumElems != 8))
3996     return false;
3997
3998   // "i" is the value the indexed mask element must have
3999   for (unsigned i = 0; i != NumElems; i += 2)
4000     if (!isUndefOrEqual(Mask[i], i) ||
4001         !isUndefOrEqual(Mask[i+1], i))
4002       return false;
4003
4004   return true;
4005 }
4006
4007 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4008 /// specifies a shuffle of elements that is suitable for input to 256-bit
4009 /// version of MOVDDUP.
4010 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4011   if (!HasFp256 || !VT.is256BitVector())
4012     return false;
4013
4014   unsigned NumElts = VT.getVectorNumElements();
4015   if (NumElts != 4)
4016     return false;
4017
4018   for (unsigned i = 0; i != NumElts/2; ++i)
4019     if (!isUndefOrEqual(Mask[i], 0))
4020       return false;
4021   for (unsigned i = NumElts/2; i != NumElts; ++i)
4022     if (!isUndefOrEqual(Mask[i], NumElts/2))
4023       return false;
4024   return true;
4025 }
4026
4027 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4028 /// specifies a shuffle of elements that is suitable for input to 128-bit
4029 /// version of MOVDDUP.
4030 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4031   if (!VT.is128BitVector())
4032     return false;
4033
4034   unsigned e = VT.getVectorNumElements() / 2;
4035   for (unsigned i = 0; i != e; ++i)
4036     if (!isUndefOrEqual(Mask[i], i))
4037       return false;
4038   for (unsigned i = 0; i != e; ++i)
4039     if (!isUndefOrEqual(Mask[e+i], i))
4040       return false;
4041   return true;
4042 }
4043
4044 /// isVEXTRACTF128Index - Return true if the specified
4045 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4046 /// suitable for input to VEXTRACTF128.
4047 bool X86::isVEXTRACTF128Index(SDNode *N) {
4048   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4049     return false;
4050
4051   // The index should be aligned on a 128-bit boundary.
4052   uint64_t Index =
4053     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4054
4055   MVT VT = N->getValueType(0).getSimpleVT();
4056   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4057   bool Result = (Index * ElSize) % 128 == 0;
4058
4059   return Result;
4060 }
4061
4062 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4063 /// operand specifies a subvector insert that is suitable for input to
4064 /// VINSERTF128.
4065 bool X86::isVINSERTF128Index(SDNode *N) {
4066   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4067     return false;
4068
4069   // The index should be aligned on a 128-bit boundary.
4070   uint64_t Index =
4071     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4072
4073   MVT VT = N->getValueType(0).getSimpleVT();
4074   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4075   bool Result = (Index * ElSize) % 128 == 0;
4076
4077   return Result;
4078 }
4079
4080 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4081 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4082 /// Handles 128-bit and 256-bit.
4083 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4084   MVT VT = N->getValueType(0).getSimpleVT();
4085
4086   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4087          "Unsupported vector type for PSHUF/SHUFP");
4088
4089   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4090   // independently on 128-bit lanes.
4091   unsigned NumElts = VT.getVectorNumElements();
4092   unsigned NumLanes = VT.getSizeInBits()/128;
4093   unsigned NumLaneElts = NumElts/NumLanes;
4094
4095   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4096          "Only supports 2 or 4 elements per lane");
4097
4098   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4099   unsigned Mask = 0;
4100   for (unsigned i = 0; i != NumElts; ++i) {
4101     int Elt = N->getMaskElt(i);
4102     if (Elt < 0) continue;
4103     Elt &= NumLaneElts - 1;
4104     unsigned ShAmt = (i << Shift) % 8;
4105     Mask |= Elt << ShAmt;
4106   }
4107
4108   return Mask;
4109 }
4110
4111 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4112 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4113 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4114   MVT VT = N->getValueType(0).getSimpleVT();
4115
4116   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4117          "Unsupported vector type for PSHUFHW");
4118
4119   unsigned NumElts = VT.getVectorNumElements();
4120
4121   unsigned Mask = 0;
4122   for (unsigned l = 0; l != NumElts; l += 8) {
4123     // 8 nodes per lane, but we only care about the last 4.
4124     for (unsigned i = 0; i < 4; ++i) {
4125       int Elt = N->getMaskElt(l+i+4);
4126       if (Elt < 0) continue;
4127       Elt &= 0x3; // only 2-bits.
4128       Mask |= Elt << (i * 2);
4129     }
4130   }
4131
4132   return Mask;
4133 }
4134
4135 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4136 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4137 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4138   MVT VT = N->getValueType(0).getSimpleVT();
4139
4140   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4141          "Unsupported vector type for PSHUFHW");
4142
4143   unsigned NumElts = VT.getVectorNumElements();
4144
4145   unsigned Mask = 0;
4146   for (unsigned l = 0; l != NumElts; l += 8) {
4147     // 8 nodes per lane, but we only care about the first 4.
4148     for (unsigned i = 0; i < 4; ++i) {
4149       int Elt = N->getMaskElt(l+i);
4150       if (Elt < 0) continue;
4151       Elt &= 0x3; // only 2-bits
4152       Mask |= Elt << (i * 2);
4153     }
4154   }
4155
4156   return Mask;
4157 }
4158
4159 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4160 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4161 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4162   MVT VT = SVOp->getValueType(0).getSimpleVT();
4163   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4164
4165   unsigned NumElts = VT.getVectorNumElements();
4166   unsigned NumLanes = VT.getSizeInBits()/128;
4167   unsigned NumLaneElts = NumElts/NumLanes;
4168
4169   int Val = 0;
4170   unsigned i;
4171   for (i = 0; i != NumElts; ++i) {
4172     Val = SVOp->getMaskElt(i);
4173     if (Val >= 0)
4174       break;
4175   }
4176   if (Val >= (int)NumElts)
4177     Val -= NumElts - NumLaneElts;
4178
4179   assert(Val - i > 0 && "PALIGNR imm should be positive");
4180   return (Val - i) * EltSize;
4181 }
4182
4183 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4184 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4185 /// instructions.
4186 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4187   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4188     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4189
4190   uint64_t Index =
4191     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4192
4193   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4194   MVT ElVT = VecVT.getVectorElementType();
4195
4196   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4197   return Index / NumElemsPerChunk;
4198 }
4199
4200 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4201 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4202 /// instructions.
4203 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4204   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4205     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4206
4207   uint64_t Index =
4208     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4209
4210   MVT VecVT = N->getValueType(0).getSimpleVT();
4211   MVT ElVT = VecVT.getVectorElementType();
4212
4213   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4214   return Index / NumElemsPerChunk;
4215 }
4216
4217 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4218 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4219 /// Handles 256-bit.
4220 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4221   MVT VT = N->getValueType(0).getSimpleVT();
4222
4223   unsigned NumElts = VT.getVectorNumElements();
4224
4225   assert((VT.is256BitVector() && NumElts == 4) &&
4226          "Unsupported vector type for VPERMQ/VPERMPD");
4227
4228   unsigned Mask = 0;
4229   for (unsigned i = 0; i != NumElts; ++i) {
4230     int Elt = N->getMaskElt(i);
4231     if (Elt < 0)
4232       continue;
4233     Mask |= Elt << (i*2);
4234   }
4235
4236   return Mask;
4237 }
4238 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4239 /// constant +0.0.
4240 bool X86::isZeroNode(SDValue Elt) {
4241   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4242     return CN->isNullValue();
4243   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4244     return CFP->getValueAPF().isPosZero();
4245   return false;
4246 }
4247
4248 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4249 /// their permute mask.
4250 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4251                                     SelectionDAG &DAG) {
4252   MVT VT = SVOp->getValueType(0).getSimpleVT();
4253   unsigned NumElems = VT.getVectorNumElements();
4254   SmallVector<int, 8> MaskVec;
4255
4256   for (unsigned i = 0; i != NumElems; ++i) {
4257     int Idx = SVOp->getMaskElt(i);
4258     if (Idx >= 0) {
4259       if (Idx < (int)NumElems)
4260         Idx += NumElems;
4261       else
4262         Idx -= NumElems;
4263     }
4264     MaskVec.push_back(Idx);
4265   }
4266   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4267                               SVOp->getOperand(0), &MaskVec[0]);
4268 }
4269
4270 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4271 /// match movhlps. The lower half elements should come from upper half of
4272 /// V1 (and in order), and the upper half elements should come from the upper
4273 /// half of V2 (and in order).
4274 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4275   if (!VT.is128BitVector())
4276     return false;
4277   if (VT.getVectorNumElements() != 4)
4278     return false;
4279   for (unsigned i = 0, e = 2; i != e; ++i)
4280     if (!isUndefOrEqual(Mask[i], i+2))
4281       return false;
4282   for (unsigned i = 2; i != 4; ++i)
4283     if (!isUndefOrEqual(Mask[i], i+4))
4284       return false;
4285   return true;
4286 }
4287
4288 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4289 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4290 /// required.
4291 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4292   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4293     return false;
4294   N = N->getOperand(0).getNode();
4295   if (!ISD::isNON_EXTLoad(N))
4296     return false;
4297   if (LD)
4298     *LD = cast<LoadSDNode>(N);
4299   return true;
4300 }
4301
4302 // Test whether the given value is a vector value which will be legalized
4303 // into a load.
4304 static bool WillBeConstantPoolLoad(SDNode *N) {
4305   if (N->getOpcode() != ISD::BUILD_VECTOR)
4306     return false;
4307
4308   // Check for any non-constant elements.
4309   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4310     switch (N->getOperand(i).getNode()->getOpcode()) {
4311     case ISD::UNDEF:
4312     case ISD::ConstantFP:
4313     case ISD::Constant:
4314       break;
4315     default:
4316       return false;
4317     }
4318
4319   // Vectors of all-zeros and all-ones are materialized with special
4320   // instructions rather than being loaded.
4321   return !ISD::isBuildVectorAllZeros(N) &&
4322          !ISD::isBuildVectorAllOnes(N);
4323 }
4324
4325 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4326 /// match movlp{s|d}. The lower half elements should come from lower half of
4327 /// V1 (and in order), and the upper half elements should come from the upper
4328 /// half of V2 (and in order). And since V1 will become the source of the
4329 /// MOVLP, it must be either a vector load or a scalar load to vector.
4330 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4331                                ArrayRef<int> Mask, EVT VT) {
4332   if (!VT.is128BitVector())
4333     return false;
4334
4335   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4336     return false;
4337   // Is V2 is a vector load, don't do this transformation. We will try to use
4338   // load folding shufps op.
4339   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4340     return false;
4341
4342   unsigned NumElems = VT.getVectorNumElements();
4343
4344   if (NumElems != 2 && NumElems != 4)
4345     return false;
4346   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4347     if (!isUndefOrEqual(Mask[i], i))
4348       return false;
4349   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4350     if (!isUndefOrEqual(Mask[i], i+NumElems))
4351       return false;
4352   return true;
4353 }
4354
4355 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4356 /// all the same.
4357 static bool isSplatVector(SDNode *N) {
4358   if (N->getOpcode() != ISD::BUILD_VECTOR)
4359     return false;
4360
4361   SDValue SplatValue = N->getOperand(0);
4362   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4363     if (N->getOperand(i) != SplatValue)
4364       return false;
4365   return true;
4366 }
4367
4368 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4369 /// to an zero vector.
4370 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4371 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4372   SDValue V1 = N->getOperand(0);
4373   SDValue V2 = N->getOperand(1);
4374   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4375   for (unsigned i = 0; i != NumElems; ++i) {
4376     int Idx = N->getMaskElt(i);
4377     if (Idx >= (int)NumElems) {
4378       unsigned Opc = V2.getOpcode();
4379       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4380         continue;
4381       if (Opc != ISD::BUILD_VECTOR ||
4382           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4383         return false;
4384     } else if (Idx >= 0) {
4385       unsigned Opc = V1.getOpcode();
4386       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4387         continue;
4388       if (Opc != ISD::BUILD_VECTOR ||
4389           !X86::isZeroNode(V1.getOperand(Idx)))
4390         return false;
4391     }
4392   }
4393   return true;
4394 }
4395
4396 /// getZeroVector - Returns a vector of specified type with all zero elements.
4397 ///
4398 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4399                              SelectionDAG &DAG, DebugLoc dl) {
4400   assert(VT.isVector() && "Expected a vector type");
4401
4402   // Always build SSE zero vectors as <4 x i32> bitcasted
4403   // to their dest type. This ensures they get CSE'd.
4404   SDValue Vec;
4405   if (VT.is128BitVector()) {  // SSE
4406     if (Subtarget->hasSSE2()) {  // SSE2
4407       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4408       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4409     } else { // SSE1
4410       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4411       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4412     }
4413   } else if (VT.is256BitVector()) { // AVX
4414     if (Subtarget->hasInt256()) { // AVX2
4415       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4416       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4417       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4418                         array_lengthof(Ops));
4419     } else {
4420       // 256-bit logic and arithmetic instructions in AVX are all
4421       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4422       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4423       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4424       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4425                         array_lengthof(Ops));
4426     }
4427   } else
4428     llvm_unreachable("Unexpected vector type");
4429
4430   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4431 }
4432
4433 /// getOnesVector - Returns a vector of specified type with all bits set.
4434 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4435 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4436 /// Then bitcast to their original type, ensuring they get CSE'd.
4437 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4438                              DebugLoc dl) {
4439   assert(VT.isVector() && "Expected a vector type");
4440
4441   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4442   SDValue Vec;
4443   if (VT.is256BitVector()) {
4444     if (HasInt256) { // AVX2
4445       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4446       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4447                         array_lengthof(Ops));
4448     } else { // AVX
4449       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4450       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4451     }
4452   } else if (VT.is128BitVector()) {
4453     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4454   } else
4455     llvm_unreachable("Unexpected vector type");
4456
4457   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4458 }
4459
4460 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4461 /// that point to V2 points to its first element.
4462 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4463   for (unsigned i = 0; i != NumElems; ++i) {
4464     if (Mask[i] > (int)NumElems) {
4465       Mask[i] = NumElems;
4466     }
4467   }
4468 }
4469
4470 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4471 /// operation of specified width.
4472 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4473                        SDValue V2) {
4474   unsigned NumElems = VT.getVectorNumElements();
4475   SmallVector<int, 8> Mask;
4476   Mask.push_back(NumElems);
4477   for (unsigned i = 1; i != NumElems; ++i)
4478     Mask.push_back(i);
4479   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4480 }
4481
4482 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4483 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4484                           SDValue V2) {
4485   unsigned NumElems = VT.getVectorNumElements();
4486   SmallVector<int, 8> Mask;
4487   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4488     Mask.push_back(i);
4489     Mask.push_back(i + NumElems);
4490   }
4491   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4492 }
4493
4494 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4495 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4496                           SDValue V2) {
4497   unsigned NumElems = VT.getVectorNumElements();
4498   SmallVector<int, 8> Mask;
4499   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4500     Mask.push_back(i + Half);
4501     Mask.push_back(i + NumElems + Half);
4502   }
4503   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4504 }
4505
4506 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4507 // a generic shuffle instruction because the target has no such instructions.
4508 // Generate shuffles which repeat i16 and i8 several times until they can be
4509 // represented by v4f32 and then be manipulated by target suported shuffles.
4510 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4511   EVT VT = V.getValueType();
4512   int NumElems = VT.getVectorNumElements();
4513   DebugLoc dl = V.getDebugLoc();
4514
4515   while (NumElems > 4) {
4516     if (EltNo < NumElems/2) {
4517       V = getUnpackl(DAG, dl, VT, V, V);
4518     } else {
4519       V = getUnpackh(DAG, dl, VT, V, V);
4520       EltNo -= NumElems/2;
4521     }
4522     NumElems >>= 1;
4523   }
4524   return V;
4525 }
4526
4527 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4528 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4529   EVT VT = V.getValueType();
4530   DebugLoc dl = V.getDebugLoc();
4531
4532   if (VT.is128BitVector()) {
4533     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4534     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4535     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4536                              &SplatMask[0]);
4537   } else if (VT.is256BitVector()) {
4538     // To use VPERMILPS to splat scalars, the second half of indicies must
4539     // refer to the higher part, which is a duplication of the lower one,
4540     // because VPERMILPS can only handle in-lane permutations.
4541     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4542                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4543
4544     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4545     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4546                              &SplatMask[0]);
4547   } else
4548     llvm_unreachable("Vector size not supported");
4549
4550   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4551 }
4552
4553 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4554 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4555   EVT SrcVT = SV->getValueType(0);
4556   SDValue V1 = SV->getOperand(0);
4557   DebugLoc dl = SV->getDebugLoc();
4558
4559   int EltNo = SV->getSplatIndex();
4560   int NumElems = SrcVT.getVectorNumElements();
4561   bool Is256BitVec = SrcVT.is256BitVector();
4562
4563   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4564          "Unknown how to promote splat for type");
4565
4566   // Extract the 128-bit part containing the splat element and update
4567   // the splat element index when it refers to the higher register.
4568   if (Is256BitVec) {
4569     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4570     if (EltNo >= NumElems/2)
4571       EltNo -= NumElems/2;
4572   }
4573
4574   // All i16 and i8 vector types can't be used directly by a generic shuffle
4575   // instruction because the target has no such instruction. Generate shuffles
4576   // which repeat i16 and i8 several times until they fit in i32, and then can
4577   // be manipulated by target suported shuffles.
4578   EVT EltVT = SrcVT.getVectorElementType();
4579   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4580     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4581
4582   // Recreate the 256-bit vector and place the same 128-bit vector
4583   // into the low and high part. This is necessary because we want
4584   // to use VPERM* to shuffle the vectors
4585   if (Is256BitVec) {
4586     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4587   }
4588
4589   return getLegalSplat(DAG, V1, EltNo);
4590 }
4591
4592 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4593 /// vector of zero or undef vector.  This produces a shuffle where the low
4594 /// element of V2 is swizzled into the zero/undef vector, landing at element
4595 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4596 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4597                                            bool IsZero,
4598                                            const X86Subtarget *Subtarget,
4599                                            SelectionDAG &DAG) {
4600   EVT VT = V2.getValueType();
4601   SDValue V1 = IsZero
4602     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4603   unsigned NumElems = VT.getVectorNumElements();
4604   SmallVector<int, 16> MaskVec;
4605   for (unsigned i = 0; i != NumElems; ++i)
4606     // If this is the insertion idx, put the low elt of V2 here.
4607     MaskVec.push_back(i == Idx ? NumElems : i);
4608   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4609 }
4610
4611 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4612 /// target specific opcode. Returns true if the Mask could be calculated.
4613 /// Sets IsUnary to true if only uses one source.
4614 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4615                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4616   unsigned NumElems = VT.getVectorNumElements();
4617   SDValue ImmN;
4618
4619   IsUnary = false;
4620   switch(N->getOpcode()) {
4621   case X86ISD::SHUFP:
4622     ImmN = N->getOperand(N->getNumOperands()-1);
4623     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4624     break;
4625   case X86ISD::UNPCKH:
4626     DecodeUNPCKHMask(VT, Mask);
4627     break;
4628   case X86ISD::UNPCKL:
4629     DecodeUNPCKLMask(VT, Mask);
4630     break;
4631   case X86ISD::MOVHLPS:
4632     DecodeMOVHLPSMask(NumElems, Mask);
4633     break;
4634   case X86ISD::MOVLHPS:
4635     DecodeMOVLHPSMask(NumElems, Mask);
4636     break;
4637   case X86ISD::PALIGNR:
4638     ImmN = N->getOperand(N->getNumOperands()-1);
4639     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4640     break;
4641   case X86ISD::PSHUFD:
4642   case X86ISD::VPERMILP:
4643     ImmN = N->getOperand(N->getNumOperands()-1);
4644     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4645     IsUnary = true;
4646     break;
4647   case X86ISD::PSHUFHW:
4648     ImmN = N->getOperand(N->getNumOperands()-1);
4649     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4650     IsUnary = true;
4651     break;
4652   case X86ISD::PSHUFLW:
4653     ImmN = N->getOperand(N->getNumOperands()-1);
4654     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4655     IsUnary = true;
4656     break;
4657   case X86ISD::VPERMI:
4658     ImmN = N->getOperand(N->getNumOperands()-1);
4659     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4660     IsUnary = true;
4661     break;
4662   case X86ISD::MOVSS:
4663   case X86ISD::MOVSD: {
4664     // The index 0 always comes from the first element of the second source,
4665     // this is why MOVSS and MOVSD are used in the first place. The other
4666     // elements come from the other positions of the first source vector
4667     Mask.push_back(NumElems);
4668     for (unsigned i = 1; i != NumElems; ++i) {
4669       Mask.push_back(i);
4670     }
4671     break;
4672   }
4673   case X86ISD::VPERM2X128:
4674     ImmN = N->getOperand(N->getNumOperands()-1);
4675     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4676     if (Mask.empty()) return false;
4677     break;
4678   case X86ISD::MOVDDUP:
4679   case X86ISD::MOVLHPD:
4680   case X86ISD::MOVLPD:
4681   case X86ISD::MOVLPS:
4682   case X86ISD::MOVSHDUP:
4683   case X86ISD::MOVSLDUP:
4684     // Not yet implemented
4685     return false;
4686   default: llvm_unreachable("unknown target shuffle node");
4687   }
4688
4689   return true;
4690 }
4691
4692 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4693 /// element of the result of the vector shuffle.
4694 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4695                                    unsigned Depth) {
4696   if (Depth == 6)
4697     return SDValue();  // Limit search depth.
4698
4699   SDValue V = SDValue(N, 0);
4700   EVT VT = V.getValueType();
4701   unsigned Opcode = V.getOpcode();
4702
4703   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4704   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4705     int Elt = SV->getMaskElt(Index);
4706
4707     if (Elt < 0)
4708       return DAG.getUNDEF(VT.getVectorElementType());
4709
4710     unsigned NumElems = VT.getVectorNumElements();
4711     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4712                                          : SV->getOperand(1);
4713     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4714   }
4715
4716   // Recurse into target specific vector shuffles to find scalars.
4717   if (isTargetShuffle(Opcode)) {
4718     MVT ShufVT = V.getValueType().getSimpleVT();
4719     unsigned NumElems = ShufVT.getVectorNumElements();
4720     SmallVector<int, 16> ShuffleMask;
4721     bool IsUnary;
4722
4723     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4724       return SDValue();
4725
4726     int Elt = ShuffleMask[Index];
4727     if (Elt < 0)
4728       return DAG.getUNDEF(ShufVT.getVectorElementType());
4729
4730     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4731                                          : N->getOperand(1);
4732     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4733                                Depth+1);
4734   }
4735
4736   // Actual nodes that may contain scalar elements
4737   if (Opcode == ISD::BITCAST) {
4738     V = V.getOperand(0);
4739     EVT SrcVT = V.getValueType();
4740     unsigned NumElems = VT.getVectorNumElements();
4741
4742     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4743       return SDValue();
4744   }
4745
4746   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4747     return (Index == 0) ? V.getOperand(0)
4748                         : DAG.getUNDEF(VT.getVectorElementType());
4749
4750   if (V.getOpcode() == ISD::BUILD_VECTOR)
4751     return V.getOperand(Index);
4752
4753   return SDValue();
4754 }
4755
4756 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4757 /// shuffle operation which come from a consecutively from a zero. The
4758 /// search can start in two different directions, from left or right.
4759 /// We count undefs as zeros until PreferredNum is reached.
4760 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4761                                          unsigned NumElems, bool ZerosFromLeft,
4762                                          SelectionDAG &DAG,
4763                                          unsigned PreferredNum = -1U) {
4764   unsigned NumZeros = 0;
4765   for (unsigned i = 0; i != NumElems; ++i) {
4766     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
4767     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4768     if (!Elt.getNode())
4769       break;
4770
4771     if (X86::isZeroNode(Elt))
4772       ++NumZeros;
4773     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
4774       NumZeros = std::min(NumZeros + 1, PreferredNum);
4775     else
4776       break;
4777   }
4778
4779   return NumZeros;
4780 }
4781
4782 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4783 /// correspond consecutively to elements from one of the vector operands,
4784 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4785 static
4786 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4787                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4788                               unsigned NumElems, unsigned &OpNum) {
4789   bool SeenV1 = false;
4790   bool SeenV2 = false;
4791
4792   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4793     int Idx = SVOp->getMaskElt(i);
4794     // Ignore undef indicies
4795     if (Idx < 0)
4796       continue;
4797
4798     if (Idx < (int)NumElems)
4799       SeenV1 = true;
4800     else
4801       SeenV2 = true;
4802
4803     // Only accept consecutive elements from the same vector
4804     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4805       return false;
4806   }
4807
4808   OpNum = SeenV1 ? 0 : 1;
4809   return true;
4810 }
4811
4812 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4813 /// logical left shift of a vector.
4814 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4815                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4816   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4817   unsigned NumZeros = getNumOfConsecutiveZeros(
4818       SVOp, NumElems, false /* check zeros from right */, DAG,
4819       SVOp->getMaskElt(0));
4820   unsigned OpSrc;
4821
4822   if (!NumZeros)
4823     return false;
4824
4825   // Considering the elements in the mask that are not consecutive zeros,
4826   // check if they consecutively come from only one of the source vectors.
4827   //
4828   //               V1 = {X, A, B, C}     0
4829   //                         \  \  \    /
4830   //   vector_shuffle V1, V2 <1, 2, 3, X>
4831   //
4832   if (!isShuffleMaskConsecutive(SVOp,
4833             0,                   // Mask Start Index
4834             NumElems-NumZeros,   // Mask End Index(exclusive)
4835             NumZeros,            // Where to start looking in the src vector
4836             NumElems,            // Number of elements in vector
4837             OpSrc))              // Which source operand ?
4838     return false;
4839
4840   isLeft = false;
4841   ShAmt = NumZeros;
4842   ShVal = SVOp->getOperand(OpSrc);
4843   return true;
4844 }
4845
4846 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4847 /// logical left shift of a vector.
4848 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4849                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4850   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4851   unsigned NumZeros = getNumOfConsecutiveZeros(
4852       SVOp, NumElems, true /* check zeros from left */, DAG,
4853       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
4854   unsigned OpSrc;
4855
4856   if (!NumZeros)
4857     return false;
4858
4859   // Considering the elements in the mask that are not consecutive zeros,
4860   // check if they consecutively come from only one of the source vectors.
4861   //
4862   //                           0    { A, B, X, X } = V2
4863   //                          / \    /  /
4864   //   vector_shuffle V1, V2 <X, X, 4, 5>
4865   //
4866   if (!isShuffleMaskConsecutive(SVOp,
4867             NumZeros,     // Mask Start Index
4868             NumElems,     // Mask End Index(exclusive)
4869             0,            // Where to start looking in the src vector
4870             NumElems,     // Number of elements in vector
4871             OpSrc))       // Which source operand ?
4872     return false;
4873
4874   isLeft = true;
4875   ShAmt = NumZeros;
4876   ShVal = SVOp->getOperand(OpSrc);
4877   return true;
4878 }
4879
4880 /// isVectorShift - Returns true if the shuffle can be implemented as a
4881 /// logical left or right shift of a vector.
4882 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4883                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4884   // Although the logic below support any bitwidth size, there are no
4885   // shift instructions which handle more than 128-bit vectors.
4886   if (!SVOp->getValueType(0).is128BitVector())
4887     return false;
4888
4889   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4890       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4891     return true;
4892
4893   return false;
4894 }
4895
4896 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4897 ///
4898 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4899                                        unsigned NumNonZero, unsigned NumZero,
4900                                        SelectionDAG &DAG,
4901                                        const X86Subtarget* Subtarget,
4902                                        const TargetLowering &TLI) {
4903   if (NumNonZero > 8)
4904     return SDValue();
4905
4906   DebugLoc dl = Op.getDebugLoc();
4907   SDValue V(0, 0);
4908   bool First = true;
4909   for (unsigned i = 0; i < 16; ++i) {
4910     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4911     if (ThisIsNonZero && First) {
4912       if (NumZero)
4913         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4914       else
4915         V = DAG.getUNDEF(MVT::v8i16);
4916       First = false;
4917     }
4918
4919     if ((i & 1) != 0) {
4920       SDValue ThisElt(0, 0), LastElt(0, 0);
4921       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4922       if (LastIsNonZero) {
4923         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4924                               MVT::i16, Op.getOperand(i-1));
4925       }
4926       if (ThisIsNonZero) {
4927         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4928         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4929                               ThisElt, DAG.getConstant(8, MVT::i8));
4930         if (LastIsNonZero)
4931           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4932       } else
4933         ThisElt = LastElt;
4934
4935       if (ThisElt.getNode())
4936         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4937                         DAG.getIntPtrConstant(i/2));
4938     }
4939   }
4940
4941   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4942 }
4943
4944 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4945 ///
4946 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4947                                      unsigned NumNonZero, unsigned NumZero,
4948                                      SelectionDAG &DAG,
4949                                      const X86Subtarget* Subtarget,
4950                                      const TargetLowering &TLI) {
4951   if (NumNonZero > 4)
4952     return SDValue();
4953
4954   DebugLoc dl = Op.getDebugLoc();
4955   SDValue V(0, 0);
4956   bool First = true;
4957   for (unsigned i = 0; i < 8; ++i) {
4958     bool isNonZero = (NonZeros & (1 << i)) != 0;
4959     if (isNonZero) {
4960       if (First) {
4961         if (NumZero)
4962           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4963         else
4964           V = DAG.getUNDEF(MVT::v8i16);
4965         First = false;
4966       }
4967       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4968                       MVT::v8i16, V, Op.getOperand(i),
4969                       DAG.getIntPtrConstant(i));
4970     }
4971   }
4972
4973   return V;
4974 }
4975
4976 /// getVShift - Return a vector logical shift node.
4977 ///
4978 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4979                          unsigned NumBits, SelectionDAG &DAG,
4980                          const TargetLowering &TLI, DebugLoc dl) {
4981   assert(VT.is128BitVector() && "Unknown type for VShift");
4982   EVT ShVT = MVT::v2i64;
4983   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4984   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4985   return DAG.getNode(ISD::BITCAST, dl, VT,
4986                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4987                              DAG.getConstant(NumBits,
4988                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4989 }
4990
4991 SDValue
4992 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4993                                           SelectionDAG &DAG) const {
4994
4995   // Check if the scalar load can be widened into a vector load. And if
4996   // the address is "base + cst" see if the cst can be "absorbed" into
4997   // the shuffle mask.
4998   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4999     SDValue Ptr = LD->getBasePtr();
5000     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5001       return SDValue();
5002     EVT PVT = LD->getValueType(0);
5003     if (PVT != MVT::i32 && PVT != MVT::f32)
5004       return SDValue();
5005
5006     int FI = -1;
5007     int64_t Offset = 0;
5008     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5009       FI = FINode->getIndex();
5010       Offset = 0;
5011     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5012                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5013       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5014       Offset = Ptr.getConstantOperandVal(1);
5015       Ptr = Ptr.getOperand(0);
5016     } else {
5017       return SDValue();
5018     }
5019
5020     // FIXME: 256-bit vector instructions don't require a strict alignment,
5021     // improve this code to support it better.
5022     unsigned RequiredAlign = VT.getSizeInBits()/8;
5023     SDValue Chain = LD->getChain();
5024     // Make sure the stack object alignment is at least 16 or 32.
5025     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5026     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5027       if (MFI->isFixedObjectIndex(FI)) {
5028         // Can't change the alignment. FIXME: It's possible to compute
5029         // the exact stack offset and reference FI + adjust offset instead.
5030         // If someone *really* cares about this. That's the way to implement it.
5031         return SDValue();
5032       } else {
5033         MFI->setObjectAlignment(FI, RequiredAlign);
5034       }
5035     }
5036
5037     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5038     // Ptr + (Offset & ~15).
5039     if (Offset < 0)
5040       return SDValue();
5041     if ((Offset % RequiredAlign) & 3)
5042       return SDValue();
5043     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5044     if (StartOffset)
5045       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5046                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5047
5048     int EltNo = (Offset - StartOffset) >> 2;
5049     unsigned NumElems = VT.getVectorNumElements();
5050
5051     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5052     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5053                              LD->getPointerInfo().getWithOffset(StartOffset),
5054                              false, false, false, 0);
5055
5056     SmallVector<int, 8> Mask;
5057     for (unsigned i = 0; i != NumElems; ++i)
5058       Mask.push_back(EltNo);
5059
5060     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5061   }
5062
5063   return SDValue();
5064 }
5065
5066 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5067 /// vector of type 'VT', see if the elements can be replaced by a single large
5068 /// load which has the same value as a build_vector whose operands are 'elts'.
5069 ///
5070 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5071 ///
5072 /// FIXME: we'd also like to handle the case where the last elements are zero
5073 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5074 /// There's even a handy isZeroNode for that purpose.
5075 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5076                                         DebugLoc &DL, SelectionDAG &DAG) {
5077   EVT EltVT = VT.getVectorElementType();
5078   unsigned NumElems = Elts.size();
5079
5080   LoadSDNode *LDBase = NULL;
5081   unsigned LastLoadedElt = -1U;
5082
5083   // For each element in the initializer, see if we've found a load or an undef.
5084   // If we don't find an initial load element, or later load elements are
5085   // non-consecutive, bail out.
5086   for (unsigned i = 0; i < NumElems; ++i) {
5087     SDValue Elt = Elts[i];
5088
5089     if (!Elt.getNode() ||
5090         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5091       return SDValue();
5092     if (!LDBase) {
5093       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5094         return SDValue();
5095       LDBase = cast<LoadSDNode>(Elt.getNode());
5096       LastLoadedElt = i;
5097       continue;
5098     }
5099     if (Elt.getOpcode() == ISD::UNDEF)
5100       continue;
5101
5102     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5103     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5104       return SDValue();
5105     LastLoadedElt = i;
5106   }
5107
5108   // If we have found an entire vector of loads and undefs, then return a large
5109   // load of the entire vector width starting at the base pointer.  If we found
5110   // consecutive loads for the low half, generate a vzext_load node.
5111   if (LastLoadedElt == NumElems - 1) {
5112     SDValue NewLd = SDValue();
5113     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5114       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5115                           LDBase->getPointerInfo(),
5116                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5117                           LDBase->isInvariant(), 0);
5118     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5119                         LDBase->getPointerInfo(),
5120                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5121                         LDBase->isInvariant(), LDBase->getAlignment());
5122
5123     if (LDBase->hasAnyUseOfValue(1)) {
5124       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5125                                      SDValue(LDBase, 1),
5126                                      SDValue(NewLd.getNode(), 1));
5127       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5128       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5129                              SDValue(NewLd.getNode(), 1));
5130     }
5131
5132     return NewLd;
5133   }
5134   if (NumElems == 4 && LastLoadedElt == 1 &&
5135       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5136     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5137     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5138     SDValue ResNode =
5139         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5140                                 array_lengthof(Ops), MVT::i64,
5141                                 LDBase->getPointerInfo(),
5142                                 LDBase->getAlignment(),
5143                                 false/*isVolatile*/, true/*ReadMem*/,
5144                                 false/*WriteMem*/);
5145
5146     // Make sure the newly-created LOAD is in the same position as LDBase in
5147     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5148     // update uses of LDBase's output chain to use the TokenFactor.
5149     if (LDBase->hasAnyUseOfValue(1)) {
5150       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5151                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5152       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5153       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5154                              SDValue(ResNode.getNode(), 1));
5155     }
5156
5157     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5158   }
5159   return SDValue();
5160 }
5161
5162 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5163 /// to generate a splat value for the following cases:
5164 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5165 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5166 /// a scalar load, or a constant.
5167 /// The VBROADCAST node is returned when a pattern is found,
5168 /// or SDValue() otherwise.
5169 SDValue
5170 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5171   if (!Subtarget->hasFp256())
5172     return SDValue();
5173
5174   MVT VT = Op.getValueType().getSimpleVT();
5175   DebugLoc dl = Op.getDebugLoc();
5176
5177   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5178          "Unsupported vector type for broadcast.");
5179
5180   SDValue Ld;
5181   bool ConstSplatVal;
5182
5183   switch (Op.getOpcode()) {
5184     default:
5185       // Unknown pattern found.
5186       return SDValue();
5187
5188     case ISD::BUILD_VECTOR: {
5189       // The BUILD_VECTOR node must be a splat.
5190       if (!isSplatVector(Op.getNode()))
5191         return SDValue();
5192
5193       Ld = Op.getOperand(0);
5194       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5195                      Ld.getOpcode() == ISD::ConstantFP);
5196
5197       // The suspected load node has several users. Make sure that all
5198       // of its users are from the BUILD_VECTOR node.
5199       // Constants may have multiple users.
5200       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5201         return SDValue();
5202       break;
5203     }
5204
5205     case ISD::VECTOR_SHUFFLE: {
5206       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5207
5208       // Shuffles must have a splat mask where the first element is
5209       // broadcasted.
5210       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5211         return SDValue();
5212
5213       SDValue Sc = Op.getOperand(0);
5214       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5215           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5216
5217         if (!Subtarget->hasInt256())
5218           return SDValue();
5219
5220         // Use the register form of the broadcast instruction available on AVX2.
5221         if (VT.is256BitVector())
5222           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5223         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5224       }
5225
5226       Ld = Sc.getOperand(0);
5227       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5228                        Ld.getOpcode() == ISD::ConstantFP);
5229
5230       // The scalar_to_vector node and the suspected
5231       // load node must have exactly one user.
5232       // Constants may have multiple users.
5233       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5234         return SDValue();
5235       break;
5236     }
5237   }
5238
5239   bool Is256 = VT.is256BitVector();
5240
5241   // Handle the broadcasting a single constant scalar from the constant pool
5242   // into a vector. On Sandybridge it is still better to load a constant vector
5243   // from the constant pool and not to broadcast it from a scalar.
5244   if (ConstSplatVal && Subtarget->hasInt256()) {
5245     EVT CVT = Ld.getValueType();
5246     assert(!CVT.isVector() && "Must not broadcast a vector type");
5247     unsigned ScalarSize = CVT.getSizeInBits();
5248
5249     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5250       const Constant *C = 0;
5251       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5252         C = CI->getConstantIntValue();
5253       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5254         C = CF->getConstantFPValue();
5255
5256       assert(C && "Invalid constant type");
5257
5258       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5259       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5260       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5261                        MachinePointerInfo::getConstantPool(),
5262                        false, false, false, Alignment);
5263
5264       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5265     }
5266   }
5267
5268   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5269   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5270
5271   // Handle AVX2 in-register broadcasts.
5272   if (!IsLoad && Subtarget->hasInt256() &&
5273       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5274     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5275
5276   // The scalar source must be a normal load.
5277   if (!IsLoad)
5278     return SDValue();
5279
5280   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5281     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5282
5283   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5284   // double since there is no vbroadcastsd xmm
5285   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5286     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5287       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5288   }
5289
5290   // Unsupported broadcast.
5291   return SDValue();
5292 }
5293
5294 SDValue
5295 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5296   EVT VT = Op.getValueType();
5297
5298   // Skip if insert_vec_elt is not supported.
5299   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5300     return SDValue();
5301
5302   DebugLoc DL = Op.getDebugLoc();
5303   unsigned NumElems = Op.getNumOperands();
5304
5305   SDValue VecIn1;
5306   SDValue VecIn2;
5307   SmallVector<unsigned, 4> InsertIndices;
5308   SmallVector<int, 8> Mask(NumElems, -1);
5309
5310   for (unsigned i = 0; i != NumElems; ++i) {
5311     unsigned Opc = Op.getOperand(i).getOpcode();
5312
5313     if (Opc == ISD::UNDEF)
5314       continue;
5315
5316     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5317       // Quit if more than 1 elements need inserting.
5318       if (InsertIndices.size() > 1)
5319         return SDValue();
5320
5321       InsertIndices.push_back(i);
5322       continue;
5323     }
5324
5325     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5326     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5327
5328     // Quit if extracted from vector of different type.
5329     if (ExtractedFromVec.getValueType() != VT)
5330       return SDValue();
5331
5332     // Quit if non-constant index.
5333     if (!isa<ConstantSDNode>(ExtIdx))
5334       return SDValue();
5335
5336     if (VecIn1.getNode() == 0)
5337       VecIn1 = ExtractedFromVec;
5338     else if (VecIn1 != ExtractedFromVec) {
5339       if (VecIn2.getNode() == 0)
5340         VecIn2 = ExtractedFromVec;
5341       else if (VecIn2 != ExtractedFromVec)
5342         // Quit if more than 2 vectors to shuffle
5343         return SDValue();
5344     }
5345
5346     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5347
5348     if (ExtractedFromVec == VecIn1)
5349       Mask[i] = Idx;
5350     else if (ExtractedFromVec == VecIn2)
5351       Mask[i] = Idx + NumElems;
5352   }
5353
5354   if (VecIn1.getNode() == 0)
5355     return SDValue();
5356
5357   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5358   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5359   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5360     unsigned Idx = InsertIndices[i];
5361     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5362                      DAG.getIntPtrConstant(Idx));
5363   }
5364
5365   return NV;
5366 }
5367
5368 SDValue
5369 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5370   DebugLoc dl = Op.getDebugLoc();
5371
5372   MVT VT = Op.getValueType().getSimpleVT();
5373   MVT ExtVT = VT.getVectorElementType();
5374   unsigned NumElems = Op.getNumOperands();
5375
5376   // Vectors containing all zeros can be matched by pxor and xorps later
5377   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5378     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5379     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5380     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5381       return Op;
5382
5383     return getZeroVector(VT, Subtarget, DAG, dl);
5384   }
5385
5386   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5387   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5388   // vpcmpeqd on 256-bit vectors.
5389   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5390     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5391       return Op;
5392
5393     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5394   }
5395
5396   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5397   if (Broadcast.getNode())
5398     return Broadcast;
5399
5400   unsigned EVTBits = ExtVT.getSizeInBits();
5401
5402   unsigned NumZero  = 0;
5403   unsigned NumNonZero = 0;
5404   unsigned NonZeros = 0;
5405   bool IsAllConstants = true;
5406   SmallSet<SDValue, 8> Values;
5407   for (unsigned i = 0; i < NumElems; ++i) {
5408     SDValue Elt = Op.getOperand(i);
5409     if (Elt.getOpcode() == ISD::UNDEF)
5410       continue;
5411     Values.insert(Elt);
5412     if (Elt.getOpcode() != ISD::Constant &&
5413         Elt.getOpcode() != ISD::ConstantFP)
5414       IsAllConstants = false;
5415     if (X86::isZeroNode(Elt))
5416       NumZero++;
5417     else {
5418       NonZeros |= (1 << i);
5419       NumNonZero++;
5420     }
5421   }
5422
5423   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5424   if (NumNonZero == 0)
5425     return DAG.getUNDEF(VT);
5426
5427   // Special case for single non-zero, non-undef, element.
5428   if (NumNonZero == 1) {
5429     unsigned Idx = countTrailingZeros(NonZeros);
5430     SDValue Item = Op.getOperand(Idx);
5431
5432     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5433     // the value are obviously zero, truncate the value to i32 and do the
5434     // insertion that way.  Only do this if the value is non-constant or if the
5435     // value is a constant being inserted into element 0.  It is cheaper to do
5436     // a constant pool load than it is to do a movd + shuffle.
5437     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5438         (!IsAllConstants || Idx == 0)) {
5439       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5440         // Handle SSE only.
5441         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5442         EVT VecVT = MVT::v4i32;
5443         unsigned VecElts = 4;
5444
5445         // Truncate the value (which may itself be a constant) to i32, and
5446         // convert it to a vector with movd (S2V+shuffle to zero extend).
5447         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5448         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5449         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5450
5451         // Now we have our 32-bit value zero extended in the low element of
5452         // a vector.  If Idx != 0, swizzle it into place.
5453         if (Idx != 0) {
5454           SmallVector<int, 4> Mask;
5455           Mask.push_back(Idx);
5456           for (unsigned i = 1; i != VecElts; ++i)
5457             Mask.push_back(i);
5458           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5459                                       &Mask[0]);
5460         }
5461         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5462       }
5463     }
5464
5465     // If we have a constant or non-constant insertion into the low element of
5466     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5467     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5468     // depending on what the source datatype is.
5469     if (Idx == 0) {
5470       if (NumZero == 0)
5471         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5472
5473       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5474           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5475         if (VT.is256BitVector()) {
5476           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5477           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5478                              Item, DAG.getIntPtrConstant(0));
5479         }
5480         assert(VT.is128BitVector() && "Expected an SSE value type!");
5481         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5482         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5483         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5484       }
5485
5486       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5487         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5488         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5489         if (VT.is256BitVector()) {
5490           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5491           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5492         } else {
5493           assert(VT.is128BitVector() && "Expected an SSE value type!");
5494           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5495         }
5496         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5497       }
5498     }
5499
5500     // Is it a vector logical left shift?
5501     if (NumElems == 2 && Idx == 1 &&
5502         X86::isZeroNode(Op.getOperand(0)) &&
5503         !X86::isZeroNode(Op.getOperand(1))) {
5504       unsigned NumBits = VT.getSizeInBits();
5505       return getVShift(true, VT,
5506                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5507                                    VT, Op.getOperand(1)),
5508                        NumBits/2, DAG, *this, dl);
5509     }
5510
5511     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5512       return SDValue();
5513
5514     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5515     // is a non-constant being inserted into an element other than the low one,
5516     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5517     // movd/movss) to move this into the low element, then shuffle it into
5518     // place.
5519     if (EVTBits == 32) {
5520       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5521
5522       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5523       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5524       SmallVector<int, 8> MaskVec;
5525       for (unsigned i = 0; i != NumElems; ++i)
5526         MaskVec.push_back(i == Idx ? 0 : 1);
5527       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5528     }
5529   }
5530
5531   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5532   if (Values.size() == 1) {
5533     if (EVTBits == 32) {
5534       // Instead of a shuffle like this:
5535       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5536       // Check if it's possible to issue this instead.
5537       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5538       unsigned Idx = countTrailingZeros(NonZeros);
5539       SDValue Item = Op.getOperand(Idx);
5540       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5541         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5542     }
5543     return SDValue();
5544   }
5545
5546   // A vector full of immediates; various special cases are already
5547   // handled, so this is best done with a single constant-pool load.
5548   if (IsAllConstants)
5549     return SDValue();
5550
5551   // For AVX-length vectors, build the individual 128-bit pieces and use
5552   // shuffles to put them in place.
5553   if (VT.is256BitVector()) {
5554     SmallVector<SDValue, 32> V;
5555     for (unsigned i = 0; i != NumElems; ++i)
5556       V.push_back(Op.getOperand(i));
5557
5558     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5559
5560     // Build both the lower and upper subvector.
5561     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5562     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5563                                 NumElems/2);
5564
5565     // Recreate the wider vector with the lower and upper part.
5566     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5567   }
5568
5569   // Let legalizer expand 2-wide build_vectors.
5570   if (EVTBits == 64) {
5571     if (NumNonZero == 1) {
5572       // One half is zero or undef.
5573       unsigned Idx = countTrailingZeros(NonZeros);
5574       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5575                                  Op.getOperand(Idx));
5576       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5577     }
5578     return SDValue();
5579   }
5580
5581   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5582   if (EVTBits == 8 && NumElems == 16) {
5583     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5584                                         Subtarget, *this);
5585     if (V.getNode()) return V;
5586   }
5587
5588   if (EVTBits == 16 && NumElems == 8) {
5589     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5590                                       Subtarget, *this);
5591     if (V.getNode()) return V;
5592   }
5593
5594   // If element VT is == 32 bits, turn it into a number of shuffles.
5595   SmallVector<SDValue, 8> V(NumElems);
5596   if (NumElems == 4 && NumZero > 0) {
5597     for (unsigned i = 0; i < 4; ++i) {
5598       bool isZero = !(NonZeros & (1 << i));
5599       if (isZero)
5600         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5601       else
5602         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5603     }
5604
5605     for (unsigned i = 0; i < 2; ++i) {
5606       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5607         default: break;
5608         case 0:
5609           V[i] = V[i*2];  // Must be a zero vector.
5610           break;
5611         case 1:
5612           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5613           break;
5614         case 2:
5615           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5616           break;
5617         case 3:
5618           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5619           break;
5620       }
5621     }
5622
5623     bool Reverse1 = (NonZeros & 0x3) == 2;
5624     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5625     int MaskVec[] = {
5626       Reverse1 ? 1 : 0,
5627       Reverse1 ? 0 : 1,
5628       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5629       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5630     };
5631     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5632   }
5633
5634   if (Values.size() > 1 && VT.is128BitVector()) {
5635     // Check for a build vector of consecutive loads.
5636     for (unsigned i = 0; i < NumElems; ++i)
5637       V[i] = Op.getOperand(i);
5638
5639     // Check for elements which are consecutive loads.
5640     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5641     if (LD.getNode())
5642       return LD;
5643
5644     // Check for a build vector from mostly shuffle plus few inserting.
5645     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5646     if (Sh.getNode())
5647       return Sh;
5648
5649     // For SSE 4.1, use insertps to put the high elements into the low element.
5650     if (getSubtarget()->hasSSE41()) {
5651       SDValue Result;
5652       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5653         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5654       else
5655         Result = DAG.getUNDEF(VT);
5656
5657       for (unsigned i = 1; i < NumElems; ++i) {
5658         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5659         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5660                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5661       }
5662       return Result;
5663     }
5664
5665     // Otherwise, expand into a number of unpckl*, start by extending each of
5666     // our (non-undef) elements to the full vector width with the element in the
5667     // bottom slot of the vector (which generates no code for SSE).
5668     for (unsigned i = 0; i < NumElems; ++i) {
5669       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5670         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5671       else
5672         V[i] = DAG.getUNDEF(VT);
5673     }
5674
5675     // Next, we iteratively mix elements, e.g. for v4f32:
5676     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5677     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5678     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5679     unsigned EltStride = NumElems >> 1;
5680     while (EltStride != 0) {
5681       for (unsigned i = 0; i < EltStride; ++i) {
5682         // If V[i+EltStride] is undef and this is the first round of mixing,
5683         // then it is safe to just drop this shuffle: V[i] is already in the
5684         // right place, the one element (since it's the first round) being
5685         // inserted as undef can be dropped.  This isn't safe for successive
5686         // rounds because they will permute elements within both vectors.
5687         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5688             EltStride == NumElems/2)
5689           continue;
5690
5691         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5692       }
5693       EltStride >>= 1;
5694     }
5695     return V[0];
5696   }
5697   return SDValue();
5698 }
5699
5700 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5701 // to create 256-bit vectors from two other 128-bit ones.
5702 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5703   DebugLoc dl = Op.getDebugLoc();
5704   MVT ResVT = Op.getValueType().getSimpleVT();
5705
5706   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5707
5708   SDValue V1 = Op.getOperand(0);
5709   SDValue V2 = Op.getOperand(1);
5710   unsigned NumElems = ResVT.getVectorNumElements();
5711
5712   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5713 }
5714
5715 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5716   assert(Op.getNumOperands() == 2);
5717
5718   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5719   // from two other 128-bit ones.
5720   return LowerAVXCONCAT_VECTORS(Op, DAG);
5721 }
5722
5723 // Try to lower a shuffle node into a simple blend instruction.
5724 static SDValue
5725 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5726                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5727   SDValue V1 = SVOp->getOperand(0);
5728   SDValue V2 = SVOp->getOperand(1);
5729   DebugLoc dl = SVOp->getDebugLoc();
5730   MVT VT = SVOp->getValueType(0).getSimpleVT();
5731   MVT EltVT = VT.getVectorElementType();
5732   unsigned NumElems = VT.getVectorNumElements();
5733
5734   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5735     return SDValue();
5736   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5737     return SDValue();
5738
5739   // Check the mask for BLEND and build the value.
5740   unsigned MaskValue = 0;
5741   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5742   unsigned NumLanes = (NumElems-1)/8 + 1;
5743   unsigned NumElemsInLane = NumElems / NumLanes;
5744
5745   // Blend for v16i16 should be symetric for the both lanes.
5746   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5747
5748     int SndLaneEltIdx = (NumLanes == 2) ?
5749       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5750     int EltIdx = SVOp->getMaskElt(i);
5751
5752     if ((EltIdx < 0 || EltIdx == (int)i) &&
5753         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5754       continue;
5755
5756     if (((unsigned)EltIdx == (i + NumElems)) &&
5757         (SndLaneEltIdx < 0 ||
5758          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5759       MaskValue |= (1<<i);
5760     else
5761       return SDValue();
5762   }
5763
5764   // Convert i32 vectors to floating point if it is not AVX2.
5765   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5766   MVT BlendVT = VT;
5767   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5768     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5769                                NumElems);
5770     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5771     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5772   }
5773
5774   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5775                             DAG.getConstant(MaskValue, MVT::i32));
5776   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5777 }
5778
5779 // v8i16 shuffles - Prefer shuffles in the following order:
5780 // 1. [all]   pshuflw, pshufhw, optional move
5781 // 2. [ssse3] 1 x pshufb
5782 // 3. [ssse3] 2 x pshufb + 1 x por
5783 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5784 static SDValue
5785 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5786                          SelectionDAG &DAG) {
5787   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5788   SDValue V1 = SVOp->getOperand(0);
5789   SDValue V2 = SVOp->getOperand(1);
5790   DebugLoc dl = SVOp->getDebugLoc();
5791   SmallVector<int, 8> MaskVals;
5792
5793   // Determine if more than 1 of the words in each of the low and high quadwords
5794   // of the result come from the same quadword of one of the two inputs.  Undef
5795   // mask values count as coming from any quadword, for better codegen.
5796   unsigned LoQuad[] = { 0, 0, 0, 0 };
5797   unsigned HiQuad[] = { 0, 0, 0, 0 };
5798   std::bitset<4> InputQuads;
5799   for (unsigned i = 0; i < 8; ++i) {
5800     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5801     int EltIdx = SVOp->getMaskElt(i);
5802     MaskVals.push_back(EltIdx);
5803     if (EltIdx < 0) {
5804       ++Quad[0];
5805       ++Quad[1];
5806       ++Quad[2];
5807       ++Quad[3];
5808       continue;
5809     }
5810     ++Quad[EltIdx / 4];
5811     InputQuads.set(EltIdx / 4);
5812   }
5813
5814   int BestLoQuad = -1;
5815   unsigned MaxQuad = 1;
5816   for (unsigned i = 0; i < 4; ++i) {
5817     if (LoQuad[i] > MaxQuad) {
5818       BestLoQuad = i;
5819       MaxQuad = LoQuad[i];
5820     }
5821   }
5822
5823   int BestHiQuad = -1;
5824   MaxQuad = 1;
5825   for (unsigned i = 0; i < 4; ++i) {
5826     if (HiQuad[i] > MaxQuad) {
5827       BestHiQuad = i;
5828       MaxQuad = HiQuad[i];
5829     }
5830   }
5831
5832   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5833   // of the two input vectors, shuffle them into one input vector so only a
5834   // single pshufb instruction is necessary. If There are more than 2 input
5835   // quads, disable the next transformation since it does not help SSSE3.
5836   bool V1Used = InputQuads[0] || InputQuads[1];
5837   bool V2Used = InputQuads[2] || InputQuads[3];
5838   if (Subtarget->hasSSSE3()) {
5839     if (InputQuads.count() == 2 && V1Used && V2Used) {
5840       BestLoQuad = InputQuads[0] ? 0 : 1;
5841       BestHiQuad = InputQuads[2] ? 2 : 3;
5842     }
5843     if (InputQuads.count() > 2) {
5844       BestLoQuad = -1;
5845       BestHiQuad = -1;
5846     }
5847   }
5848
5849   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5850   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5851   // words from all 4 input quadwords.
5852   SDValue NewV;
5853   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5854     int MaskV[] = {
5855       BestLoQuad < 0 ? 0 : BestLoQuad,
5856       BestHiQuad < 0 ? 1 : BestHiQuad
5857     };
5858     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5859                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5860                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5861     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5862
5863     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5864     // source words for the shuffle, to aid later transformations.
5865     bool AllWordsInNewV = true;
5866     bool InOrder[2] = { true, true };
5867     for (unsigned i = 0; i != 8; ++i) {
5868       int idx = MaskVals[i];
5869       if (idx != (int)i)
5870         InOrder[i/4] = false;
5871       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5872         continue;
5873       AllWordsInNewV = false;
5874       break;
5875     }
5876
5877     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5878     if (AllWordsInNewV) {
5879       for (int i = 0; i != 8; ++i) {
5880         int idx = MaskVals[i];
5881         if (idx < 0)
5882           continue;
5883         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5884         if ((idx != i) && idx < 4)
5885           pshufhw = false;
5886         if ((idx != i) && idx > 3)
5887           pshuflw = false;
5888       }
5889       V1 = NewV;
5890       V2Used = false;
5891       BestLoQuad = 0;
5892       BestHiQuad = 1;
5893     }
5894
5895     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5896     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5897     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5898       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5899       unsigned TargetMask = 0;
5900       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5901                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5902       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5903       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5904                              getShufflePSHUFLWImmediate(SVOp);
5905       V1 = NewV.getOperand(0);
5906       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5907     }
5908   }
5909
5910   // Promote splats to a larger type which usually leads to more efficient code.
5911   // FIXME: Is this true if pshufb is available?
5912   if (SVOp->isSplat())
5913     return PromoteSplat(SVOp, DAG);
5914
5915   // If we have SSSE3, and all words of the result are from 1 input vector,
5916   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5917   // is present, fall back to case 4.
5918   if (Subtarget->hasSSSE3()) {
5919     SmallVector<SDValue,16> pshufbMask;
5920
5921     // If we have elements from both input vectors, set the high bit of the
5922     // shuffle mask element to zero out elements that come from V2 in the V1
5923     // mask, and elements that come from V1 in the V2 mask, so that the two
5924     // results can be OR'd together.
5925     bool TwoInputs = V1Used && V2Used;
5926     for (unsigned i = 0; i != 8; ++i) {
5927       int EltIdx = MaskVals[i] * 2;
5928       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5929       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5930       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5931       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5932     }
5933     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5934     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5935                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5936                                  MVT::v16i8, &pshufbMask[0], 16));
5937     if (!TwoInputs)
5938       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5939
5940     // Calculate the shuffle mask for the second input, shuffle it, and
5941     // OR it with the first shuffled input.
5942     pshufbMask.clear();
5943     for (unsigned i = 0; i != 8; ++i) {
5944       int EltIdx = MaskVals[i] * 2;
5945       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5946       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5947       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5948       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5949     }
5950     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5951     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5952                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5953                                  MVT::v16i8, &pshufbMask[0], 16));
5954     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5955     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5956   }
5957
5958   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5959   // and update MaskVals with new element order.
5960   std::bitset<8> InOrder;
5961   if (BestLoQuad >= 0) {
5962     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5963     for (int i = 0; i != 4; ++i) {
5964       int idx = MaskVals[i];
5965       if (idx < 0) {
5966         InOrder.set(i);
5967       } else if ((idx / 4) == BestLoQuad) {
5968         MaskV[i] = idx & 3;
5969         InOrder.set(i);
5970       }
5971     }
5972     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5973                                 &MaskV[0]);
5974
5975     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5976       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5977       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5978                                   NewV.getOperand(0),
5979                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5980     }
5981   }
5982
5983   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5984   // and update MaskVals with the new element order.
5985   if (BestHiQuad >= 0) {
5986     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5987     for (unsigned i = 4; i != 8; ++i) {
5988       int idx = MaskVals[i];
5989       if (idx < 0) {
5990         InOrder.set(i);
5991       } else if ((idx / 4) == BestHiQuad) {
5992         MaskV[i] = (idx & 3) + 4;
5993         InOrder.set(i);
5994       }
5995     }
5996     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5997                                 &MaskV[0]);
5998
5999     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6000       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6001       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6002                                   NewV.getOperand(0),
6003                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6004     }
6005   }
6006
6007   // In case BestHi & BestLo were both -1, which means each quadword has a word
6008   // from each of the four input quadwords, calculate the InOrder bitvector now
6009   // before falling through to the insert/extract cleanup.
6010   if (BestLoQuad == -1 && BestHiQuad == -1) {
6011     NewV = V1;
6012     for (int i = 0; i != 8; ++i)
6013       if (MaskVals[i] < 0 || MaskVals[i] == i)
6014         InOrder.set(i);
6015   }
6016
6017   // The other elements are put in the right place using pextrw and pinsrw.
6018   for (unsigned i = 0; i != 8; ++i) {
6019     if (InOrder[i])
6020       continue;
6021     int EltIdx = MaskVals[i];
6022     if (EltIdx < 0)
6023       continue;
6024     SDValue ExtOp = (EltIdx < 8) ?
6025       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6026                   DAG.getIntPtrConstant(EltIdx)) :
6027       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6028                   DAG.getIntPtrConstant(EltIdx - 8));
6029     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6030                        DAG.getIntPtrConstant(i));
6031   }
6032   return NewV;
6033 }
6034
6035 // v16i8 shuffles - Prefer shuffles in the following order:
6036 // 1. [ssse3] 1 x pshufb
6037 // 2. [ssse3] 2 x pshufb + 1 x por
6038 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6039 static
6040 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6041                                  SelectionDAG &DAG,
6042                                  const X86TargetLowering &TLI) {
6043   SDValue V1 = SVOp->getOperand(0);
6044   SDValue V2 = SVOp->getOperand(1);
6045   DebugLoc dl = SVOp->getDebugLoc();
6046   ArrayRef<int> MaskVals = SVOp->getMask();
6047
6048   // Promote splats to a larger type which usually leads to more efficient code.
6049   // FIXME: Is this true if pshufb is available?
6050   if (SVOp->isSplat())
6051     return PromoteSplat(SVOp, DAG);
6052
6053   // If we have SSSE3, case 1 is generated when all result bytes come from
6054   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6055   // present, fall back to case 3.
6056
6057   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6058   if (TLI.getSubtarget()->hasSSSE3()) {
6059     SmallVector<SDValue,16> pshufbMask;
6060
6061     // If all result elements are from one input vector, then only translate
6062     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6063     //
6064     // Otherwise, we have elements from both input vectors, and must zero out
6065     // elements that come from V2 in the first mask, and V1 in the second mask
6066     // so that we can OR them together.
6067     for (unsigned i = 0; i != 16; ++i) {
6068       int EltIdx = MaskVals[i];
6069       if (EltIdx < 0 || EltIdx >= 16)
6070         EltIdx = 0x80;
6071       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6072     }
6073     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6074                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6075                                  MVT::v16i8, &pshufbMask[0], 16));
6076
6077     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6078     // the 2nd operand if it's undefined or zero.
6079     if (V2.getOpcode() == ISD::UNDEF ||
6080         ISD::isBuildVectorAllZeros(V2.getNode()))
6081       return V1;
6082
6083     // Calculate the shuffle mask for the second input, shuffle it, and
6084     // OR it with the first shuffled input.
6085     pshufbMask.clear();
6086     for (unsigned i = 0; i != 16; ++i) {
6087       int EltIdx = MaskVals[i];
6088       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6089       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6090     }
6091     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6092                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6093                                  MVT::v16i8, &pshufbMask[0], 16));
6094     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6095   }
6096
6097   // No SSSE3 - Calculate in place words and then fix all out of place words
6098   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6099   // the 16 different words that comprise the two doublequadword input vectors.
6100   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6101   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6102   SDValue NewV = V1;
6103   for (int i = 0; i != 8; ++i) {
6104     int Elt0 = MaskVals[i*2];
6105     int Elt1 = MaskVals[i*2+1];
6106
6107     // This word of the result is all undef, skip it.
6108     if (Elt0 < 0 && Elt1 < 0)
6109       continue;
6110
6111     // This word of the result is already in the correct place, skip it.
6112     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6113       continue;
6114
6115     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6116     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6117     SDValue InsElt;
6118
6119     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6120     // using a single extract together, load it and store it.
6121     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6122       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6123                            DAG.getIntPtrConstant(Elt1 / 2));
6124       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6125                         DAG.getIntPtrConstant(i));
6126       continue;
6127     }
6128
6129     // If Elt1 is defined, extract it from the appropriate source.  If the
6130     // source byte is not also odd, shift the extracted word left 8 bits
6131     // otherwise clear the bottom 8 bits if we need to do an or.
6132     if (Elt1 >= 0) {
6133       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6134                            DAG.getIntPtrConstant(Elt1 / 2));
6135       if ((Elt1 & 1) == 0)
6136         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6137                              DAG.getConstant(8,
6138                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6139       else if (Elt0 >= 0)
6140         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6141                              DAG.getConstant(0xFF00, MVT::i16));
6142     }
6143     // If Elt0 is defined, extract it from the appropriate source.  If the
6144     // source byte is not also even, shift the extracted word right 8 bits. If
6145     // Elt1 was also defined, OR the extracted values together before
6146     // inserting them in the result.
6147     if (Elt0 >= 0) {
6148       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6149                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6150       if ((Elt0 & 1) != 0)
6151         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6152                               DAG.getConstant(8,
6153                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6154       else if (Elt1 >= 0)
6155         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6156                              DAG.getConstant(0x00FF, MVT::i16));
6157       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6158                          : InsElt0;
6159     }
6160     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6161                        DAG.getIntPtrConstant(i));
6162   }
6163   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6164 }
6165
6166 // v32i8 shuffles - Translate to VPSHUFB if possible.
6167 static
6168 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6169                                  const X86Subtarget *Subtarget,
6170                                  SelectionDAG &DAG) {
6171   MVT VT = SVOp->getValueType(0).getSimpleVT();
6172   SDValue V1 = SVOp->getOperand(0);
6173   SDValue V2 = SVOp->getOperand(1);
6174   DebugLoc dl = SVOp->getDebugLoc();
6175   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6176
6177   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6178   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6179   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6180
6181   // VPSHUFB may be generated if
6182   // (1) one of input vector is undefined or zeroinitializer.
6183   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6184   // And (2) the mask indexes don't cross the 128-bit lane.
6185   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6186       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6187     return SDValue();
6188
6189   if (V1IsAllZero && !V2IsAllZero) {
6190     CommuteVectorShuffleMask(MaskVals, 32);
6191     V1 = V2;
6192   }
6193   SmallVector<SDValue, 32> pshufbMask;
6194   for (unsigned i = 0; i != 32; i++) {
6195     int EltIdx = MaskVals[i];
6196     if (EltIdx < 0 || EltIdx >= 32)
6197       EltIdx = 0x80;
6198     else {
6199       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6200         // Cross lane is not allowed.
6201         return SDValue();
6202       EltIdx &= 0xf;
6203     }
6204     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6205   }
6206   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6207                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6208                                   MVT::v32i8, &pshufbMask[0], 32));
6209 }
6210
6211 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6212 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6213 /// done when every pair / quad of shuffle mask elements point to elements in
6214 /// the right sequence. e.g.
6215 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6216 static
6217 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6218                                  SelectionDAG &DAG) {
6219   MVT VT = SVOp->getValueType(0).getSimpleVT();
6220   DebugLoc dl = SVOp->getDebugLoc();
6221   unsigned NumElems = VT.getVectorNumElements();
6222   MVT NewVT;
6223   unsigned Scale;
6224   switch (VT.SimpleTy) {
6225   default: llvm_unreachable("Unexpected!");
6226   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6227   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6228   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6229   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6230   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6231   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6232   }
6233
6234   SmallVector<int, 8> MaskVec;
6235   for (unsigned i = 0; i != NumElems; i += Scale) {
6236     int StartIdx = -1;
6237     for (unsigned j = 0; j != Scale; ++j) {
6238       int EltIdx = SVOp->getMaskElt(i+j);
6239       if (EltIdx < 0)
6240         continue;
6241       if (StartIdx < 0)
6242         StartIdx = (EltIdx / Scale);
6243       if (EltIdx != (int)(StartIdx*Scale + j))
6244         return SDValue();
6245     }
6246     MaskVec.push_back(StartIdx);
6247   }
6248
6249   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6250   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6251   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6252 }
6253
6254 /// getVZextMovL - Return a zero-extending vector move low node.
6255 ///
6256 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6257                             SDValue SrcOp, SelectionDAG &DAG,
6258                             const X86Subtarget *Subtarget, DebugLoc dl) {
6259   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6260     LoadSDNode *LD = NULL;
6261     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6262       LD = dyn_cast<LoadSDNode>(SrcOp);
6263     if (!LD) {
6264       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6265       // instead.
6266       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6267       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6268           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6269           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6270           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6271         // PR2108
6272         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6273         return DAG.getNode(ISD::BITCAST, dl, VT,
6274                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6275                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6276                                                    OpVT,
6277                                                    SrcOp.getOperand(0)
6278                                                           .getOperand(0))));
6279       }
6280     }
6281   }
6282
6283   return DAG.getNode(ISD::BITCAST, dl, VT,
6284                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6285                                  DAG.getNode(ISD::BITCAST, dl,
6286                                              OpVT, SrcOp)));
6287 }
6288
6289 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6290 /// which could not be matched by any known target speficic shuffle
6291 static SDValue
6292 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6293
6294   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6295   if (NewOp.getNode())
6296     return NewOp;
6297
6298   MVT VT = SVOp->getValueType(0).getSimpleVT();
6299
6300   unsigned NumElems = VT.getVectorNumElements();
6301   unsigned NumLaneElems = NumElems / 2;
6302
6303   DebugLoc dl = SVOp->getDebugLoc();
6304   MVT EltVT = VT.getVectorElementType();
6305   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6306   SDValue Output[2];
6307
6308   SmallVector<int, 16> Mask;
6309   for (unsigned l = 0; l < 2; ++l) {
6310     // Build a shuffle mask for the output, discovering on the fly which
6311     // input vectors to use as shuffle operands (recorded in InputUsed).
6312     // If building a suitable shuffle vector proves too hard, then bail
6313     // out with UseBuildVector set.
6314     bool UseBuildVector = false;
6315     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6316     unsigned LaneStart = l * NumLaneElems;
6317     for (unsigned i = 0; i != NumLaneElems; ++i) {
6318       // The mask element.  This indexes into the input.
6319       int Idx = SVOp->getMaskElt(i+LaneStart);
6320       if (Idx < 0) {
6321         // the mask element does not index into any input vector.
6322         Mask.push_back(-1);
6323         continue;
6324       }
6325
6326       // The input vector this mask element indexes into.
6327       int Input = Idx / NumLaneElems;
6328
6329       // Turn the index into an offset from the start of the input vector.
6330       Idx -= Input * NumLaneElems;
6331
6332       // Find or create a shuffle vector operand to hold this input.
6333       unsigned OpNo;
6334       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6335         if (InputUsed[OpNo] == Input)
6336           // This input vector is already an operand.
6337           break;
6338         if (InputUsed[OpNo] < 0) {
6339           // Create a new operand for this input vector.
6340           InputUsed[OpNo] = Input;
6341           break;
6342         }
6343       }
6344
6345       if (OpNo >= array_lengthof(InputUsed)) {
6346         // More than two input vectors used!  Give up on trying to create a
6347         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6348         UseBuildVector = true;
6349         break;
6350       }
6351
6352       // Add the mask index for the new shuffle vector.
6353       Mask.push_back(Idx + OpNo * NumLaneElems);
6354     }
6355
6356     if (UseBuildVector) {
6357       SmallVector<SDValue, 16> SVOps;
6358       for (unsigned i = 0; i != NumLaneElems; ++i) {
6359         // The mask element.  This indexes into the input.
6360         int Idx = SVOp->getMaskElt(i+LaneStart);
6361         if (Idx < 0) {
6362           SVOps.push_back(DAG.getUNDEF(EltVT));
6363           continue;
6364         }
6365
6366         // The input vector this mask element indexes into.
6367         int Input = Idx / NumElems;
6368
6369         // Turn the index into an offset from the start of the input vector.
6370         Idx -= Input * NumElems;
6371
6372         // Extract the vector element by hand.
6373         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6374                                     SVOp->getOperand(Input),
6375                                     DAG.getIntPtrConstant(Idx)));
6376       }
6377
6378       // Construct the output using a BUILD_VECTOR.
6379       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6380                               SVOps.size());
6381     } else if (InputUsed[0] < 0) {
6382       // No input vectors were used! The result is undefined.
6383       Output[l] = DAG.getUNDEF(NVT);
6384     } else {
6385       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6386                                         (InputUsed[0] % 2) * NumLaneElems,
6387                                         DAG, dl);
6388       // If only one input was used, use an undefined vector for the other.
6389       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6390         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6391                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6392       // At least one input vector was used. Create a new shuffle vector.
6393       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6394     }
6395
6396     Mask.clear();
6397   }
6398
6399   // Concatenate the result back
6400   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6401 }
6402
6403 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6404 /// 4 elements, and match them with several different shuffle types.
6405 static SDValue
6406 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6407   SDValue V1 = SVOp->getOperand(0);
6408   SDValue V2 = SVOp->getOperand(1);
6409   DebugLoc dl = SVOp->getDebugLoc();
6410   MVT VT = SVOp->getValueType(0).getSimpleVT();
6411
6412   assert(VT.is128BitVector() && "Unsupported vector size");
6413
6414   std::pair<int, int> Locs[4];
6415   int Mask1[] = { -1, -1, -1, -1 };
6416   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6417
6418   unsigned NumHi = 0;
6419   unsigned NumLo = 0;
6420   for (unsigned i = 0; i != 4; ++i) {
6421     int Idx = PermMask[i];
6422     if (Idx < 0) {
6423       Locs[i] = std::make_pair(-1, -1);
6424     } else {
6425       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6426       if (Idx < 4) {
6427         Locs[i] = std::make_pair(0, NumLo);
6428         Mask1[NumLo] = Idx;
6429         NumLo++;
6430       } else {
6431         Locs[i] = std::make_pair(1, NumHi);
6432         if (2+NumHi < 4)
6433           Mask1[2+NumHi] = Idx;
6434         NumHi++;
6435       }
6436     }
6437   }
6438
6439   if (NumLo <= 2 && NumHi <= 2) {
6440     // If no more than two elements come from either vector. This can be
6441     // implemented with two shuffles. First shuffle gather the elements.
6442     // The second shuffle, which takes the first shuffle as both of its
6443     // vector operands, put the elements into the right order.
6444     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6445
6446     int Mask2[] = { -1, -1, -1, -1 };
6447
6448     for (unsigned i = 0; i != 4; ++i)
6449       if (Locs[i].first != -1) {
6450         unsigned Idx = (i < 2) ? 0 : 4;
6451         Idx += Locs[i].first * 2 + Locs[i].second;
6452         Mask2[i] = Idx;
6453       }
6454
6455     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6456   }
6457
6458   if (NumLo == 3 || NumHi == 3) {
6459     // Otherwise, we must have three elements from one vector, call it X, and
6460     // one element from the other, call it Y.  First, use a shufps to build an
6461     // intermediate vector with the one element from Y and the element from X
6462     // that will be in the same half in the final destination (the indexes don't
6463     // matter). Then, use a shufps to build the final vector, taking the half
6464     // containing the element from Y from the intermediate, and the other half
6465     // from X.
6466     if (NumHi == 3) {
6467       // Normalize it so the 3 elements come from V1.
6468       CommuteVectorShuffleMask(PermMask, 4);
6469       std::swap(V1, V2);
6470     }
6471
6472     // Find the element from V2.
6473     unsigned HiIndex;
6474     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6475       int Val = PermMask[HiIndex];
6476       if (Val < 0)
6477         continue;
6478       if (Val >= 4)
6479         break;
6480     }
6481
6482     Mask1[0] = PermMask[HiIndex];
6483     Mask1[1] = -1;
6484     Mask1[2] = PermMask[HiIndex^1];
6485     Mask1[3] = -1;
6486     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6487
6488     if (HiIndex >= 2) {
6489       Mask1[0] = PermMask[0];
6490       Mask1[1] = PermMask[1];
6491       Mask1[2] = HiIndex & 1 ? 6 : 4;
6492       Mask1[3] = HiIndex & 1 ? 4 : 6;
6493       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6494     }
6495
6496     Mask1[0] = HiIndex & 1 ? 2 : 0;
6497     Mask1[1] = HiIndex & 1 ? 0 : 2;
6498     Mask1[2] = PermMask[2];
6499     Mask1[3] = PermMask[3];
6500     if (Mask1[2] >= 0)
6501       Mask1[2] += 4;
6502     if (Mask1[3] >= 0)
6503       Mask1[3] += 4;
6504     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6505   }
6506
6507   // Break it into (shuffle shuffle_hi, shuffle_lo).
6508   int LoMask[] = { -1, -1, -1, -1 };
6509   int HiMask[] = { -1, -1, -1, -1 };
6510
6511   int *MaskPtr = LoMask;
6512   unsigned MaskIdx = 0;
6513   unsigned LoIdx = 0;
6514   unsigned HiIdx = 2;
6515   for (unsigned i = 0; i != 4; ++i) {
6516     if (i == 2) {
6517       MaskPtr = HiMask;
6518       MaskIdx = 1;
6519       LoIdx = 0;
6520       HiIdx = 2;
6521     }
6522     int Idx = PermMask[i];
6523     if (Idx < 0) {
6524       Locs[i] = std::make_pair(-1, -1);
6525     } else if (Idx < 4) {
6526       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6527       MaskPtr[LoIdx] = Idx;
6528       LoIdx++;
6529     } else {
6530       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6531       MaskPtr[HiIdx] = Idx;
6532       HiIdx++;
6533     }
6534   }
6535
6536   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6537   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6538   int MaskOps[] = { -1, -1, -1, -1 };
6539   for (unsigned i = 0; i != 4; ++i)
6540     if (Locs[i].first != -1)
6541       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6542   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6543 }
6544
6545 static bool MayFoldVectorLoad(SDValue V) {
6546   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6547     V = V.getOperand(0);
6548
6549   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6550     V = V.getOperand(0);
6551   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6552       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6553     // BUILD_VECTOR (load), undef
6554     V = V.getOperand(0);
6555
6556   return MayFoldLoad(V);
6557 }
6558
6559 static
6560 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6561   EVT VT = Op.getValueType();
6562
6563   // Canonizalize to v2f64.
6564   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6565   return DAG.getNode(ISD::BITCAST, dl, VT,
6566                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6567                                           V1, DAG));
6568 }
6569
6570 static
6571 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6572                         bool HasSSE2) {
6573   SDValue V1 = Op.getOperand(0);
6574   SDValue V2 = Op.getOperand(1);
6575   EVT VT = Op.getValueType();
6576
6577   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6578
6579   if (HasSSE2 && VT == MVT::v2f64)
6580     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6581
6582   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6583   return DAG.getNode(ISD::BITCAST, dl, VT,
6584                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6585                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6586                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6587 }
6588
6589 static
6590 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6591   SDValue V1 = Op.getOperand(0);
6592   SDValue V2 = Op.getOperand(1);
6593   EVT VT = Op.getValueType();
6594
6595   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6596          "unsupported shuffle type");
6597
6598   if (V2.getOpcode() == ISD::UNDEF)
6599     V2 = V1;
6600
6601   // v4i32 or v4f32
6602   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6603 }
6604
6605 static
6606 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6607   SDValue V1 = Op.getOperand(0);
6608   SDValue V2 = Op.getOperand(1);
6609   EVT VT = Op.getValueType();
6610   unsigned NumElems = VT.getVectorNumElements();
6611
6612   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6613   // operand of these instructions is only memory, so check if there's a
6614   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6615   // same masks.
6616   bool CanFoldLoad = false;
6617
6618   // Trivial case, when V2 comes from a load.
6619   if (MayFoldVectorLoad(V2))
6620     CanFoldLoad = true;
6621
6622   // When V1 is a load, it can be folded later into a store in isel, example:
6623   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6624   //    turns into:
6625   //  (MOVLPSmr addr:$src1, VR128:$src2)
6626   // So, recognize this potential and also use MOVLPS or MOVLPD
6627   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6628     CanFoldLoad = true;
6629
6630   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6631   if (CanFoldLoad) {
6632     if (HasSSE2 && NumElems == 2)
6633       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6634
6635     if (NumElems == 4)
6636       // If we don't care about the second element, proceed to use movss.
6637       if (SVOp->getMaskElt(1) != -1)
6638         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6639   }
6640
6641   // movl and movlp will both match v2i64, but v2i64 is never matched by
6642   // movl earlier because we make it strict to avoid messing with the movlp load
6643   // folding logic (see the code above getMOVLP call). Match it here then,
6644   // this is horrible, but will stay like this until we move all shuffle
6645   // matching to x86 specific nodes. Note that for the 1st condition all
6646   // types are matched with movsd.
6647   if (HasSSE2) {
6648     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6649     // as to remove this logic from here, as much as possible
6650     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6651       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6652     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6653   }
6654
6655   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6656
6657   // Invert the operand order and use SHUFPS to match it.
6658   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6659                               getShuffleSHUFImmediate(SVOp), DAG);
6660 }
6661
6662 // Reduce a vector shuffle to zext.
6663 SDValue
6664 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6665   // PMOVZX is only available from SSE41.
6666   if (!Subtarget->hasSSE41())
6667     return SDValue();
6668
6669   EVT VT = Op.getValueType();
6670
6671   // Only AVX2 support 256-bit vector integer extending.
6672   if (!Subtarget->hasInt256() && VT.is256BitVector())
6673     return SDValue();
6674
6675   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6676   DebugLoc DL = Op.getDebugLoc();
6677   SDValue V1 = Op.getOperand(0);
6678   SDValue V2 = Op.getOperand(1);
6679   unsigned NumElems = VT.getVectorNumElements();
6680
6681   // Extending is an unary operation and the element type of the source vector
6682   // won't be equal to or larger than i64.
6683   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6684       VT.getVectorElementType() == MVT::i64)
6685     return SDValue();
6686
6687   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6688   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6689   while ((1U << Shift) < NumElems) {
6690     if (SVOp->getMaskElt(1U << Shift) == 1)
6691       break;
6692     Shift += 1;
6693     // The maximal ratio is 8, i.e. from i8 to i64.
6694     if (Shift > 3)
6695       return SDValue();
6696   }
6697
6698   // Check the shuffle mask.
6699   unsigned Mask = (1U << Shift) - 1;
6700   for (unsigned i = 0; i != NumElems; ++i) {
6701     int EltIdx = SVOp->getMaskElt(i);
6702     if ((i & Mask) != 0 && EltIdx != -1)
6703       return SDValue();
6704     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6705       return SDValue();
6706   }
6707
6708   LLVMContext *Context = DAG.getContext();
6709   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6710   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6711   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6712
6713   if (!isTypeLegal(NVT))
6714     return SDValue();
6715
6716   // Simplify the operand as it's prepared to be fed into shuffle.
6717   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6718   if (V1.getOpcode() == ISD::BITCAST &&
6719       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6720       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6721       V1.getOperand(0)
6722         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6723     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6724     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6725     ConstantSDNode *CIdx =
6726       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6727     // If it's foldable, i.e. normal load with single use, we will let code
6728     // selection to fold it. Otherwise, we will short the conversion sequence.
6729     if (CIdx && CIdx->getZExtValue() == 0 &&
6730         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6731       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6732         // The "ext_vec_elt" node is wider than the result node.
6733         // In this case we should extract subvector from V.
6734         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6735         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6736         EVT FullVT = V.getValueType();
6737         EVT SubVecVT = EVT::getVectorVT(*Context,
6738                                         FullVT.getVectorElementType(),
6739                                         FullVT.getVectorNumElements()/Ratio);
6740         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6741                         DAG.getIntPtrConstant(0));
6742       }
6743       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6744     }
6745   }
6746
6747   return DAG.getNode(ISD::BITCAST, DL, VT,
6748                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6749 }
6750
6751 SDValue
6752 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6753   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6754   MVT VT = Op.getValueType().getSimpleVT();
6755   DebugLoc dl = Op.getDebugLoc();
6756   SDValue V1 = Op.getOperand(0);
6757   SDValue V2 = Op.getOperand(1);
6758
6759   if (isZeroShuffle(SVOp))
6760     return getZeroVector(VT, Subtarget, DAG, dl);
6761
6762   // Handle splat operations
6763   if (SVOp->isSplat()) {
6764     // Use vbroadcast whenever the splat comes from a foldable load
6765     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6766     if (Broadcast.getNode())
6767       return Broadcast;
6768   }
6769
6770   // Check integer expanding shuffles.
6771   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6772   if (NewOp.getNode())
6773     return NewOp;
6774
6775   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6776   // do it!
6777   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6778       VT == MVT::v16i16 || VT == MVT::v32i8) {
6779     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6780     if (NewOp.getNode())
6781       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6782   } else if ((VT == MVT::v4i32 ||
6783              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6784     // FIXME: Figure out a cleaner way to do this.
6785     // Try to make use of movq to zero out the top part.
6786     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6787       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6788       if (NewOp.getNode()) {
6789         MVT NewVT = NewOp.getValueType().getSimpleVT();
6790         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6791                                NewVT, true, false))
6792           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6793                               DAG, Subtarget, dl);
6794       }
6795     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6796       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6797       if (NewOp.getNode()) {
6798         MVT NewVT = NewOp.getValueType().getSimpleVT();
6799         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6800           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6801                               DAG, Subtarget, dl);
6802       }
6803     }
6804   }
6805   return SDValue();
6806 }
6807
6808 SDValue
6809 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6810   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6811   SDValue V1 = Op.getOperand(0);
6812   SDValue V2 = Op.getOperand(1);
6813   MVT VT = Op.getValueType().getSimpleVT();
6814   DebugLoc dl = Op.getDebugLoc();
6815   unsigned NumElems = VT.getVectorNumElements();
6816   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6817   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6818   bool V1IsSplat = false;
6819   bool V2IsSplat = false;
6820   bool HasSSE2 = Subtarget->hasSSE2();
6821   bool HasFp256    = Subtarget->hasFp256();
6822   bool HasInt256   = Subtarget->hasInt256();
6823   MachineFunction &MF = DAG.getMachineFunction();
6824   bool OptForSize = MF.getFunction()->getAttributes().
6825     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6826
6827   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6828
6829   if (V1IsUndef && V2IsUndef)
6830     return DAG.getUNDEF(VT);
6831
6832   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6833
6834   // Vector shuffle lowering takes 3 steps:
6835   //
6836   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6837   //    narrowing and commutation of operands should be handled.
6838   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6839   //    shuffle nodes.
6840   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6841   //    so the shuffle can be broken into other shuffles and the legalizer can
6842   //    try the lowering again.
6843   //
6844   // The general idea is that no vector_shuffle operation should be left to
6845   // be matched during isel, all of them must be converted to a target specific
6846   // node here.
6847
6848   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6849   // narrowing and commutation of operands should be handled. The actual code
6850   // doesn't include all of those, work in progress...
6851   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6852   if (NewOp.getNode())
6853     return NewOp;
6854
6855   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6856
6857   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6858   // unpckh_undef). Only use pshufd if speed is more important than size.
6859   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6860     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6861   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6862     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6863
6864   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6865       V2IsUndef && MayFoldVectorLoad(V1))
6866     return getMOVDDup(Op, dl, V1, DAG);
6867
6868   if (isMOVHLPS_v_undef_Mask(M, VT))
6869     return getMOVHighToLow(Op, dl, DAG);
6870
6871   // Use to match splats
6872   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6873       (VT == MVT::v2f64 || VT == MVT::v2i64))
6874     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6875
6876   if (isPSHUFDMask(M, VT)) {
6877     // The actual implementation will match the mask in the if above and then
6878     // during isel it can match several different instructions, not only pshufd
6879     // as its name says, sad but true, emulate the behavior for now...
6880     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6881       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6882
6883     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6884
6885     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6886       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6887
6888     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6889       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6890                                   DAG);
6891
6892     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6893                                 TargetMask, DAG);
6894   }
6895
6896   if (isPALIGNRMask(M, VT, Subtarget))
6897     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6898                                 getShufflePALIGNRImmediate(SVOp),
6899                                 DAG);
6900
6901   // Check if this can be converted into a logical shift.
6902   bool isLeft = false;
6903   unsigned ShAmt = 0;
6904   SDValue ShVal;
6905   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6906   if (isShift && ShVal.hasOneUse()) {
6907     // If the shifted value has multiple uses, it may be cheaper to use
6908     // v_set0 + movlhps or movhlps, etc.
6909     MVT EltVT = VT.getVectorElementType();
6910     ShAmt *= EltVT.getSizeInBits();
6911     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6912   }
6913
6914   if (isMOVLMask(M, VT)) {
6915     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6916       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6917     if (!isMOVLPMask(M, VT)) {
6918       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6919         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6920
6921       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6922         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6923     }
6924   }
6925
6926   // FIXME: fold these into legal mask.
6927   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6928     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6929
6930   if (isMOVHLPSMask(M, VT))
6931     return getMOVHighToLow(Op, dl, DAG);
6932
6933   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6934     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6935
6936   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6937     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6938
6939   if (isMOVLPMask(M, VT))
6940     return getMOVLP(Op, dl, DAG, HasSSE2);
6941
6942   if (ShouldXformToMOVHLPS(M, VT) ||
6943       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6944     return CommuteVectorShuffle(SVOp, DAG);
6945
6946   if (isShift) {
6947     // No better options. Use a vshldq / vsrldq.
6948     MVT EltVT = VT.getVectorElementType();
6949     ShAmt *= EltVT.getSizeInBits();
6950     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6951   }
6952
6953   bool Commuted = false;
6954   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6955   // 1,1,1,1 -> v8i16 though.
6956   V1IsSplat = isSplatVector(V1.getNode());
6957   V2IsSplat = isSplatVector(V2.getNode());
6958
6959   // Canonicalize the splat or undef, if present, to be on the RHS.
6960   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6961     CommuteVectorShuffleMask(M, NumElems);
6962     std::swap(V1, V2);
6963     std::swap(V1IsSplat, V2IsSplat);
6964     Commuted = true;
6965   }
6966
6967   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6968     // Shuffling low element of v1 into undef, just return v1.
6969     if (V2IsUndef)
6970       return V1;
6971     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6972     // the instruction selector will not match, so get a canonical MOVL with
6973     // swapped operands to undo the commute.
6974     return getMOVL(DAG, dl, VT, V2, V1);
6975   }
6976
6977   if (isUNPCKLMask(M, VT, HasInt256))
6978     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6979
6980   if (isUNPCKHMask(M, VT, HasInt256))
6981     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6982
6983   if (V2IsSplat) {
6984     // Normalize mask so all entries that point to V2 points to its first
6985     // element then try to match unpck{h|l} again. If match, return a
6986     // new vector_shuffle with the corrected mask.p
6987     SmallVector<int, 8> NewMask(M.begin(), M.end());
6988     NormalizeMask(NewMask, NumElems);
6989     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6990       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6991     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6992       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6993   }
6994
6995   if (Commuted) {
6996     // Commute is back and try unpck* again.
6997     // FIXME: this seems wrong.
6998     CommuteVectorShuffleMask(M, NumElems);
6999     std::swap(V1, V2);
7000     std::swap(V1IsSplat, V2IsSplat);
7001     Commuted = false;
7002
7003     if (isUNPCKLMask(M, VT, HasInt256))
7004       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7005
7006     if (isUNPCKHMask(M, VT, HasInt256))
7007       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7008   }
7009
7010   // Normalize the node to match x86 shuffle ops if needed
7011   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7012     return CommuteVectorShuffle(SVOp, DAG);
7013
7014   // The checks below are all present in isShuffleMaskLegal, but they are
7015   // inlined here right now to enable us to directly emit target specific
7016   // nodes, and remove one by one until they don't return Op anymore.
7017
7018   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7019       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7020     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7021       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7022   }
7023
7024   if (isPSHUFHWMask(M, VT, HasInt256))
7025     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7026                                 getShufflePSHUFHWImmediate(SVOp),
7027                                 DAG);
7028
7029   if (isPSHUFLWMask(M, VT, HasInt256))
7030     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7031                                 getShufflePSHUFLWImmediate(SVOp),
7032                                 DAG);
7033
7034   if (isSHUFPMask(M, VT, HasFp256))
7035     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7036                                 getShuffleSHUFImmediate(SVOp), DAG);
7037
7038   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7039     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7040   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7041     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7042
7043   //===--------------------------------------------------------------------===//
7044   // Generate target specific nodes for 128 or 256-bit shuffles only
7045   // supported in the AVX instruction set.
7046   //
7047
7048   // Handle VMOVDDUPY permutations
7049   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7050     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7051
7052   // Handle VPERMILPS/D* permutations
7053   if (isVPERMILPMask(M, VT, HasFp256)) {
7054     if (HasInt256 && VT == MVT::v8i32)
7055       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7056                                   getShuffleSHUFImmediate(SVOp), DAG);
7057     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7058                                 getShuffleSHUFImmediate(SVOp), DAG);
7059   }
7060
7061   // Handle VPERM2F128/VPERM2I128 permutations
7062   if (isVPERM2X128Mask(M, VT, HasFp256))
7063     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7064                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7065
7066   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7067   if (BlendOp.getNode())
7068     return BlendOp;
7069
7070   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7071     SmallVector<SDValue, 8> permclMask;
7072     for (unsigned i = 0; i != 8; ++i) {
7073       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7074     }
7075     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7076                                &permclMask[0], 8);
7077     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7078     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7079                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7080   }
7081
7082   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7083     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7084                                 getShuffleCLImmediate(SVOp), DAG);
7085
7086   //===--------------------------------------------------------------------===//
7087   // Since no target specific shuffle was selected for this generic one,
7088   // lower it into other known shuffles. FIXME: this isn't true yet, but
7089   // this is the plan.
7090   //
7091
7092   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7093   if (VT == MVT::v8i16) {
7094     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7095     if (NewOp.getNode())
7096       return NewOp;
7097   }
7098
7099   if (VT == MVT::v16i8) {
7100     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7101     if (NewOp.getNode())
7102       return NewOp;
7103   }
7104
7105   if (VT == MVT::v32i8) {
7106     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7107     if (NewOp.getNode())
7108       return NewOp;
7109   }
7110
7111   // Handle all 128-bit wide vectors with 4 elements, and match them with
7112   // several different shuffle types.
7113   if (NumElems == 4 && VT.is128BitVector())
7114     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7115
7116   // Handle general 256-bit shuffles
7117   if (VT.is256BitVector())
7118     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7119
7120   return SDValue();
7121 }
7122
7123 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7124   MVT VT = Op.getValueType().getSimpleVT();
7125   DebugLoc dl = Op.getDebugLoc();
7126
7127   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7128     return SDValue();
7129
7130   if (VT.getSizeInBits() == 8) {
7131     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7132                                   Op.getOperand(0), Op.getOperand(1));
7133     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7134                                   DAG.getValueType(VT));
7135     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7136   }
7137
7138   if (VT.getSizeInBits() == 16) {
7139     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7140     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7141     if (Idx == 0)
7142       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7143                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7144                                      DAG.getNode(ISD::BITCAST, dl,
7145                                                  MVT::v4i32,
7146                                                  Op.getOperand(0)),
7147                                      Op.getOperand(1)));
7148     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7149                                   Op.getOperand(0), Op.getOperand(1));
7150     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7151                                   DAG.getValueType(VT));
7152     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7153   }
7154
7155   if (VT == MVT::f32) {
7156     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7157     // the result back to FR32 register. It's only worth matching if the
7158     // result has a single use which is a store or a bitcast to i32.  And in
7159     // the case of a store, it's not worth it if the index is a constant 0,
7160     // because a MOVSSmr can be used instead, which is smaller and faster.
7161     if (!Op.hasOneUse())
7162       return SDValue();
7163     SDNode *User = *Op.getNode()->use_begin();
7164     if ((User->getOpcode() != ISD::STORE ||
7165          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7166           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7167         (User->getOpcode() != ISD::BITCAST ||
7168          User->getValueType(0) != MVT::i32))
7169       return SDValue();
7170     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7171                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7172                                               Op.getOperand(0)),
7173                                               Op.getOperand(1));
7174     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7175   }
7176
7177   if (VT == MVT::i32 || VT == MVT::i64) {
7178     // ExtractPS/pextrq works with constant index.
7179     if (isa<ConstantSDNode>(Op.getOperand(1)))
7180       return Op;
7181   }
7182   return SDValue();
7183 }
7184
7185 SDValue
7186 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7187                                            SelectionDAG &DAG) const {
7188   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7189     return SDValue();
7190
7191   SDValue Vec = Op.getOperand(0);
7192   MVT VecVT = Vec.getValueType().getSimpleVT();
7193
7194   // If this is a 256-bit vector result, first extract the 128-bit vector and
7195   // then extract the element from the 128-bit vector.
7196   if (VecVT.is256BitVector()) {
7197     DebugLoc dl = Op.getNode()->getDebugLoc();
7198     unsigned NumElems = VecVT.getVectorNumElements();
7199     SDValue Idx = Op.getOperand(1);
7200     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7201
7202     // Get the 128-bit vector.
7203     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7204
7205     if (IdxVal >= NumElems/2)
7206       IdxVal -= NumElems/2;
7207     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7208                        DAG.getConstant(IdxVal, MVT::i32));
7209   }
7210
7211   assert(VecVT.is128BitVector() && "Unexpected vector length");
7212
7213   if (Subtarget->hasSSE41()) {
7214     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7215     if (Res.getNode())
7216       return Res;
7217   }
7218
7219   MVT VT = Op.getValueType().getSimpleVT();
7220   DebugLoc dl = Op.getDebugLoc();
7221   // TODO: handle v16i8.
7222   if (VT.getSizeInBits() == 16) {
7223     SDValue Vec = Op.getOperand(0);
7224     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7225     if (Idx == 0)
7226       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7227                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7228                                      DAG.getNode(ISD::BITCAST, dl,
7229                                                  MVT::v4i32, Vec),
7230                                      Op.getOperand(1)));
7231     // Transform it so it match pextrw which produces a 32-bit result.
7232     MVT EltVT = MVT::i32;
7233     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7234                                   Op.getOperand(0), Op.getOperand(1));
7235     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7236                                   DAG.getValueType(VT));
7237     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7238   }
7239
7240   if (VT.getSizeInBits() == 32) {
7241     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7242     if (Idx == 0)
7243       return Op;
7244
7245     // SHUFPS the element to the lowest double word, then movss.
7246     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7247     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7248     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7249                                        DAG.getUNDEF(VVT), Mask);
7250     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7251                        DAG.getIntPtrConstant(0));
7252   }
7253
7254   if (VT.getSizeInBits() == 64) {
7255     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7256     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7257     //        to match extract_elt for f64.
7258     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7259     if (Idx == 0)
7260       return Op;
7261
7262     // UNPCKHPD the element to the lowest double word, then movsd.
7263     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7264     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7265     int Mask[2] = { 1, -1 };
7266     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7267     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7268                                        DAG.getUNDEF(VVT), Mask);
7269     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7270                        DAG.getIntPtrConstant(0));
7271   }
7272
7273   return SDValue();
7274 }
7275
7276 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7277   MVT VT = Op.getValueType().getSimpleVT();
7278   MVT EltVT = VT.getVectorElementType();
7279   DebugLoc dl = Op.getDebugLoc();
7280
7281   SDValue N0 = Op.getOperand(0);
7282   SDValue N1 = Op.getOperand(1);
7283   SDValue N2 = Op.getOperand(2);
7284
7285   if (!VT.is128BitVector())
7286     return SDValue();
7287
7288   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7289       isa<ConstantSDNode>(N2)) {
7290     unsigned Opc;
7291     if (VT == MVT::v8i16)
7292       Opc = X86ISD::PINSRW;
7293     else if (VT == MVT::v16i8)
7294       Opc = X86ISD::PINSRB;
7295     else
7296       Opc = X86ISD::PINSRB;
7297
7298     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7299     // argument.
7300     if (N1.getValueType() != MVT::i32)
7301       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7302     if (N2.getValueType() != MVT::i32)
7303       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7304     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7305   }
7306
7307   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7308     // Bits [7:6] of the constant are the source select.  This will always be
7309     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7310     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7311     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7312     // Bits [5:4] of the constant are the destination select.  This is the
7313     //  value of the incoming immediate.
7314     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7315     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7316     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7317     // Create this as a scalar to vector..
7318     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7319     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7320   }
7321
7322   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7323     // PINSR* works with constant index.
7324     return Op;
7325   }
7326   return SDValue();
7327 }
7328
7329 SDValue
7330 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7331   MVT VT = Op.getValueType().getSimpleVT();
7332   MVT EltVT = VT.getVectorElementType();
7333
7334   DebugLoc dl = Op.getDebugLoc();
7335   SDValue N0 = Op.getOperand(0);
7336   SDValue N1 = Op.getOperand(1);
7337   SDValue N2 = Op.getOperand(2);
7338
7339   // If this is a 256-bit vector result, first extract the 128-bit vector,
7340   // insert the element into the extracted half and then place it back.
7341   if (VT.is256BitVector()) {
7342     if (!isa<ConstantSDNode>(N2))
7343       return SDValue();
7344
7345     // Get the desired 128-bit vector half.
7346     unsigned NumElems = VT.getVectorNumElements();
7347     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7348     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7349
7350     // Insert the element into the desired half.
7351     bool Upper = IdxVal >= NumElems/2;
7352     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7353                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7354
7355     // Insert the changed part back to the 256-bit vector
7356     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7357   }
7358
7359   if (Subtarget->hasSSE41())
7360     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7361
7362   if (EltVT == MVT::i8)
7363     return SDValue();
7364
7365   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7366     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7367     // as its second argument.
7368     if (N1.getValueType() != MVT::i32)
7369       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7370     if (N2.getValueType() != MVT::i32)
7371       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7372     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7373   }
7374   return SDValue();
7375 }
7376
7377 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7378   LLVMContext *Context = DAG.getContext();
7379   DebugLoc dl = Op.getDebugLoc();
7380   MVT OpVT = Op.getValueType().getSimpleVT();
7381
7382   // If this is a 256-bit vector result, first insert into a 128-bit
7383   // vector and then insert into the 256-bit vector.
7384   if (!OpVT.is128BitVector()) {
7385     // Insert into a 128-bit vector.
7386     EVT VT128 = EVT::getVectorVT(*Context,
7387                                  OpVT.getVectorElementType(),
7388                                  OpVT.getVectorNumElements() / 2);
7389
7390     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7391
7392     // Insert the 128-bit vector.
7393     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7394   }
7395
7396   if (OpVT == MVT::v1i64 &&
7397       Op.getOperand(0).getValueType() == MVT::i64)
7398     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7399
7400   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7401   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7402   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7403                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7404 }
7405
7406 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7407 // a simple subregister reference or explicit instructions to grab
7408 // upper bits of a vector.
7409 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7410                                       SelectionDAG &DAG) {
7411   if (Subtarget->hasFp256()) {
7412     DebugLoc dl = Op.getNode()->getDebugLoc();
7413     SDValue Vec = Op.getNode()->getOperand(0);
7414     SDValue Idx = Op.getNode()->getOperand(1);
7415
7416     if (Op.getNode()->getValueType(0).is128BitVector() &&
7417         Vec.getNode()->getValueType(0).is256BitVector() &&
7418         isa<ConstantSDNode>(Idx)) {
7419       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7420       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7421     }
7422   }
7423   return SDValue();
7424 }
7425
7426 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7427 // simple superregister reference or explicit instructions to insert
7428 // the upper bits of a vector.
7429 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7430                                      SelectionDAG &DAG) {
7431   if (Subtarget->hasFp256()) {
7432     DebugLoc dl = Op.getNode()->getDebugLoc();
7433     SDValue Vec = Op.getNode()->getOperand(0);
7434     SDValue SubVec = Op.getNode()->getOperand(1);
7435     SDValue Idx = Op.getNode()->getOperand(2);
7436
7437     if (Op.getNode()->getValueType(0).is256BitVector() &&
7438         SubVec.getNode()->getValueType(0).is128BitVector() &&
7439         isa<ConstantSDNode>(Idx)) {
7440       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7441       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7442     }
7443   }
7444   return SDValue();
7445 }
7446
7447 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7448 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7449 // one of the above mentioned nodes. It has to be wrapped because otherwise
7450 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7451 // be used to form addressing mode. These wrapped nodes will be selected
7452 // into MOV32ri.
7453 SDValue
7454 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7455   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7456
7457   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7458   // global base reg.
7459   unsigned char OpFlag = 0;
7460   unsigned WrapperKind = X86ISD::Wrapper;
7461   CodeModel::Model M = getTargetMachine().getCodeModel();
7462
7463   if (Subtarget->isPICStyleRIPRel() &&
7464       (M == CodeModel::Small || M == CodeModel::Kernel))
7465     WrapperKind = X86ISD::WrapperRIP;
7466   else if (Subtarget->isPICStyleGOT())
7467     OpFlag = X86II::MO_GOTOFF;
7468   else if (Subtarget->isPICStyleStubPIC())
7469     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7470
7471   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7472                                              CP->getAlignment(),
7473                                              CP->getOffset(), OpFlag);
7474   DebugLoc DL = CP->getDebugLoc();
7475   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7476   // With PIC, the address is actually $g + Offset.
7477   if (OpFlag) {
7478     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7479                          DAG.getNode(X86ISD::GlobalBaseReg,
7480                                      DebugLoc(), getPointerTy()),
7481                          Result);
7482   }
7483
7484   return Result;
7485 }
7486
7487 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7488   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7489
7490   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7491   // global base reg.
7492   unsigned char OpFlag = 0;
7493   unsigned WrapperKind = X86ISD::Wrapper;
7494   CodeModel::Model M = getTargetMachine().getCodeModel();
7495
7496   if (Subtarget->isPICStyleRIPRel() &&
7497       (M == CodeModel::Small || M == CodeModel::Kernel))
7498     WrapperKind = X86ISD::WrapperRIP;
7499   else if (Subtarget->isPICStyleGOT())
7500     OpFlag = X86II::MO_GOTOFF;
7501   else if (Subtarget->isPICStyleStubPIC())
7502     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7503
7504   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7505                                           OpFlag);
7506   DebugLoc DL = JT->getDebugLoc();
7507   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7508
7509   // With PIC, the address is actually $g + Offset.
7510   if (OpFlag)
7511     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7512                          DAG.getNode(X86ISD::GlobalBaseReg,
7513                                      DebugLoc(), getPointerTy()),
7514                          Result);
7515
7516   return Result;
7517 }
7518
7519 SDValue
7520 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7521   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7522
7523   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7524   // global base reg.
7525   unsigned char OpFlag = 0;
7526   unsigned WrapperKind = X86ISD::Wrapper;
7527   CodeModel::Model M = getTargetMachine().getCodeModel();
7528
7529   if (Subtarget->isPICStyleRIPRel() &&
7530       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7531     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7532       OpFlag = X86II::MO_GOTPCREL;
7533     WrapperKind = X86ISD::WrapperRIP;
7534   } else if (Subtarget->isPICStyleGOT()) {
7535     OpFlag = X86II::MO_GOT;
7536   } else if (Subtarget->isPICStyleStubPIC()) {
7537     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7538   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7539     OpFlag = X86II::MO_DARWIN_NONLAZY;
7540   }
7541
7542   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7543
7544   DebugLoc DL = Op.getDebugLoc();
7545   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7546
7547   // With PIC, the address is actually $g + Offset.
7548   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7549       !Subtarget->is64Bit()) {
7550     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7551                          DAG.getNode(X86ISD::GlobalBaseReg,
7552                                      DebugLoc(), getPointerTy()),
7553                          Result);
7554   }
7555
7556   // For symbols that require a load from a stub to get the address, emit the
7557   // load.
7558   if (isGlobalStubReference(OpFlag))
7559     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7560                          MachinePointerInfo::getGOT(), false, false, false, 0);
7561
7562   return Result;
7563 }
7564
7565 SDValue
7566 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7567   // Create the TargetBlockAddressAddress node.
7568   unsigned char OpFlags =
7569     Subtarget->ClassifyBlockAddressReference();
7570   CodeModel::Model M = getTargetMachine().getCodeModel();
7571   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7572   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7573   DebugLoc dl = Op.getDebugLoc();
7574   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7575                                              OpFlags);
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   return Result;
7591 }
7592
7593 SDValue
7594 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7595                                       int64_t Offset, SelectionDAG &DAG) const {
7596   // Create the TargetGlobalAddress node, folding in the constant
7597   // offset if it is legal.
7598   unsigned char OpFlags =
7599     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7600   CodeModel::Model M = getTargetMachine().getCodeModel();
7601   SDValue Result;
7602   if (OpFlags == X86II::MO_NO_FLAG &&
7603       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7604     // A direct static reference to a global.
7605     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7606     Offset = 0;
7607   } else {
7608     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7609   }
7610
7611   if (Subtarget->isPICStyleRIPRel() &&
7612       (M == CodeModel::Small || M == CodeModel::Kernel))
7613     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7614   else
7615     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7616
7617   // With PIC, the address is actually $g + Offset.
7618   if (isGlobalRelativeToPICBase(OpFlags)) {
7619     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7620                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7621                          Result);
7622   }
7623
7624   // For globals that require a load from a stub to get the address, emit the
7625   // load.
7626   if (isGlobalStubReference(OpFlags))
7627     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7628                          MachinePointerInfo::getGOT(), false, false, false, 0);
7629
7630   // If there was a non-zero offset that we didn't fold, create an explicit
7631   // addition for it.
7632   if (Offset != 0)
7633     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7634                          DAG.getConstant(Offset, getPointerTy()));
7635
7636   return Result;
7637 }
7638
7639 SDValue
7640 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7641   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7642   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7643   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7644 }
7645
7646 static SDValue
7647 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7648            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7649            unsigned char OperandFlags, bool LocalDynamic = false) {
7650   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7651   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7652   DebugLoc dl = GA->getDebugLoc();
7653   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7654                                            GA->getValueType(0),
7655                                            GA->getOffset(),
7656                                            OperandFlags);
7657
7658   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7659                                            : X86ISD::TLSADDR;
7660
7661   if (InFlag) {
7662     SDValue Ops[] = { Chain,  TGA, *InFlag };
7663     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7664   } else {
7665     SDValue Ops[]  = { Chain, TGA };
7666     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7667   }
7668
7669   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7670   MFI->setAdjustsStack(true);
7671
7672   SDValue Flag = Chain.getValue(1);
7673   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7674 }
7675
7676 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7677 static SDValue
7678 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7679                                 const EVT PtrVT) {
7680   SDValue InFlag;
7681   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7682   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7683                                    DAG.getNode(X86ISD::GlobalBaseReg,
7684                                                DebugLoc(), PtrVT), InFlag);
7685   InFlag = Chain.getValue(1);
7686
7687   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7688 }
7689
7690 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7691 static SDValue
7692 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7693                                 const EVT PtrVT) {
7694   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7695                     X86::RAX, X86II::MO_TLSGD);
7696 }
7697
7698 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7699                                            SelectionDAG &DAG,
7700                                            const EVT PtrVT,
7701                                            bool is64Bit) {
7702   DebugLoc dl = GA->getDebugLoc();
7703
7704   // Get the start address of the TLS block for this module.
7705   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7706       .getInfo<X86MachineFunctionInfo>();
7707   MFI->incNumLocalDynamicTLSAccesses();
7708
7709   SDValue Base;
7710   if (is64Bit) {
7711     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7712                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7713   } else {
7714     SDValue InFlag;
7715     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7716         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7717     InFlag = Chain.getValue(1);
7718     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7719                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7720   }
7721
7722   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7723   // of Base.
7724
7725   // Build x@dtpoff.
7726   unsigned char OperandFlags = X86II::MO_DTPOFF;
7727   unsigned WrapperKind = X86ISD::Wrapper;
7728   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7729                                            GA->getValueType(0),
7730                                            GA->getOffset(), OperandFlags);
7731   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7732
7733   // Add x@dtpoff with the base.
7734   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7735 }
7736
7737 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7738 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7739                                    const EVT PtrVT, TLSModel::Model model,
7740                                    bool is64Bit, bool isPIC) {
7741   DebugLoc dl = GA->getDebugLoc();
7742
7743   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7744   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7745                                                          is64Bit ? 257 : 256));
7746
7747   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7748                                       DAG.getIntPtrConstant(0),
7749                                       MachinePointerInfo(Ptr),
7750                                       false, false, false, 0);
7751
7752   unsigned char OperandFlags = 0;
7753   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7754   // initialexec.
7755   unsigned WrapperKind = X86ISD::Wrapper;
7756   if (model == TLSModel::LocalExec) {
7757     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7758   } else if (model == TLSModel::InitialExec) {
7759     if (is64Bit) {
7760       OperandFlags = X86II::MO_GOTTPOFF;
7761       WrapperKind = X86ISD::WrapperRIP;
7762     } else {
7763       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7764     }
7765   } else {
7766     llvm_unreachable("Unexpected model");
7767   }
7768
7769   // emit "addl x@ntpoff,%eax" (local exec)
7770   // or "addl x@indntpoff,%eax" (initial exec)
7771   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7772   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7773                                            GA->getValueType(0),
7774                                            GA->getOffset(), OperandFlags);
7775   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7776
7777   if (model == TLSModel::InitialExec) {
7778     if (isPIC && !is64Bit) {
7779       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7780                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7781                            Offset);
7782     }
7783
7784     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7785                          MachinePointerInfo::getGOT(), false, false, false,
7786                          0);
7787   }
7788
7789   // The address of the thread local variable is the add of the thread
7790   // pointer with the offset of the variable.
7791   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7792 }
7793
7794 SDValue
7795 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7796
7797   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7798   const GlobalValue *GV = GA->getGlobal();
7799
7800   if (Subtarget->isTargetELF()) {
7801     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7802
7803     switch (model) {
7804       case TLSModel::GeneralDynamic:
7805         if (Subtarget->is64Bit())
7806           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7807         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7808       case TLSModel::LocalDynamic:
7809         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7810                                            Subtarget->is64Bit());
7811       case TLSModel::InitialExec:
7812       case TLSModel::LocalExec:
7813         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7814                                    Subtarget->is64Bit(),
7815                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7816     }
7817     llvm_unreachable("Unknown TLS model.");
7818   }
7819
7820   if (Subtarget->isTargetDarwin()) {
7821     // Darwin only has one model of TLS.  Lower to that.
7822     unsigned char OpFlag = 0;
7823     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7824                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7825
7826     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7827     // global base reg.
7828     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7829                   !Subtarget->is64Bit();
7830     if (PIC32)
7831       OpFlag = X86II::MO_TLVP_PIC_BASE;
7832     else
7833       OpFlag = X86II::MO_TLVP;
7834     DebugLoc DL = Op.getDebugLoc();
7835     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7836                                                 GA->getValueType(0),
7837                                                 GA->getOffset(), OpFlag);
7838     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7839
7840     // With PIC32, the address is actually $g + Offset.
7841     if (PIC32)
7842       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7843                            DAG.getNode(X86ISD::GlobalBaseReg,
7844                                        DebugLoc(), getPointerTy()),
7845                            Offset);
7846
7847     // Lowering the machine isd will make sure everything is in the right
7848     // location.
7849     SDValue Chain = DAG.getEntryNode();
7850     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7851     SDValue Args[] = { Chain, Offset };
7852     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7853
7854     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7855     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7856     MFI->setAdjustsStack(true);
7857
7858     // And our return value (tls address) is in the standard call return value
7859     // location.
7860     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7861     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7862                               Chain.getValue(1));
7863   }
7864
7865   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7866     // Just use the implicit TLS architecture
7867     // Need to generate someting similar to:
7868     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7869     //                                  ; from TEB
7870     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7871     //   mov     rcx, qword [rdx+rcx*8]
7872     //   mov     eax, .tls$:tlsvar
7873     //   [rax+rcx] contains the address
7874     // Windows 64bit: gs:0x58
7875     // Windows 32bit: fs:__tls_array
7876
7877     // If GV is an alias then use the aliasee for determining
7878     // thread-localness.
7879     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7880       GV = GA->resolveAliasedGlobal(false);
7881     DebugLoc dl = GA->getDebugLoc();
7882     SDValue Chain = DAG.getEntryNode();
7883
7884     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7885     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7886     // use its literal value of 0x2C.
7887     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7888                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7889                                                              256)
7890                                         : Type::getInt32PtrTy(*DAG.getContext(),
7891                                                               257));
7892
7893     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7894       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7895         DAG.getExternalSymbol("_tls_array", getPointerTy()));
7896
7897     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7898                                         MachinePointerInfo(Ptr),
7899                                         false, false, false, 0);
7900
7901     // Load the _tls_index variable
7902     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7903     if (Subtarget->is64Bit())
7904       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7905                            IDX, MachinePointerInfo(), MVT::i32,
7906                            false, false, 0);
7907     else
7908       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7909                         false, false, false, 0);
7910
7911     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7912                                     getPointerTy());
7913     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7914
7915     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7916     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7917                       false, false, false, 0);
7918
7919     // Get the offset of start of .tls section
7920     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7921                                              GA->getValueType(0),
7922                                              GA->getOffset(), X86II::MO_SECREL);
7923     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7924
7925     // The address of the thread local variable is the add of the thread
7926     // pointer with the offset of the variable.
7927     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7928   }
7929
7930   llvm_unreachable("TLS not implemented for this target.");
7931 }
7932
7933 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7934 /// and take a 2 x i32 value to shift plus a shift amount.
7935 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7936   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7937   EVT VT = Op.getValueType();
7938   unsigned VTBits = VT.getSizeInBits();
7939   DebugLoc dl = Op.getDebugLoc();
7940   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7941   SDValue ShOpLo = Op.getOperand(0);
7942   SDValue ShOpHi = Op.getOperand(1);
7943   SDValue ShAmt  = Op.getOperand(2);
7944   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7945                                      DAG.getConstant(VTBits - 1, MVT::i8))
7946                        : DAG.getConstant(0, VT);
7947
7948   SDValue Tmp2, Tmp3;
7949   if (Op.getOpcode() == ISD::SHL_PARTS) {
7950     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7951     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7952   } else {
7953     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7954     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7955   }
7956
7957   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7958                                 DAG.getConstant(VTBits, MVT::i8));
7959   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7960                              AndNode, DAG.getConstant(0, MVT::i8));
7961
7962   SDValue Hi, Lo;
7963   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7964   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7965   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7966
7967   if (Op.getOpcode() == ISD::SHL_PARTS) {
7968     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7969     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7970   } else {
7971     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7972     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7973   }
7974
7975   SDValue Ops[2] = { Lo, Hi };
7976   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7977 }
7978
7979 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7980                                            SelectionDAG &DAG) const {
7981   EVT SrcVT = Op.getOperand(0).getValueType();
7982
7983   if (SrcVT.isVector())
7984     return SDValue();
7985
7986   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7987          "Unknown SINT_TO_FP to lower!");
7988
7989   // These are really Legal; return the operand so the caller accepts it as
7990   // Legal.
7991   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7992     return Op;
7993   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7994       Subtarget->is64Bit()) {
7995     return Op;
7996   }
7997
7998   DebugLoc dl = Op.getDebugLoc();
7999   unsigned Size = SrcVT.getSizeInBits()/8;
8000   MachineFunction &MF = DAG.getMachineFunction();
8001   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8002   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8003   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8004                                StackSlot,
8005                                MachinePointerInfo::getFixedStack(SSFI),
8006                                false, false, 0);
8007   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8008 }
8009
8010 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8011                                      SDValue StackSlot,
8012                                      SelectionDAG &DAG) const {
8013   // Build the FILD
8014   DebugLoc DL = Op.getDebugLoc();
8015   SDVTList Tys;
8016   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8017   if (useSSE)
8018     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8019   else
8020     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8021
8022   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8023
8024   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8025   MachineMemOperand *MMO;
8026   if (FI) {
8027     int SSFI = FI->getIndex();
8028     MMO =
8029       DAG.getMachineFunction()
8030       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8031                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8032   } else {
8033     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8034     StackSlot = StackSlot.getOperand(1);
8035   }
8036   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8037   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8038                                            X86ISD::FILD, DL,
8039                                            Tys, Ops, array_lengthof(Ops),
8040                                            SrcVT, MMO);
8041
8042   if (useSSE) {
8043     Chain = Result.getValue(1);
8044     SDValue InFlag = Result.getValue(2);
8045
8046     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8047     // shouldn't be necessary except that RFP cannot be live across
8048     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8049     MachineFunction &MF = DAG.getMachineFunction();
8050     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8051     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8052     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8053     Tys = DAG.getVTList(MVT::Other);
8054     SDValue Ops[] = {
8055       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8056     };
8057     MachineMemOperand *MMO =
8058       DAG.getMachineFunction()
8059       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8060                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8061
8062     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8063                                     Ops, array_lengthof(Ops),
8064                                     Op.getValueType(), MMO);
8065     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8066                          MachinePointerInfo::getFixedStack(SSFI),
8067                          false, false, false, 0);
8068   }
8069
8070   return Result;
8071 }
8072
8073 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8074 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8075                                                SelectionDAG &DAG) const {
8076   // This algorithm is not obvious. Here it is what we're trying to output:
8077   /*
8078      movq       %rax,  %xmm0
8079      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8080      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8081      #ifdef __SSE3__
8082        haddpd   %xmm0, %xmm0
8083      #else
8084        pshufd   $0x4e, %xmm0, %xmm1
8085        addpd    %xmm1, %xmm0
8086      #endif
8087   */
8088
8089   DebugLoc dl = Op.getDebugLoc();
8090   LLVMContext *Context = DAG.getContext();
8091
8092   // Build some magic constants.
8093   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8094   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8095   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8096
8097   SmallVector<Constant*,2> CV1;
8098   CV1.push_back(
8099     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8100                                       APInt(64, 0x4330000000000000ULL))));
8101   CV1.push_back(
8102     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8103                                       APInt(64, 0x4530000000000000ULL))));
8104   Constant *C1 = ConstantVector::get(CV1);
8105   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8106
8107   // Load the 64-bit value into an XMM register.
8108   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8109                             Op.getOperand(0));
8110   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8111                               MachinePointerInfo::getConstantPool(),
8112                               false, false, false, 16);
8113   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8114                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8115                               CLod0);
8116
8117   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8118                               MachinePointerInfo::getConstantPool(),
8119                               false, false, false, 16);
8120   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8121   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8122   SDValue Result;
8123
8124   if (Subtarget->hasSSE3()) {
8125     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8126     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8127   } else {
8128     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8129     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8130                                            S2F, 0x4E, DAG);
8131     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8132                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8133                          Sub);
8134   }
8135
8136   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8137                      DAG.getIntPtrConstant(0));
8138 }
8139
8140 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8141 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8142                                                SelectionDAG &DAG) const {
8143   DebugLoc dl = Op.getDebugLoc();
8144   // FP constant to bias correct the final result.
8145   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8146                                    MVT::f64);
8147
8148   // Load the 32-bit value into an XMM register.
8149   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8150                              Op.getOperand(0));
8151
8152   // Zero out the upper parts of the register.
8153   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8154
8155   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8156                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8157                      DAG.getIntPtrConstant(0));
8158
8159   // Or the load with the bias.
8160   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8161                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8162                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8163                                                    MVT::v2f64, Load)),
8164                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8165                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8166                                                    MVT::v2f64, Bias)));
8167   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8168                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8169                    DAG.getIntPtrConstant(0));
8170
8171   // Subtract the bias.
8172   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8173
8174   // Handle final rounding.
8175   EVT DestVT = Op.getValueType();
8176
8177   if (DestVT.bitsLT(MVT::f64))
8178     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8179                        DAG.getIntPtrConstant(0));
8180   if (DestVT.bitsGT(MVT::f64))
8181     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8182
8183   // Handle final rounding.
8184   return Sub;
8185 }
8186
8187 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8188                                                SelectionDAG &DAG) const {
8189   SDValue N0 = Op.getOperand(0);
8190   EVT SVT = N0.getValueType();
8191   DebugLoc dl = Op.getDebugLoc();
8192
8193   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8194           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8195          "Custom UINT_TO_FP is not supported!");
8196
8197   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8198                              SVT.getVectorNumElements());
8199   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8200                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8201 }
8202
8203 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8204                                            SelectionDAG &DAG) const {
8205   SDValue N0 = Op.getOperand(0);
8206   DebugLoc dl = Op.getDebugLoc();
8207
8208   if (Op.getValueType().isVector())
8209     return lowerUINT_TO_FP_vec(Op, DAG);
8210
8211   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8212   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8213   // the optimization here.
8214   if (DAG.SignBitIsZero(N0))
8215     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8216
8217   EVT SrcVT = N0.getValueType();
8218   EVT DstVT = Op.getValueType();
8219   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8220     return LowerUINT_TO_FP_i64(Op, DAG);
8221   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8222     return LowerUINT_TO_FP_i32(Op, DAG);
8223   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8224     return SDValue();
8225
8226   // Make a 64-bit buffer, and use it to build an FILD.
8227   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8228   if (SrcVT == MVT::i32) {
8229     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8230     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8231                                      getPointerTy(), StackSlot, WordOff);
8232     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8233                                   StackSlot, MachinePointerInfo(),
8234                                   false, false, 0);
8235     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8236                                   OffsetSlot, MachinePointerInfo(),
8237                                   false, false, 0);
8238     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8239     return Fild;
8240   }
8241
8242   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8243   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8244                                StackSlot, MachinePointerInfo(),
8245                                false, false, 0);
8246   // For i64 source, we need to add the appropriate power of 2 if the input
8247   // was negative.  This is the same as the optimization in
8248   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8249   // we must be careful to do the computation in x87 extended precision, not
8250   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8251   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8252   MachineMemOperand *MMO =
8253     DAG.getMachineFunction()
8254     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8255                           MachineMemOperand::MOLoad, 8, 8);
8256
8257   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8258   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8259   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8260                                          array_lengthof(Ops), MVT::i64, MMO);
8261
8262   APInt FF(32, 0x5F800000ULL);
8263
8264   // Check whether the sign bit is set.
8265   SDValue SignSet = DAG.getSetCC(dl,
8266                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8267                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8268                                  ISD::SETLT);
8269
8270   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8271   SDValue FudgePtr = DAG.getConstantPool(
8272                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8273                                          getPointerTy());
8274
8275   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8276   SDValue Zero = DAG.getIntPtrConstant(0);
8277   SDValue Four = DAG.getIntPtrConstant(4);
8278   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8279                                Zero, Four);
8280   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8281
8282   // Load the value out, extending it from f32 to f80.
8283   // FIXME: Avoid the extend by constructing the right constant pool?
8284   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8285                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8286                                  MVT::f32, false, false, 4);
8287   // Extend everything to 80 bits to force it to be done on x87.
8288   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8289   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8290 }
8291
8292 std::pair<SDValue,SDValue>
8293 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8294                                     bool IsSigned, bool IsReplace) const {
8295   DebugLoc DL = Op.getDebugLoc();
8296
8297   EVT DstTy = Op.getValueType();
8298
8299   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8300     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8301     DstTy = MVT::i64;
8302   }
8303
8304   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8305          DstTy.getSimpleVT() >= MVT::i16 &&
8306          "Unknown FP_TO_INT to lower!");
8307
8308   // These are really Legal.
8309   if (DstTy == MVT::i32 &&
8310       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8311     return std::make_pair(SDValue(), SDValue());
8312   if (Subtarget->is64Bit() &&
8313       DstTy == MVT::i64 &&
8314       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8315     return std::make_pair(SDValue(), SDValue());
8316
8317   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8318   // stack slot, or into the FTOL runtime function.
8319   MachineFunction &MF = DAG.getMachineFunction();
8320   unsigned MemSize = DstTy.getSizeInBits()/8;
8321   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8322   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8323
8324   unsigned Opc;
8325   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8326     Opc = X86ISD::WIN_FTOL;
8327   else
8328     switch (DstTy.getSimpleVT().SimpleTy) {
8329     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8330     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8331     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8332     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8333     }
8334
8335   SDValue Chain = DAG.getEntryNode();
8336   SDValue Value = Op.getOperand(0);
8337   EVT TheVT = Op.getOperand(0).getValueType();
8338   // FIXME This causes a redundant load/store if the SSE-class value is already
8339   // in memory, such as if it is on the callstack.
8340   if (isScalarFPTypeInSSEReg(TheVT)) {
8341     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8342     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8343                          MachinePointerInfo::getFixedStack(SSFI),
8344                          false, false, 0);
8345     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8346     SDValue Ops[] = {
8347       Chain, StackSlot, DAG.getValueType(TheVT)
8348     };
8349
8350     MachineMemOperand *MMO =
8351       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8352                               MachineMemOperand::MOLoad, MemSize, MemSize);
8353     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8354                                     array_lengthof(Ops), DstTy, MMO);
8355     Chain = Value.getValue(1);
8356     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8357     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8358   }
8359
8360   MachineMemOperand *MMO =
8361     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8362                             MachineMemOperand::MOStore, MemSize, MemSize);
8363
8364   if (Opc != X86ISD::WIN_FTOL) {
8365     // Build the FP_TO_INT*_IN_MEM
8366     SDValue Ops[] = { Chain, Value, StackSlot };
8367     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8368                                            Ops, array_lengthof(Ops), DstTy,
8369                                            MMO);
8370     return std::make_pair(FIST, StackSlot);
8371   } else {
8372     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8373       DAG.getVTList(MVT::Other, MVT::Glue),
8374       Chain, Value);
8375     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8376       MVT::i32, ftol.getValue(1));
8377     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8378       MVT::i32, eax.getValue(2));
8379     SDValue Ops[] = { eax, edx };
8380     SDValue pair = IsReplace
8381       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8382       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8383     return std::make_pair(pair, SDValue());
8384   }
8385 }
8386
8387 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8388                               const X86Subtarget *Subtarget) {
8389   MVT VT = Op->getValueType(0).getSimpleVT();
8390   SDValue In = Op->getOperand(0);
8391   MVT InVT = In.getValueType().getSimpleVT();
8392   DebugLoc dl = Op->getDebugLoc();
8393
8394   // Optimize vectors in AVX mode:
8395   //
8396   //   v8i16 -> v8i32
8397   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8398   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8399   //   Concat upper and lower parts.
8400   //
8401   //   v4i32 -> v4i64
8402   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8403   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8404   //   Concat upper and lower parts.
8405   //
8406
8407   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8408       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8409     return SDValue();
8410
8411   if (Subtarget->hasInt256())
8412     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8413
8414   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8415   SDValue Undef = DAG.getUNDEF(InVT);
8416   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8417   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8418   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8419
8420   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8421                              VT.getVectorNumElements()/2);
8422
8423   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8424   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8425
8426   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8427 }
8428
8429 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8430                                            SelectionDAG &DAG) const {
8431   if (Subtarget->hasFp256()) {
8432     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8433     if (Res.getNode())
8434       return Res;
8435   }
8436
8437   return SDValue();
8438 }
8439 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8440                                             SelectionDAG &DAG) const {
8441   DebugLoc DL = Op.getDebugLoc();
8442   MVT VT = Op.getValueType().getSimpleVT();
8443   SDValue In = Op.getOperand(0);
8444   MVT SVT = In.getValueType().getSimpleVT();
8445
8446   if (Subtarget->hasFp256()) {
8447     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8448     if (Res.getNode())
8449       return Res;
8450   }
8451
8452   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8453       VT.getVectorNumElements() != SVT.getVectorNumElements())
8454     return SDValue();
8455
8456   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8457
8458   // AVX2 has better support of integer extending.
8459   if (Subtarget->hasInt256())
8460     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8461
8462   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8463   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8464   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8465                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8466                                                 DAG.getUNDEF(MVT::v8i16),
8467                                                 &Mask[0]));
8468
8469   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8470 }
8471
8472 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8473   DebugLoc DL = Op.getDebugLoc();
8474   MVT VT = Op.getValueType().getSimpleVT();
8475   SDValue In = Op.getOperand(0);
8476   MVT SVT = In.getValueType().getSimpleVT();
8477
8478   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8479     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8480     if (Subtarget->hasInt256()) {
8481       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8482       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8483       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8484                                 ShufMask);
8485       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8486                          DAG.getIntPtrConstant(0));
8487     }
8488
8489     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8490     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8491                                DAG.getIntPtrConstant(0));
8492     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8493                                DAG.getIntPtrConstant(2));
8494
8495     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8496     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8497
8498     // The PSHUFD mask:
8499     static const int ShufMask1[] = {0, 2, 0, 0};
8500     SDValue Undef = DAG.getUNDEF(VT);
8501     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8502     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8503
8504     // The MOVLHPS mask:
8505     static const int ShufMask2[] = {0, 1, 4, 5};
8506     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8507   }
8508
8509   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8510     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8511     if (Subtarget->hasInt256()) {
8512       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8513
8514       SmallVector<SDValue,32> pshufbMask;
8515       for (unsigned i = 0; i < 2; ++i) {
8516         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8517         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8518         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8519         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8520         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8521         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8522         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8523         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8524         for (unsigned j = 0; j < 8; ++j)
8525           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8526       }
8527       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8528                                &pshufbMask[0], 32);
8529       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8530       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8531
8532       static const int ShufMask[] = {0,  2,  -1,  -1};
8533       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8534                                 &ShufMask[0]);
8535       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8536                        DAG.getIntPtrConstant(0));
8537       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8538     }
8539
8540     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8541                                DAG.getIntPtrConstant(0));
8542
8543     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8544                                DAG.getIntPtrConstant(4));
8545
8546     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8547     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8548
8549     // The PSHUFB mask:
8550     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8551                                    -1, -1, -1, -1, -1, -1, -1, -1};
8552
8553     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8554     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8555     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8556
8557     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8558     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8559
8560     // The MOVLHPS Mask:
8561     static const int ShufMask2[] = {0, 1, 4, 5};
8562     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8563     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8564   }
8565
8566   // Handle truncation of V256 to V128 using shuffles.
8567   if (!VT.is128BitVector() || !SVT.is256BitVector())
8568     return SDValue();
8569
8570   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8571          "Invalid op");
8572   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8573
8574   unsigned NumElems = VT.getVectorNumElements();
8575   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8576                              NumElems * 2);
8577
8578   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8579   // Prepare truncation shuffle mask
8580   for (unsigned i = 0; i != NumElems; ++i)
8581     MaskVec[i] = i * 2;
8582   SDValue V = DAG.getVectorShuffle(NVT, DL,
8583                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8584                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8585   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8586                      DAG.getIntPtrConstant(0));
8587 }
8588
8589 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8590                                            SelectionDAG &DAG) const {
8591   MVT VT = Op.getValueType().getSimpleVT();
8592   if (VT.isVector()) {
8593     if (VT == MVT::v8i16)
8594       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8595                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8596                                      MVT::v8i32, Op.getOperand(0)));
8597     return SDValue();
8598   }
8599
8600   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8601     /*IsSigned=*/ true, /*IsReplace=*/ false);
8602   SDValue FIST = Vals.first, StackSlot = Vals.second;
8603   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8604   if (FIST.getNode() == 0) return Op;
8605
8606   if (StackSlot.getNode())
8607     // Load the result.
8608     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8609                        FIST, StackSlot, MachinePointerInfo(),
8610                        false, false, false, 0);
8611
8612   // The node is the result.
8613   return FIST;
8614 }
8615
8616 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8617                                            SelectionDAG &DAG) const {
8618   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8619     /*IsSigned=*/ false, /*IsReplace=*/ false);
8620   SDValue FIST = Vals.first, StackSlot = Vals.second;
8621   assert(FIST.getNode() && "Unexpected failure");
8622
8623   if (StackSlot.getNode())
8624     // Load the result.
8625     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8626                        FIST, StackSlot, MachinePointerInfo(),
8627                        false, false, false, 0);
8628
8629   // The node is the result.
8630   return FIST;
8631 }
8632
8633 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8634   DebugLoc DL = Op.getDebugLoc();
8635   MVT VT = Op.getValueType().getSimpleVT();
8636   SDValue In = Op.getOperand(0);
8637   MVT SVT = In.getValueType().getSimpleVT();
8638
8639   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8640
8641   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8642                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8643                                  In, DAG.getUNDEF(SVT)));
8644 }
8645
8646 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8647   LLVMContext *Context = DAG.getContext();
8648   DebugLoc dl = Op.getDebugLoc();
8649   MVT VT = Op.getValueType().getSimpleVT();
8650   MVT EltVT = VT;
8651   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8652   if (VT.isVector()) {
8653     EltVT = VT.getVectorElementType();
8654     NumElts = VT.getVectorNumElements();
8655   }
8656   Constant *C;
8657   if (EltVT == MVT::f64)
8658     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8659                                           APInt(64, ~(1ULL << 63))));
8660   else
8661     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8662                                           APInt(32, ~(1U << 31))));
8663   C = ConstantVector::getSplat(NumElts, C);
8664   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8665   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8666   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8667                              MachinePointerInfo::getConstantPool(),
8668                              false, false, false, Alignment);
8669   if (VT.isVector()) {
8670     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8671     return DAG.getNode(ISD::BITCAST, dl, VT,
8672                        DAG.getNode(ISD::AND, dl, ANDVT,
8673                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8674                                                Op.getOperand(0)),
8675                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8676   }
8677   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8678 }
8679
8680 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8681   LLVMContext *Context = DAG.getContext();
8682   DebugLoc dl = Op.getDebugLoc();
8683   MVT VT = Op.getValueType().getSimpleVT();
8684   MVT EltVT = VT;
8685   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8686   if (VT.isVector()) {
8687     EltVT = VT.getVectorElementType();
8688     NumElts = VT.getVectorNumElements();
8689   }
8690   Constant *C;
8691   if (EltVT == MVT::f64)
8692     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8693                                           APInt(64, 1ULL << 63)));
8694   else
8695     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8696                                           APInt(32, 1U << 31)));
8697   C = ConstantVector::getSplat(NumElts, C);
8698   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8699   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8700   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8701                              MachinePointerInfo::getConstantPool(),
8702                              false, false, false, Alignment);
8703   if (VT.isVector()) {
8704     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8705     return DAG.getNode(ISD::BITCAST, dl, VT,
8706                        DAG.getNode(ISD::XOR, dl, XORVT,
8707                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8708                                                Op.getOperand(0)),
8709                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8710   }
8711
8712   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8713 }
8714
8715 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8716   LLVMContext *Context = DAG.getContext();
8717   SDValue Op0 = Op.getOperand(0);
8718   SDValue Op1 = Op.getOperand(1);
8719   DebugLoc dl = Op.getDebugLoc();
8720   MVT VT = Op.getValueType().getSimpleVT();
8721   MVT SrcVT = Op1.getValueType().getSimpleVT();
8722
8723   // If second operand is smaller, extend it first.
8724   if (SrcVT.bitsLT(VT)) {
8725     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8726     SrcVT = VT;
8727   }
8728   // And if it is bigger, shrink it first.
8729   if (SrcVT.bitsGT(VT)) {
8730     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8731     SrcVT = VT;
8732   }
8733
8734   // At this point the operands and the result should have the same
8735   // type, and that won't be f80 since that is not custom lowered.
8736
8737   // First get the sign bit of second operand.
8738   SmallVector<Constant*,4> CV;
8739   if (SrcVT == MVT::f64) {
8740     const fltSemantics &Sem = APFloat::IEEEdouble;
8741     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8742     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8743   } else {
8744     const fltSemantics &Sem = APFloat::IEEEsingle;
8745     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8746     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8747     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8748     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8749   }
8750   Constant *C = ConstantVector::get(CV);
8751   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8752   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8753                               MachinePointerInfo::getConstantPool(),
8754                               false, false, false, 16);
8755   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8756
8757   // Shift sign bit right or left if the two operands have different types.
8758   if (SrcVT.bitsGT(VT)) {
8759     // Op0 is MVT::f32, Op1 is MVT::f64.
8760     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8761     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8762                           DAG.getConstant(32, MVT::i32));
8763     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8764     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8765                           DAG.getIntPtrConstant(0));
8766   }
8767
8768   // Clear first operand sign bit.
8769   CV.clear();
8770   if (VT == MVT::f64) {
8771     const fltSemantics &Sem = APFloat::IEEEdouble;
8772     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8773                                                    APInt(64, ~(1ULL << 63)))));
8774     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8775   } else {
8776     const fltSemantics &Sem = APFloat::IEEEsingle;
8777     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8778                                                    APInt(32, ~(1U << 31)))));
8779     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8780     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8781     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8782   }
8783   C = ConstantVector::get(CV);
8784   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8785   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8786                               MachinePointerInfo::getConstantPool(),
8787                               false, false, false, 16);
8788   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8789
8790   // Or the value with the sign bit.
8791   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8792 }
8793
8794 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8795   SDValue N0 = Op.getOperand(0);
8796   DebugLoc dl = Op.getDebugLoc();
8797   MVT VT = Op.getValueType().getSimpleVT();
8798
8799   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8800   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8801                                   DAG.getConstant(1, VT));
8802   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8803 }
8804
8805 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8806 //
8807 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8808                                                   SelectionDAG &DAG) const {
8809   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8810
8811   if (!Subtarget->hasSSE41())
8812     return SDValue();
8813
8814   if (!Op->hasOneUse())
8815     return SDValue();
8816
8817   SDNode *N = Op.getNode();
8818   DebugLoc DL = N->getDebugLoc();
8819
8820   SmallVector<SDValue, 8> Opnds;
8821   DenseMap<SDValue, unsigned> VecInMap;
8822   EVT VT = MVT::Other;
8823
8824   // Recognize a special case where a vector is casted into wide integer to
8825   // test all 0s.
8826   Opnds.push_back(N->getOperand(0));
8827   Opnds.push_back(N->getOperand(1));
8828
8829   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8830     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8831     // BFS traverse all OR'd operands.
8832     if (I->getOpcode() == ISD::OR) {
8833       Opnds.push_back(I->getOperand(0));
8834       Opnds.push_back(I->getOperand(1));
8835       // Re-evaluate the number of nodes to be traversed.
8836       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8837       continue;
8838     }
8839
8840     // Quit if a non-EXTRACT_VECTOR_ELT
8841     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8842       return SDValue();
8843
8844     // Quit if without a constant index.
8845     SDValue Idx = I->getOperand(1);
8846     if (!isa<ConstantSDNode>(Idx))
8847       return SDValue();
8848
8849     SDValue ExtractedFromVec = I->getOperand(0);
8850     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8851     if (M == VecInMap.end()) {
8852       VT = ExtractedFromVec.getValueType();
8853       // Quit if not 128/256-bit vector.
8854       if (!VT.is128BitVector() && !VT.is256BitVector())
8855         return SDValue();
8856       // Quit if not the same type.
8857       if (VecInMap.begin() != VecInMap.end() &&
8858           VT != VecInMap.begin()->first.getValueType())
8859         return SDValue();
8860       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8861     }
8862     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8863   }
8864
8865   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8866          "Not extracted from 128-/256-bit vector.");
8867
8868   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8869   SmallVector<SDValue, 8> VecIns;
8870
8871   for (DenseMap<SDValue, unsigned>::const_iterator
8872         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8873     // Quit if not all elements are used.
8874     if (I->second != FullMask)
8875       return SDValue();
8876     VecIns.push_back(I->first);
8877   }
8878
8879   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8880
8881   // Cast all vectors into TestVT for PTEST.
8882   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8883     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8884
8885   // If more than one full vectors are evaluated, OR them first before PTEST.
8886   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8887     // Each iteration will OR 2 nodes and append the result until there is only
8888     // 1 node left, i.e. the final OR'd value of all vectors.
8889     SDValue LHS = VecIns[Slot];
8890     SDValue RHS = VecIns[Slot + 1];
8891     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8892   }
8893
8894   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8895                      VecIns.back(), VecIns.back());
8896 }
8897
8898 /// Emit nodes that will be selected as "test Op0,Op0", or something
8899 /// equivalent.
8900 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8901                                     SelectionDAG &DAG) const {
8902   DebugLoc dl = Op.getDebugLoc();
8903
8904   // CF and OF aren't always set the way we want. Determine which
8905   // of these we need.
8906   bool NeedCF = false;
8907   bool NeedOF = false;
8908   switch (X86CC) {
8909   default: break;
8910   case X86::COND_A: case X86::COND_AE:
8911   case X86::COND_B: case X86::COND_BE:
8912     NeedCF = true;
8913     break;
8914   case X86::COND_G: case X86::COND_GE:
8915   case X86::COND_L: case X86::COND_LE:
8916   case X86::COND_O: case X86::COND_NO:
8917     NeedOF = true;
8918     break;
8919   }
8920
8921   // See if we can use the EFLAGS value from the operand instead of
8922   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8923   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8924   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8925     // Emit a CMP with 0, which is the TEST pattern.
8926     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8927                        DAG.getConstant(0, Op.getValueType()));
8928
8929   unsigned Opcode = 0;
8930   unsigned NumOperands = 0;
8931
8932   // Truncate operations may prevent the merge of the SETCC instruction
8933   // and the arithmetic intruction before it. Attempt to truncate the operands
8934   // of the arithmetic instruction and use a reduced bit-width instruction.
8935   bool NeedTruncation = false;
8936   SDValue ArithOp = Op;
8937   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8938     SDValue Arith = Op->getOperand(0);
8939     // Both the trunc and the arithmetic op need to have one user each.
8940     if (Arith->hasOneUse())
8941       switch (Arith.getOpcode()) {
8942         default: break;
8943         case ISD::ADD:
8944         case ISD::SUB:
8945         case ISD::AND:
8946         case ISD::OR:
8947         case ISD::XOR: {
8948           NeedTruncation = true;
8949           ArithOp = Arith;
8950         }
8951       }
8952   }
8953
8954   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8955   // which may be the result of a CAST.  We use the variable 'Op', which is the
8956   // non-casted variable when we check for possible users.
8957   switch (ArithOp.getOpcode()) {
8958   case ISD::ADD:
8959     // Due to an isel shortcoming, be conservative if this add is likely to be
8960     // selected as part of a load-modify-store instruction. When the root node
8961     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8962     // uses of other nodes in the match, such as the ADD in this case. This
8963     // leads to the ADD being left around and reselected, with the result being
8964     // two adds in the output.  Alas, even if none our users are stores, that
8965     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8966     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8967     // climbing the DAG back to the root, and it doesn't seem to be worth the
8968     // effort.
8969     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8970          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8971       if (UI->getOpcode() != ISD::CopyToReg &&
8972           UI->getOpcode() != ISD::SETCC &&
8973           UI->getOpcode() != ISD::STORE)
8974         goto default_case;
8975
8976     if (ConstantSDNode *C =
8977         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8978       // An add of one will be selected as an INC.
8979       if (C->getAPIntValue() == 1) {
8980         Opcode = X86ISD::INC;
8981         NumOperands = 1;
8982         break;
8983       }
8984
8985       // An add of negative one (subtract of one) will be selected as a DEC.
8986       if (C->getAPIntValue().isAllOnesValue()) {
8987         Opcode = X86ISD::DEC;
8988         NumOperands = 1;
8989         break;
8990       }
8991     }
8992
8993     // Otherwise use a regular EFLAGS-setting add.
8994     Opcode = X86ISD::ADD;
8995     NumOperands = 2;
8996     break;
8997   case ISD::AND: {
8998     // If the primary and result isn't used, don't bother using X86ISD::AND,
8999     // because a TEST instruction will be better.
9000     bool NonFlagUse = false;
9001     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9002            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9003       SDNode *User = *UI;
9004       unsigned UOpNo = UI.getOperandNo();
9005       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9006         // Look pass truncate.
9007         UOpNo = User->use_begin().getOperandNo();
9008         User = *User->use_begin();
9009       }
9010
9011       if (User->getOpcode() != ISD::BRCOND &&
9012           User->getOpcode() != ISD::SETCC &&
9013           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9014         NonFlagUse = true;
9015         break;
9016       }
9017     }
9018
9019     if (!NonFlagUse)
9020       break;
9021   }
9022     // FALL THROUGH
9023   case ISD::SUB:
9024   case ISD::OR:
9025   case ISD::XOR:
9026     // Due to the ISEL shortcoming noted above, be conservative if this op is
9027     // likely to be selected as part of a load-modify-store instruction.
9028     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9029            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9030       if (UI->getOpcode() == ISD::STORE)
9031         goto default_case;
9032
9033     // Otherwise use a regular EFLAGS-setting instruction.
9034     switch (ArithOp.getOpcode()) {
9035     default: llvm_unreachable("unexpected operator!");
9036     case ISD::SUB: Opcode = X86ISD::SUB; break;
9037     case ISD::XOR: Opcode = X86ISD::XOR; break;
9038     case ISD::AND: Opcode = X86ISD::AND; break;
9039     case ISD::OR: {
9040       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9041         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9042         if (EFLAGS.getNode())
9043           return EFLAGS;
9044       }
9045       Opcode = X86ISD::OR;
9046       break;
9047     }
9048     }
9049
9050     NumOperands = 2;
9051     break;
9052   case X86ISD::ADD:
9053   case X86ISD::SUB:
9054   case X86ISD::INC:
9055   case X86ISD::DEC:
9056   case X86ISD::OR:
9057   case X86ISD::XOR:
9058   case X86ISD::AND:
9059     return SDValue(Op.getNode(), 1);
9060   default:
9061   default_case:
9062     break;
9063   }
9064
9065   // If we found that truncation is beneficial, perform the truncation and
9066   // update 'Op'.
9067   if (NeedTruncation) {
9068     EVT VT = Op.getValueType();
9069     SDValue WideVal = Op->getOperand(0);
9070     EVT WideVT = WideVal.getValueType();
9071     unsigned ConvertedOp = 0;
9072     // Use a target machine opcode to prevent further DAGCombine
9073     // optimizations that may separate the arithmetic operations
9074     // from the setcc node.
9075     switch (WideVal.getOpcode()) {
9076       default: break;
9077       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9078       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9079       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9080       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9081       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9082     }
9083
9084     if (ConvertedOp) {
9085       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9086       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9087         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9088         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9089         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9090       }
9091     }
9092   }
9093
9094   if (Opcode == 0)
9095     // Emit a CMP with 0, which is the TEST pattern.
9096     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9097                        DAG.getConstant(0, Op.getValueType()));
9098
9099   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9100   SmallVector<SDValue, 4> Ops;
9101   for (unsigned i = 0; i != NumOperands; ++i)
9102     Ops.push_back(Op.getOperand(i));
9103
9104   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9105   DAG.ReplaceAllUsesWith(Op, New);
9106   return SDValue(New.getNode(), 1);
9107 }
9108
9109 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9110 /// equivalent.
9111 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9112                                    SelectionDAG &DAG) const {
9113   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9114     if (C->getAPIntValue() == 0)
9115       return EmitTest(Op0, X86CC, DAG);
9116
9117   DebugLoc dl = Op0.getDebugLoc();
9118   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9119        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9120     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9121     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9122     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9123                               Op0, Op1);
9124     return SDValue(Sub.getNode(), 1);
9125   }
9126   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9127 }
9128
9129 /// Convert a comparison if required by the subtarget.
9130 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9131                                                  SelectionDAG &DAG) const {
9132   // If the subtarget does not support the FUCOMI instruction, floating-point
9133   // comparisons have to be converted.
9134   if (Subtarget->hasCMov() ||
9135       Cmp.getOpcode() != X86ISD::CMP ||
9136       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9137       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9138     return Cmp;
9139
9140   // The instruction selector will select an FUCOM instruction instead of
9141   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9142   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9143   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9144   DebugLoc dl = Cmp.getDebugLoc();
9145   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9146   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9147   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9148                             DAG.getConstant(8, MVT::i8));
9149   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9150   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9151 }
9152
9153 static bool isAllOnes(SDValue V) {
9154   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9155   return C && C->isAllOnesValue();
9156 }
9157
9158 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9159 /// if it's possible.
9160 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9161                                      DebugLoc dl, SelectionDAG &DAG) const {
9162   SDValue Op0 = And.getOperand(0);
9163   SDValue Op1 = And.getOperand(1);
9164   if (Op0.getOpcode() == ISD::TRUNCATE)
9165     Op0 = Op0.getOperand(0);
9166   if (Op1.getOpcode() == ISD::TRUNCATE)
9167     Op1 = Op1.getOperand(0);
9168
9169   SDValue LHS, RHS;
9170   if (Op1.getOpcode() == ISD::SHL)
9171     std::swap(Op0, Op1);
9172   if (Op0.getOpcode() == ISD::SHL) {
9173     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9174       if (And00C->getZExtValue() == 1) {
9175         // If we looked past a truncate, check that it's only truncating away
9176         // known zeros.
9177         unsigned BitWidth = Op0.getValueSizeInBits();
9178         unsigned AndBitWidth = And.getValueSizeInBits();
9179         if (BitWidth > AndBitWidth) {
9180           APInt Zeros, Ones;
9181           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9182           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9183             return SDValue();
9184         }
9185         LHS = Op1;
9186         RHS = Op0.getOperand(1);
9187       }
9188   } else if (Op1.getOpcode() == ISD::Constant) {
9189     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9190     uint64_t AndRHSVal = AndRHS->getZExtValue();
9191     SDValue AndLHS = Op0;
9192
9193     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9194       LHS = AndLHS.getOperand(0);
9195       RHS = AndLHS.getOperand(1);
9196     }
9197
9198     // Use BT if the immediate can't be encoded in a TEST instruction.
9199     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9200       LHS = AndLHS;
9201       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9202     }
9203   }
9204
9205   if (LHS.getNode()) {
9206     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9207     // instruction.  Since the shift amount is in-range-or-undefined, we know
9208     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9209     // the encoding for the i16 version is larger than the i32 version.
9210     // Also promote i16 to i32 for performance / code size reason.
9211     if (LHS.getValueType() == MVT::i8 ||
9212         LHS.getValueType() == MVT::i16)
9213       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9214
9215     // If the operand types disagree, extend the shift amount to match.  Since
9216     // BT ignores high bits (like shifts) we can use anyextend.
9217     if (LHS.getValueType() != RHS.getValueType())
9218       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9219
9220     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9221     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9222     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9223                        DAG.getConstant(Cond, MVT::i8), BT);
9224   }
9225
9226   return SDValue();
9227 }
9228
9229 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9230 // ones, and then concatenate the result back.
9231 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9232   MVT VT = Op.getValueType().getSimpleVT();
9233
9234   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9235          "Unsupported value type for operation");
9236
9237   unsigned NumElems = VT.getVectorNumElements();
9238   DebugLoc dl = Op.getDebugLoc();
9239   SDValue CC = Op.getOperand(2);
9240
9241   // Extract the LHS vectors
9242   SDValue LHS = Op.getOperand(0);
9243   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9244   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9245
9246   // Extract the RHS vectors
9247   SDValue RHS = Op.getOperand(1);
9248   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9249   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9250
9251   // Issue the operation on the smaller types and concatenate the result back
9252   MVT EltVT = VT.getVectorElementType();
9253   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9254   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9255                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9256                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9257 }
9258
9259 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9260                            SelectionDAG &DAG) {
9261   SDValue Cond;
9262   SDValue Op0 = Op.getOperand(0);
9263   SDValue Op1 = Op.getOperand(1);
9264   SDValue CC = Op.getOperand(2);
9265   MVT VT = Op.getValueType().getSimpleVT();
9266   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9267   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9268   DebugLoc dl = Op.getDebugLoc();
9269
9270   if (isFP) {
9271 #ifndef NDEBUG
9272     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9273     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9274 #endif
9275
9276     unsigned SSECC;
9277     bool Swap = false;
9278
9279     // SSE Condition code mapping:
9280     //  0 - EQ
9281     //  1 - LT
9282     //  2 - LE
9283     //  3 - UNORD
9284     //  4 - NEQ
9285     //  5 - NLT
9286     //  6 - NLE
9287     //  7 - ORD
9288     switch (SetCCOpcode) {
9289     default: llvm_unreachable("Unexpected SETCC condition");
9290     case ISD::SETOEQ:
9291     case ISD::SETEQ:  SSECC = 0; break;
9292     case ISD::SETOGT:
9293     case ISD::SETGT: Swap = true; // Fallthrough
9294     case ISD::SETLT:
9295     case ISD::SETOLT: SSECC = 1; break;
9296     case ISD::SETOGE:
9297     case ISD::SETGE: Swap = true; // Fallthrough
9298     case ISD::SETLE:
9299     case ISD::SETOLE: SSECC = 2; break;
9300     case ISD::SETUO:  SSECC = 3; break;
9301     case ISD::SETUNE:
9302     case ISD::SETNE:  SSECC = 4; break;
9303     case ISD::SETULE: Swap = true; // Fallthrough
9304     case ISD::SETUGE: SSECC = 5; break;
9305     case ISD::SETULT: Swap = true; // Fallthrough
9306     case ISD::SETUGT: SSECC = 6; break;
9307     case ISD::SETO:   SSECC = 7; break;
9308     case ISD::SETUEQ:
9309     case ISD::SETONE: SSECC = 8; break;
9310     }
9311     if (Swap)
9312       std::swap(Op0, Op1);
9313
9314     // In the two special cases we can't handle, emit two comparisons.
9315     if (SSECC == 8) {
9316       unsigned CC0, CC1;
9317       unsigned CombineOpc;
9318       if (SetCCOpcode == ISD::SETUEQ) {
9319         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9320       } else {
9321         assert(SetCCOpcode == ISD::SETONE);
9322         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9323       }
9324
9325       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9326                                  DAG.getConstant(CC0, MVT::i8));
9327       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9328                                  DAG.getConstant(CC1, MVT::i8));
9329       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9330     }
9331     // Handle all other FP comparisons here.
9332     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9333                        DAG.getConstant(SSECC, MVT::i8));
9334   }
9335
9336   // Break 256-bit integer vector compare into smaller ones.
9337   if (VT.is256BitVector() && !Subtarget->hasInt256())
9338     return Lower256IntVSETCC(Op, DAG);
9339
9340   // We are handling one of the integer comparisons here.  Since SSE only has
9341   // GT and EQ comparisons for integer, swapping operands and multiple
9342   // operations may be required for some comparisons.
9343   unsigned Opc;
9344   bool Swap = false, Invert = false, FlipSigns = false;
9345
9346   switch (SetCCOpcode) {
9347   default: llvm_unreachable("Unexpected SETCC condition");
9348   case ISD::SETNE:  Invert = true;
9349   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9350   case ISD::SETLT:  Swap = true;
9351   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9352   case ISD::SETGE:  Swap = true;
9353   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9354   case ISD::SETULT: Swap = true;
9355   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9356   case ISD::SETUGE: Swap = true;
9357   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9358   }
9359   if (Swap)
9360     std::swap(Op0, Op1);
9361
9362   // Check that the operation in question is available (most are plain SSE2,
9363   // but PCMPGTQ and PCMPEQQ have different requirements).
9364   if (VT == MVT::v2i64) {
9365     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9366       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9367
9368       // First cast everything to the right type.
9369       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9370       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9371
9372       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9373       // bits of the inputs before performing those operations. The lower
9374       // compare is always unsigned.
9375       SDValue SB;
9376       if (FlipSigns) {
9377         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9378       } else {
9379         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9380         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9381         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9382                          Sign, Zero, Sign, Zero);
9383       }
9384       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9385       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9386
9387       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9388       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9389       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9390
9391       // Create masks for only the low parts/high parts of the 64 bit integers.
9392       const int MaskHi[] = { 1, 1, 3, 3 };
9393       const int MaskLo[] = { 0, 0, 2, 2 };
9394       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9395       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9396       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9397
9398       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9399       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9400
9401       if (Invert)
9402         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9403
9404       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9405     }
9406
9407     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9408       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9409       // pcmpeqd + pshufd + pand.
9410       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9411
9412       // First cast everything to the right type.
9413       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9414       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9415
9416       // Do the compare.
9417       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9418
9419       // Make sure the lower and upper halves are both all-ones.
9420       const int Mask[] = { 1, 0, 3, 2 };
9421       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9422       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9423
9424       if (Invert)
9425         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9426
9427       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9428     }
9429   }
9430
9431   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9432   // bits of the inputs before performing those operations.
9433   if (FlipSigns) {
9434     EVT EltVT = VT.getVectorElementType();
9435     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9436     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9437     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9438   }
9439
9440   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9441
9442   // If the logical-not of the result is required, perform that now.
9443   if (Invert)
9444     Result = DAG.getNOT(dl, Result, VT);
9445
9446   return Result;
9447 }
9448
9449 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9450
9451   MVT VT = Op.getValueType().getSimpleVT();
9452
9453   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9454
9455   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9456   SDValue Op0 = Op.getOperand(0);
9457   SDValue Op1 = Op.getOperand(1);
9458   DebugLoc dl = Op.getDebugLoc();
9459   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9460
9461   // Optimize to BT if possible.
9462   // Lower (X & (1 << N)) == 0 to BT(X, N).
9463   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9464   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9465   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9466       Op1.getOpcode() == ISD::Constant &&
9467       cast<ConstantSDNode>(Op1)->isNullValue() &&
9468       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9469     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9470     if (NewSetCC.getNode())
9471       return NewSetCC;
9472   }
9473
9474   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9475   // these.
9476   if (Op1.getOpcode() == ISD::Constant &&
9477       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9478        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9479       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9480
9481     // If the input is a setcc, then reuse the input setcc or use a new one with
9482     // the inverted condition.
9483     if (Op0.getOpcode() == X86ISD::SETCC) {
9484       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9485       bool Invert = (CC == ISD::SETNE) ^
9486         cast<ConstantSDNode>(Op1)->isNullValue();
9487       if (!Invert) return Op0;
9488
9489       CCode = X86::GetOppositeBranchCondition(CCode);
9490       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9491                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9492     }
9493   }
9494
9495   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9496   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9497   if (X86CC == X86::COND_INVALID)
9498     return SDValue();
9499
9500   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9501   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9502   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9503                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9504 }
9505
9506 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9507 static bool isX86LogicalCmp(SDValue Op) {
9508   unsigned Opc = Op.getNode()->getOpcode();
9509   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9510       Opc == X86ISD::SAHF)
9511     return true;
9512   if (Op.getResNo() == 1 &&
9513       (Opc == X86ISD::ADD ||
9514        Opc == X86ISD::SUB ||
9515        Opc == X86ISD::ADC ||
9516        Opc == X86ISD::SBB ||
9517        Opc == X86ISD::SMUL ||
9518        Opc == X86ISD::UMUL ||
9519        Opc == X86ISD::INC ||
9520        Opc == X86ISD::DEC ||
9521        Opc == X86ISD::OR ||
9522        Opc == X86ISD::XOR ||
9523        Opc == X86ISD::AND))
9524     return true;
9525
9526   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9527     return true;
9528
9529   return false;
9530 }
9531
9532 static bool isZero(SDValue V) {
9533   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9534   return C && C->isNullValue();
9535 }
9536
9537 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9538   if (V.getOpcode() != ISD::TRUNCATE)
9539     return false;
9540
9541   SDValue VOp0 = V.getOperand(0);
9542   unsigned InBits = VOp0.getValueSizeInBits();
9543   unsigned Bits = V.getValueSizeInBits();
9544   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9545 }
9546
9547 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9548   bool addTest = true;
9549   SDValue Cond  = Op.getOperand(0);
9550   SDValue Op1 = Op.getOperand(1);
9551   SDValue Op2 = Op.getOperand(2);
9552   DebugLoc DL = Op.getDebugLoc();
9553   SDValue CC;
9554
9555   if (Cond.getOpcode() == ISD::SETCC) {
9556     SDValue NewCond = LowerSETCC(Cond, DAG);
9557     if (NewCond.getNode())
9558       Cond = NewCond;
9559   }
9560
9561   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9562   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9563   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9564   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9565   if (Cond.getOpcode() == X86ISD::SETCC &&
9566       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9567       isZero(Cond.getOperand(1).getOperand(1))) {
9568     SDValue Cmp = Cond.getOperand(1);
9569
9570     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9571
9572     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9573         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9574       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9575
9576       SDValue CmpOp0 = Cmp.getOperand(0);
9577       // Apply further optimizations for special cases
9578       // (select (x != 0), -1, 0) -> neg & sbb
9579       // (select (x == 0), 0, -1) -> neg & sbb
9580       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9581         if (YC->isNullValue() &&
9582             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9583           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9584           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9585                                     DAG.getConstant(0, CmpOp0.getValueType()),
9586                                     CmpOp0);
9587           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9588                                     DAG.getConstant(X86::COND_B, MVT::i8),
9589                                     SDValue(Neg.getNode(), 1));
9590           return Res;
9591         }
9592
9593       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9594                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9595       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9596
9597       SDValue Res =   // Res = 0 or -1.
9598         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9599                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9600
9601       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9602         Res = DAG.getNOT(DL, Res, Res.getValueType());
9603
9604       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9605       if (N2C == 0 || !N2C->isNullValue())
9606         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9607       return Res;
9608     }
9609   }
9610
9611   // Look past (and (setcc_carry (cmp ...)), 1).
9612   if (Cond.getOpcode() == ISD::AND &&
9613       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9614     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9615     if (C && C->getAPIntValue() == 1)
9616       Cond = Cond.getOperand(0);
9617   }
9618
9619   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9620   // setting operand in place of the X86ISD::SETCC.
9621   unsigned CondOpcode = Cond.getOpcode();
9622   if (CondOpcode == X86ISD::SETCC ||
9623       CondOpcode == X86ISD::SETCC_CARRY) {
9624     CC = Cond.getOperand(0);
9625
9626     SDValue Cmp = Cond.getOperand(1);
9627     unsigned Opc = Cmp.getOpcode();
9628     MVT VT = Op.getValueType().getSimpleVT();
9629
9630     bool IllegalFPCMov = false;
9631     if (VT.isFloatingPoint() && !VT.isVector() &&
9632         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9633       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9634
9635     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9636         Opc == X86ISD::BT) { // FIXME
9637       Cond = Cmp;
9638       addTest = false;
9639     }
9640   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9641              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9642              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9643               Cond.getOperand(0).getValueType() != MVT::i8)) {
9644     SDValue LHS = Cond.getOperand(0);
9645     SDValue RHS = Cond.getOperand(1);
9646     unsigned X86Opcode;
9647     unsigned X86Cond;
9648     SDVTList VTs;
9649     switch (CondOpcode) {
9650     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9651     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9652     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9653     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9654     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9655     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9656     default: llvm_unreachable("unexpected overflowing operator");
9657     }
9658     if (CondOpcode == ISD::UMULO)
9659       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9660                           MVT::i32);
9661     else
9662       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9663
9664     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9665
9666     if (CondOpcode == ISD::UMULO)
9667       Cond = X86Op.getValue(2);
9668     else
9669       Cond = X86Op.getValue(1);
9670
9671     CC = DAG.getConstant(X86Cond, MVT::i8);
9672     addTest = false;
9673   }
9674
9675   if (addTest) {
9676     // Look pass the truncate if the high bits are known zero.
9677     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9678         Cond = Cond.getOperand(0);
9679
9680     // We know the result of AND is compared against zero. Try to match
9681     // it to BT.
9682     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9683       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9684       if (NewSetCC.getNode()) {
9685         CC = NewSetCC.getOperand(0);
9686         Cond = NewSetCC.getOperand(1);
9687         addTest = false;
9688       }
9689     }
9690   }
9691
9692   if (addTest) {
9693     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9694     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9695   }
9696
9697   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9698   // a <  b ?  0 : -1 -> RES = setcc_carry
9699   // a >= b ? -1 :  0 -> RES = setcc_carry
9700   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9701   if (Cond.getOpcode() == X86ISD::SUB) {
9702     Cond = ConvertCmpIfNecessary(Cond, DAG);
9703     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9704
9705     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9706         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9707       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9708                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9709       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9710         return DAG.getNOT(DL, Res, Res.getValueType());
9711       return Res;
9712     }
9713   }
9714
9715   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9716   // widen the cmov and push the truncate through. This avoids introducing a new
9717   // branch during isel and doesn't add any extensions.
9718   if (Op.getValueType() == MVT::i8 &&
9719       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9720     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9721     if (T1.getValueType() == T2.getValueType() &&
9722         // Blacklist CopyFromReg to avoid partial register stalls.
9723         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9724       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9725       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9726       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9727     }
9728   }
9729
9730   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9731   // condition is true.
9732   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9733   SDValue Ops[] = { Op2, Op1, CC, Cond };
9734   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9735 }
9736
9737 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9738                                             SelectionDAG &DAG) const {
9739   MVT VT = Op->getValueType(0).getSimpleVT();
9740   SDValue In = Op->getOperand(0);
9741   MVT InVT = In.getValueType().getSimpleVT();
9742   DebugLoc dl = Op->getDebugLoc();
9743
9744   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9745       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9746     return SDValue();
9747
9748   if (Subtarget->hasInt256())
9749     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9750
9751   // Optimize vectors in AVX mode
9752   // Sign extend  v8i16 to v8i32 and
9753   //              v4i32 to v4i64
9754   //
9755   // Divide input vector into two parts
9756   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9757   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9758   // concat the vectors to original VT
9759
9760   unsigned NumElems = InVT.getVectorNumElements();
9761   SDValue Undef = DAG.getUNDEF(InVT);
9762
9763   SmallVector<int,8> ShufMask1(NumElems, -1);
9764   for (unsigned i = 0; i != NumElems/2; ++i)
9765     ShufMask1[i] = i;
9766
9767   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9768
9769   SmallVector<int,8> ShufMask2(NumElems, -1);
9770   for (unsigned i = 0; i != NumElems/2; ++i)
9771     ShufMask2[i] = i + NumElems/2;
9772
9773   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9774
9775   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9776                                 VT.getVectorNumElements()/2);
9777
9778   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9779   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9780
9781   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9782 }
9783
9784 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9785 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9786 // from the AND / OR.
9787 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9788   Opc = Op.getOpcode();
9789   if (Opc != ISD::OR && Opc != ISD::AND)
9790     return false;
9791   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9792           Op.getOperand(0).hasOneUse() &&
9793           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9794           Op.getOperand(1).hasOneUse());
9795 }
9796
9797 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9798 // 1 and that the SETCC node has a single use.
9799 static bool isXor1OfSetCC(SDValue Op) {
9800   if (Op.getOpcode() != ISD::XOR)
9801     return false;
9802   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9803   if (N1C && N1C->getAPIntValue() == 1) {
9804     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9805       Op.getOperand(0).hasOneUse();
9806   }
9807   return false;
9808 }
9809
9810 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9811   bool addTest = true;
9812   SDValue Chain = Op.getOperand(0);
9813   SDValue Cond  = Op.getOperand(1);
9814   SDValue Dest  = Op.getOperand(2);
9815   DebugLoc dl = Op.getDebugLoc();
9816   SDValue CC;
9817   bool Inverted = false;
9818
9819   if (Cond.getOpcode() == ISD::SETCC) {
9820     // Check for setcc([su]{add,sub,mul}o == 0).
9821     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9822         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9823         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9824         Cond.getOperand(0).getResNo() == 1 &&
9825         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9826          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9827          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9828          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9829          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9830          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9831       Inverted = true;
9832       Cond = Cond.getOperand(0);
9833     } else {
9834       SDValue NewCond = LowerSETCC(Cond, DAG);
9835       if (NewCond.getNode())
9836         Cond = NewCond;
9837     }
9838   }
9839 #if 0
9840   // FIXME: LowerXALUO doesn't handle these!!
9841   else if (Cond.getOpcode() == X86ISD::ADD  ||
9842            Cond.getOpcode() == X86ISD::SUB  ||
9843            Cond.getOpcode() == X86ISD::SMUL ||
9844            Cond.getOpcode() == X86ISD::UMUL)
9845     Cond = LowerXALUO(Cond, DAG);
9846 #endif
9847
9848   // Look pass (and (setcc_carry (cmp ...)), 1).
9849   if (Cond.getOpcode() == ISD::AND &&
9850       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9851     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9852     if (C && C->getAPIntValue() == 1)
9853       Cond = Cond.getOperand(0);
9854   }
9855
9856   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9857   // setting operand in place of the X86ISD::SETCC.
9858   unsigned CondOpcode = Cond.getOpcode();
9859   if (CondOpcode == X86ISD::SETCC ||
9860       CondOpcode == X86ISD::SETCC_CARRY) {
9861     CC = Cond.getOperand(0);
9862
9863     SDValue Cmp = Cond.getOperand(1);
9864     unsigned Opc = Cmp.getOpcode();
9865     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9866     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9867       Cond = Cmp;
9868       addTest = false;
9869     } else {
9870       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9871       default: break;
9872       case X86::COND_O:
9873       case X86::COND_B:
9874         // These can only come from an arithmetic instruction with overflow,
9875         // e.g. SADDO, UADDO.
9876         Cond = Cond.getNode()->getOperand(1);
9877         addTest = false;
9878         break;
9879       }
9880     }
9881   }
9882   CondOpcode = Cond.getOpcode();
9883   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9884       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9885       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9886        Cond.getOperand(0).getValueType() != MVT::i8)) {
9887     SDValue LHS = Cond.getOperand(0);
9888     SDValue RHS = Cond.getOperand(1);
9889     unsigned X86Opcode;
9890     unsigned X86Cond;
9891     SDVTList VTs;
9892     switch (CondOpcode) {
9893     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9894     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9895     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9896     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9897     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9898     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9899     default: llvm_unreachable("unexpected overflowing operator");
9900     }
9901     if (Inverted)
9902       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9903     if (CondOpcode == ISD::UMULO)
9904       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9905                           MVT::i32);
9906     else
9907       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9908
9909     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9910
9911     if (CondOpcode == ISD::UMULO)
9912       Cond = X86Op.getValue(2);
9913     else
9914       Cond = X86Op.getValue(1);
9915
9916     CC = DAG.getConstant(X86Cond, MVT::i8);
9917     addTest = false;
9918   } else {
9919     unsigned CondOpc;
9920     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9921       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9922       if (CondOpc == ISD::OR) {
9923         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9924         // two branches instead of an explicit OR instruction with a
9925         // separate test.
9926         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9927             isX86LogicalCmp(Cmp)) {
9928           CC = Cond.getOperand(0).getOperand(0);
9929           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9930                               Chain, Dest, CC, Cmp);
9931           CC = Cond.getOperand(1).getOperand(0);
9932           Cond = Cmp;
9933           addTest = false;
9934         }
9935       } else { // ISD::AND
9936         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9937         // two branches instead of an explicit AND instruction with a
9938         // separate test. However, we only do this if this block doesn't
9939         // have a fall-through edge, because this requires an explicit
9940         // jmp when the condition is false.
9941         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9942             isX86LogicalCmp(Cmp) &&
9943             Op.getNode()->hasOneUse()) {
9944           X86::CondCode CCode =
9945             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9946           CCode = X86::GetOppositeBranchCondition(CCode);
9947           CC = DAG.getConstant(CCode, MVT::i8);
9948           SDNode *User = *Op.getNode()->use_begin();
9949           // Look for an unconditional branch following this conditional branch.
9950           // We need this because we need to reverse the successors in order
9951           // to implement FCMP_OEQ.
9952           if (User->getOpcode() == ISD::BR) {
9953             SDValue FalseBB = User->getOperand(1);
9954             SDNode *NewBR =
9955               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9956             assert(NewBR == User);
9957             (void)NewBR;
9958             Dest = FalseBB;
9959
9960             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9961                                 Chain, Dest, CC, Cmp);
9962             X86::CondCode CCode =
9963               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9964             CCode = X86::GetOppositeBranchCondition(CCode);
9965             CC = DAG.getConstant(CCode, MVT::i8);
9966             Cond = Cmp;
9967             addTest = false;
9968           }
9969         }
9970       }
9971     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9972       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9973       // It should be transformed during dag combiner except when the condition
9974       // is set by a arithmetics with overflow node.
9975       X86::CondCode CCode =
9976         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9977       CCode = X86::GetOppositeBranchCondition(CCode);
9978       CC = DAG.getConstant(CCode, MVT::i8);
9979       Cond = Cond.getOperand(0).getOperand(1);
9980       addTest = false;
9981     } else if (Cond.getOpcode() == ISD::SETCC &&
9982                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9983       // For FCMP_OEQ, we can emit
9984       // two branches instead of an explicit AND instruction with a
9985       // separate test. However, we only do this if this block doesn't
9986       // have a fall-through edge, because this requires an explicit
9987       // jmp when the condition is false.
9988       if (Op.getNode()->hasOneUse()) {
9989         SDNode *User = *Op.getNode()->use_begin();
9990         // Look for an unconditional branch following this conditional branch.
9991         // We need this because we need to reverse the successors in order
9992         // to implement FCMP_OEQ.
9993         if (User->getOpcode() == ISD::BR) {
9994           SDValue FalseBB = User->getOperand(1);
9995           SDNode *NewBR =
9996             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9997           assert(NewBR == User);
9998           (void)NewBR;
9999           Dest = FalseBB;
10000
10001           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10002                                     Cond.getOperand(0), Cond.getOperand(1));
10003           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10004           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10005           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10006                               Chain, Dest, CC, Cmp);
10007           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10008           Cond = Cmp;
10009           addTest = false;
10010         }
10011       }
10012     } else if (Cond.getOpcode() == ISD::SETCC &&
10013                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10014       // For FCMP_UNE, we can emit
10015       // two branches instead of an explicit AND instruction with a
10016       // separate test. However, we only do this if this block doesn't
10017       // have a fall-through edge, because this requires an explicit
10018       // jmp when the condition is false.
10019       if (Op.getNode()->hasOneUse()) {
10020         SDNode *User = *Op.getNode()->use_begin();
10021         // Look for an unconditional branch following this conditional branch.
10022         // We need this because we need to reverse the successors in order
10023         // to implement FCMP_UNE.
10024         if (User->getOpcode() == ISD::BR) {
10025           SDValue FalseBB = User->getOperand(1);
10026           SDNode *NewBR =
10027             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10028           assert(NewBR == User);
10029           (void)NewBR;
10030
10031           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10032                                     Cond.getOperand(0), Cond.getOperand(1));
10033           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10034           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10035           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10036                               Chain, Dest, CC, Cmp);
10037           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10038           Cond = Cmp;
10039           addTest = false;
10040           Dest = FalseBB;
10041         }
10042       }
10043     }
10044   }
10045
10046   if (addTest) {
10047     // Look pass the truncate if the high bits are known zero.
10048     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10049         Cond = Cond.getOperand(0);
10050
10051     // We know the result of AND is compared against zero. Try to match
10052     // it to BT.
10053     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10054       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10055       if (NewSetCC.getNode()) {
10056         CC = NewSetCC.getOperand(0);
10057         Cond = NewSetCC.getOperand(1);
10058         addTest = false;
10059       }
10060     }
10061   }
10062
10063   if (addTest) {
10064     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10065     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10066   }
10067   Cond = ConvertCmpIfNecessary(Cond, DAG);
10068   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10069                      Chain, Dest, CC, Cond);
10070 }
10071
10072 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10073 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10074 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10075 // that the guard pages used by the OS virtual memory manager are allocated in
10076 // correct sequence.
10077 SDValue
10078 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10079                                            SelectionDAG &DAG) const {
10080   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10081           getTargetMachine().Options.EnableSegmentedStacks) &&
10082          "This should be used only on Windows targets or when segmented stacks "
10083          "are being used");
10084   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10085   DebugLoc dl = Op.getDebugLoc();
10086
10087   // Get the inputs.
10088   SDValue Chain = Op.getOperand(0);
10089   SDValue Size  = Op.getOperand(1);
10090   // FIXME: Ensure alignment here
10091
10092   bool Is64Bit = Subtarget->is64Bit();
10093   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10094
10095   if (getTargetMachine().Options.EnableSegmentedStacks) {
10096     MachineFunction &MF = DAG.getMachineFunction();
10097     MachineRegisterInfo &MRI = MF.getRegInfo();
10098
10099     if (Is64Bit) {
10100       // The 64 bit implementation of segmented stacks needs to clobber both r10
10101       // r11. This makes it impossible to use it along with nested parameters.
10102       const Function *F = MF.getFunction();
10103
10104       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10105            I != E; ++I)
10106         if (I->hasNestAttr())
10107           report_fatal_error("Cannot use segmented stacks with functions that "
10108                              "have nested arguments.");
10109     }
10110
10111     const TargetRegisterClass *AddrRegClass =
10112       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10113     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10114     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10115     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10116                                 DAG.getRegister(Vreg, SPTy));
10117     SDValue Ops1[2] = { Value, Chain };
10118     return DAG.getMergeValues(Ops1, 2, dl);
10119   } else {
10120     SDValue Flag;
10121     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10122
10123     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10124     Flag = Chain.getValue(1);
10125     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10126
10127     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10128     Flag = Chain.getValue(1);
10129
10130     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10131                                SPTy).getValue(1);
10132
10133     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10134     return DAG.getMergeValues(Ops1, 2, dl);
10135   }
10136 }
10137
10138 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10139   MachineFunction &MF = DAG.getMachineFunction();
10140   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10141
10142   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10143   DebugLoc DL = Op.getDebugLoc();
10144
10145   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10146     // vastart just stores the address of the VarArgsFrameIndex slot into the
10147     // memory location argument.
10148     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10149                                    getPointerTy());
10150     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10151                         MachinePointerInfo(SV), false, false, 0);
10152   }
10153
10154   // __va_list_tag:
10155   //   gp_offset         (0 - 6 * 8)
10156   //   fp_offset         (48 - 48 + 8 * 16)
10157   //   overflow_arg_area (point to parameters coming in memory).
10158   //   reg_save_area
10159   SmallVector<SDValue, 8> MemOps;
10160   SDValue FIN = Op.getOperand(1);
10161   // Store gp_offset
10162   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10163                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10164                                                MVT::i32),
10165                                FIN, MachinePointerInfo(SV), false, false, 0);
10166   MemOps.push_back(Store);
10167
10168   // Store fp_offset
10169   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10170                     FIN, DAG.getIntPtrConstant(4));
10171   Store = DAG.getStore(Op.getOperand(0), DL,
10172                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10173                                        MVT::i32),
10174                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10175   MemOps.push_back(Store);
10176
10177   // Store ptr to overflow_arg_area
10178   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10179                     FIN, DAG.getIntPtrConstant(4));
10180   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10181                                     getPointerTy());
10182   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10183                        MachinePointerInfo(SV, 8),
10184                        false, false, 0);
10185   MemOps.push_back(Store);
10186
10187   // Store ptr to reg_save_area.
10188   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10189                     FIN, DAG.getIntPtrConstant(8));
10190   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10191                                     getPointerTy());
10192   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10193                        MachinePointerInfo(SV, 16), false, false, 0);
10194   MemOps.push_back(Store);
10195   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10196                      &MemOps[0], MemOps.size());
10197 }
10198
10199 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10200   assert(Subtarget->is64Bit() &&
10201          "LowerVAARG only handles 64-bit va_arg!");
10202   assert((Subtarget->isTargetLinux() ||
10203           Subtarget->isTargetDarwin()) &&
10204           "Unhandled target in LowerVAARG");
10205   assert(Op.getNode()->getNumOperands() == 4);
10206   SDValue Chain = Op.getOperand(0);
10207   SDValue SrcPtr = Op.getOperand(1);
10208   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10209   unsigned Align = Op.getConstantOperandVal(3);
10210   DebugLoc dl = Op.getDebugLoc();
10211
10212   EVT ArgVT = Op.getNode()->getValueType(0);
10213   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10214   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10215   uint8_t ArgMode;
10216
10217   // Decide which area this value should be read from.
10218   // TODO: Implement the AMD64 ABI in its entirety. This simple
10219   // selection mechanism works only for the basic types.
10220   if (ArgVT == MVT::f80) {
10221     llvm_unreachable("va_arg for f80 not yet implemented");
10222   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10223     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10224   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10225     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10226   } else {
10227     llvm_unreachable("Unhandled argument type in LowerVAARG");
10228   }
10229
10230   if (ArgMode == 2) {
10231     // Sanity Check: Make sure using fp_offset makes sense.
10232     assert(!getTargetMachine().Options.UseSoftFloat &&
10233            !(DAG.getMachineFunction()
10234                 .getFunction()->getAttributes()
10235                 .hasAttribute(AttributeSet::FunctionIndex,
10236                               Attribute::NoImplicitFloat)) &&
10237            Subtarget->hasSSE1());
10238   }
10239
10240   // Insert VAARG_64 node into the DAG
10241   // VAARG_64 returns two values: Variable Argument Address, Chain
10242   SmallVector<SDValue, 11> InstOps;
10243   InstOps.push_back(Chain);
10244   InstOps.push_back(SrcPtr);
10245   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10246   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10247   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10248   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10249   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10250                                           VTs, &InstOps[0], InstOps.size(),
10251                                           MVT::i64,
10252                                           MachinePointerInfo(SV),
10253                                           /*Align=*/0,
10254                                           /*Volatile=*/false,
10255                                           /*ReadMem=*/true,
10256                                           /*WriteMem=*/true);
10257   Chain = VAARG.getValue(1);
10258
10259   // Load the next argument and return it
10260   return DAG.getLoad(ArgVT, dl,
10261                      Chain,
10262                      VAARG,
10263                      MachinePointerInfo(),
10264                      false, false, false, 0);
10265 }
10266
10267 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10268                            SelectionDAG &DAG) {
10269   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10270   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10271   SDValue Chain = Op.getOperand(0);
10272   SDValue DstPtr = Op.getOperand(1);
10273   SDValue SrcPtr = Op.getOperand(2);
10274   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10275   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10276   DebugLoc DL = Op.getDebugLoc();
10277
10278   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10279                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10280                        false,
10281                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10282 }
10283
10284 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10285 // may or may not be a constant. Takes immediate version of shift as input.
10286 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10287                                    SDValue SrcOp, SDValue ShAmt,
10288                                    SelectionDAG &DAG) {
10289   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10290
10291   if (isa<ConstantSDNode>(ShAmt)) {
10292     // Constant may be a TargetConstant. Use a regular constant.
10293     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10294     switch (Opc) {
10295       default: llvm_unreachable("Unknown target vector shift node");
10296       case X86ISD::VSHLI:
10297       case X86ISD::VSRLI:
10298       case X86ISD::VSRAI:
10299         return DAG.getNode(Opc, dl, VT, SrcOp,
10300                            DAG.getConstant(ShiftAmt, MVT::i32));
10301     }
10302   }
10303
10304   // Change opcode to non-immediate version
10305   switch (Opc) {
10306     default: llvm_unreachable("Unknown target vector shift node");
10307     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10308     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10309     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10310   }
10311
10312   // Need to build a vector containing shift amount
10313   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10314   SDValue ShOps[4];
10315   ShOps[0] = ShAmt;
10316   ShOps[1] = DAG.getConstant(0, MVT::i32);
10317   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10318   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10319
10320   // The return type has to be a 128-bit type with the same element
10321   // type as the input type.
10322   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10323   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10324
10325   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10326   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10327 }
10328
10329 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10330   DebugLoc dl = Op.getDebugLoc();
10331   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10332   switch (IntNo) {
10333   default: return SDValue();    // Don't custom lower most intrinsics.
10334   // Comparison intrinsics.
10335   case Intrinsic::x86_sse_comieq_ss:
10336   case Intrinsic::x86_sse_comilt_ss:
10337   case Intrinsic::x86_sse_comile_ss:
10338   case Intrinsic::x86_sse_comigt_ss:
10339   case Intrinsic::x86_sse_comige_ss:
10340   case Intrinsic::x86_sse_comineq_ss:
10341   case Intrinsic::x86_sse_ucomieq_ss:
10342   case Intrinsic::x86_sse_ucomilt_ss:
10343   case Intrinsic::x86_sse_ucomile_ss:
10344   case Intrinsic::x86_sse_ucomigt_ss:
10345   case Intrinsic::x86_sse_ucomige_ss:
10346   case Intrinsic::x86_sse_ucomineq_ss:
10347   case Intrinsic::x86_sse2_comieq_sd:
10348   case Intrinsic::x86_sse2_comilt_sd:
10349   case Intrinsic::x86_sse2_comile_sd:
10350   case Intrinsic::x86_sse2_comigt_sd:
10351   case Intrinsic::x86_sse2_comige_sd:
10352   case Intrinsic::x86_sse2_comineq_sd:
10353   case Intrinsic::x86_sse2_ucomieq_sd:
10354   case Intrinsic::x86_sse2_ucomilt_sd:
10355   case Intrinsic::x86_sse2_ucomile_sd:
10356   case Intrinsic::x86_sse2_ucomigt_sd:
10357   case Intrinsic::x86_sse2_ucomige_sd:
10358   case Intrinsic::x86_sse2_ucomineq_sd: {
10359     unsigned Opc;
10360     ISD::CondCode CC;
10361     switch (IntNo) {
10362     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10363     case Intrinsic::x86_sse_comieq_ss:
10364     case Intrinsic::x86_sse2_comieq_sd:
10365       Opc = X86ISD::COMI;
10366       CC = ISD::SETEQ;
10367       break;
10368     case Intrinsic::x86_sse_comilt_ss:
10369     case Intrinsic::x86_sse2_comilt_sd:
10370       Opc = X86ISD::COMI;
10371       CC = ISD::SETLT;
10372       break;
10373     case Intrinsic::x86_sse_comile_ss:
10374     case Intrinsic::x86_sse2_comile_sd:
10375       Opc = X86ISD::COMI;
10376       CC = ISD::SETLE;
10377       break;
10378     case Intrinsic::x86_sse_comigt_ss:
10379     case Intrinsic::x86_sse2_comigt_sd:
10380       Opc = X86ISD::COMI;
10381       CC = ISD::SETGT;
10382       break;
10383     case Intrinsic::x86_sse_comige_ss:
10384     case Intrinsic::x86_sse2_comige_sd:
10385       Opc = X86ISD::COMI;
10386       CC = ISD::SETGE;
10387       break;
10388     case Intrinsic::x86_sse_comineq_ss:
10389     case Intrinsic::x86_sse2_comineq_sd:
10390       Opc = X86ISD::COMI;
10391       CC = ISD::SETNE;
10392       break;
10393     case Intrinsic::x86_sse_ucomieq_ss:
10394     case Intrinsic::x86_sse2_ucomieq_sd:
10395       Opc = X86ISD::UCOMI;
10396       CC = ISD::SETEQ;
10397       break;
10398     case Intrinsic::x86_sse_ucomilt_ss:
10399     case Intrinsic::x86_sse2_ucomilt_sd:
10400       Opc = X86ISD::UCOMI;
10401       CC = ISD::SETLT;
10402       break;
10403     case Intrinsic::x86_sse_ucomile_ss:
10404     case Intrinsic::x86_sse2_ucomile_sd:
10405       Opc = X86ISD::UCOMI;
10406       CC = ISD::SETLE;
10407       break;
10408     case Intrinsic::x86_sse_ucomigt_ss:
10409     case Intrinsic::x86_sse2_ucomigt_sd:
10410       Opc = X86ISD::UCOMI;
10411       CC = ISD::SETGT;
10412       break;
10413     case Intrinsic::x86_sse_ucomige_ss:
10414     case Intrinsic::x86_sse2_ucomige_sd:
10415       Opc = X86ISD::UCOMI;
10416       CC = ISD::SETGE;
10417       break;
10418     case Intrinsic::x86_sse_ucomineq_ss:
10419     case Intrinsic::x86_sse2_ucomineq_sd:
10420       Opc = X86ISD::UCOMI;
10421       CC = ISD::SETNE;
10422       break;
10423     }
10424
10425     SDValue LHS = Op.getOperand(1);
10426     SDValue RHS = Op.getOperand(2);
10427     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10428     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10429     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10430     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10431                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10432     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10433   }
10434
10435   // Arithmetic intrinsics.
10436   case Intrinsic::x86_sse2_pmulu_dq:
10437   case Intrinsic::x86_avx2_pmulu_dq:
10438     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10439                        Op.getOperand(1), Op.getOperand(2));
10440
10441   // SSE2/AVX2 sub with unsigned saturation intrinsics
10442   case Intrinsic::x86_sse2_psubus_b:
10443   case Intrinsic::x86_sse2_psubus_w:
10444   case Intrinsic::x86_avx2_psubus_b:
10445   case Intrinsic::x86_avx2_psubus_w:
10446     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10447                        Op.getOperand(1), Op.getOperand(2));
10448
10449   // SSE3/AVX horizontal add/sub intrinsics
10450   case Intrinsic::x86_sse3_hadd_ps:
10451   case Intrinsic::x86_sse3_hadd_pd:
10452   case Intrinsic::x86_avx_hadd_ps_256:
10453   case Intrinsic::x86_avx_hadd_pd_256:
10454   case Intrinsic::x86_sse3_hsub_ps:
10455   case Intrinsic::x86_sse3_hsub_pd:
10456   case Intrinsic::x86_avx_hsub_ps_256:
10457   case Intrinsic::x86_avx_hsub_pd_256:
10458   case Intrinsic::x86_ssse3_phadd_w_128:
10459   case Intrinsic::x86_ssse3_phadd_d_128:
10460   case Intrinsic::x86_avx2_phadd_w:
10461   case Intrinsic::x86_avx2_phadd_d:
10462   case Intrinsic::x86_ssse3_phsub_w_128:
10463   case Intrinsic::x86_ssse3_phsub_d_128:
10464   case Intrinsic::x86_avx2_phsub_w:
10465   case Intrinsic::x86_avx2_phsub_d: {
10466     unsigned Opcode;
10467     switch (IntNo) {
10468     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10469     case Intrinsic::x86_sse3_hadd_ps:
10470     case Intrinsic::x86_sse3_hadd_pd:
10471     case Intrinsic::x86_avx_hadd_ps_256:
10472     case Intrinsic::x86_avx_hadd_pd_256:
10473       Opcode = X86ISD::FHADD;
10474       break;
10475     case Intrinsic::x86_sse3_hsub_ps:
10476     case Intrinsic::x86_sse3_hsub_pd:
10477     case Intrinsic::x86_avx_hsub_ps_256:
10478     case Intrinsic::x86_avx_hsub_pd_256:
10479       Opcode = X86ISD::FHSUB;
10480       break;
10481     case Intrinsic::x86_ssse3_phadd_w_128:
10482     case Intrinsic::x86_ssse3_phadd_d_128:
10483     case Intrinsic::x86_avx2_phadd_w:
10484     case Intrinsic::x86_avx2_phadd_d:
10485       Opcode = X86ISD::HADD;
10486       break;
10487     case Intrinsic::x86_ssse3_phsub_w_128:
10488     case Intrinsic::x86_ssse3_phsub_d_128:
10489     case Intrinsic::x86_avx2_phsub_w:
10490     case Intrinsic::x86_avx2_phsub_d:
10491       Opcode = X86ISD::HSUB;
10492       break;
10493     }
10494     return DAG.getNode(Opcode, dl, Op.getValueType(),
10495                        Op.getOperand(1), Op.getOperand(2));
10496   }
10497
10498   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10499   case Intrinsic::x86_sse2_pmaxu_b:
10500   case Intrinsic::x86_sse41_pmaxuw:
10501   case Intrinsic::x86_sse41_pmaxud:
10502   case Intrinsic::x86_avx2_pmaxu_b:
10503   case Intrinsic::x86_avx2_pmaxu_w:
10504   case Intrinsic::x86_avx2_pmaxu_d:
10505   case Intrinsic::x86_sse2_pminu_b:
10506   case Intrinsic::x86_sse41_pminuw:
10507   case Intrinsic::x86_sse41_pminud:
10508   case Intrinsic::x86_avx2_pminu_b:
10509   case Intrinsic::x86_avx2_pminu_w:
10510   case Intrinsic::x86_avx2_pminu_d:
10511   case Intrinsic::x86_sse41_pmaxsb:
10512   case Intrinsic::x86_sse2_pmaxs_w:
10513   case Intrinsic::x86_sse41_pmaxsd:
10514   case Intrinsic::x86_avx2_pmaxs_b:
10515   case Intrinsic::x86_avx2_pmaxs_w:
10516   case Intrinsic::x86_avx2_pmaxs_d:
10517   case Intrinsic::x86_sse41_pminsb:
10518   case Intrinsic::x86_sse2_pmins_w:
10519   case Intrinsic::x86_sse41_pminsd:
10520   case Intrinsic::x86_avx2_pmins_b:
10521   case Intrinsic::x86_avx2_pmins_w:
10522   case Intrinsic::x86_avx2_pmins_d: {
10523     unsigned Opcode;
10524     switch (IntNo) {
10525     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10526     case Intrinsic::x86_sse2_pmaxu_b:
10527     case Intrinsic::x86_sse41_pmaxuw:
10528     case Intrinsic::x86_sse41_pmaxud:
10529     case Intrinsic::x86_avx2_pmaxu_b:
10530     case Intrinsic::x86_avx2_pmaxu_w:
10531     case Intrinsic::x86_avx2_pmaxu_d:
10532       Opcode = X86ISD::UMAX;
10533       break;
10534     case Intrinsic::x86_sse2_pminu_b:
10535     case Intrinsic::x86_sse41_pminuw:
10536     case Intrinsic::x86_sse41_pminud:
10537     case Intrinsic::x86_avx2_pminu_b:
10538     case Intrinsic::x86_avx2_pminu_w:
10539     case Intrinsic::x86_avx2_pminu_d:
10540       Opcode = X86ISD::UMIN;
10541       break;
10542     case Intrinsic::x86_sse41_pmaxsb:
10543     case Intrinsic::x86_sse2_pmaxs_w:
10544     case Intrinsic::x86_sse41_pmaxsd:
10545     case Intrinsic::x86_avx2_pmaxs_b:
10546     case Intrinsic::x86_avx2_pmaxs_w:
10547     case Intrinsic::x86_avx2_pmaxs_d:
10548       Opcode = X86ISD::SMAX;
10549       break;
10550     case Intrinsic::x86_sse41_pminsb:
10551     case Intrinsic::x86_sse2_pmins_w:
10552     case Intrinsic::x86_sse41_pminsd:
10553     case Intrinsic::x86_avx2_pmins_b:
10554     case Intrinsic::x86_avx2_pmins_w:
10555     case Intrinsic::x86_avx2_pmins_d:
10556       Opcode = X86ISD::SMIN;
10557       break;
10558     }
10559     return DAG.getNode(Opcode, dl, Op.getValueType(),
10560                        Op.getOperand(1), Op.getOperand(2));
10561   }
10562
10563   // SSE/SSE2/AVX floating point max/min intrinsics.
10564   case Intrinsic::x86_sse_max_ps:
10565   case Intrinsic::x86_sse2_max_pd:
10566   case Intrinsic::x86_avx_max_ps_256:
10567   case Intrinsic::x86_avx_max_pd_256:
10568   case Intrinsic::x86_sse_min_ps:
10569   case Intrinsic::x86_sse2_min_pd:
10570   case Intrinsic::x86_avx_min_ps_256:
10571   case Intrinsic::x86_avx_min_pd_256: {
10572     unsigned Opcode;
10573     switch (IntNo) {
10574     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10575     case Intrinsic::x86_sse_max_ps:
10576     case Intrinsic::x86_sse2_max_pd:
10577     case Intrinsic::x86_avx_max_ps_256:
10578     case Intrinsic::x86_avx_max_pd_256:
10579       Opcode = X86ISD::FMAX;
10580       break;
10581     case Intrinsic::x86_sse_min_ps:
10582     case Intrinsic::x86_sse2_min_pd:
10583     case Intrinsic::x86_avx_min_ps_256:
10584     case Intrinsic::x86_avx_min_pd_256:
10585       Opcode = X86ISD::FMIN;
10586       break;
10587     }
10588     return DAG.getNode(Opcode, dl, Op.getValueType(),
10589                        Op.getOperand(1), Op.getOperand(2));
10590   }
10591
10592   // AVX2 variable shift intrinsics
10593   case Intrinsic::x86_avx2_psllv_d:
10594   case Intrinsic::x86_avx2_psllv_q:
10595   case Intrinsic::x86_avx2_psllv_d_256:
10596   case Intrinsic::x86_avx2_psllv_q_256:
10597   case Intrinsic::x86_avx2_psrlv_d:
10598   case Intrinsic::x86_avx2_psrlv_q:
10599   case Intrinsic::x86_avx2_psrlv_d_256:
10600   case Intrinsic::x86_avx2_psrlv_q_256:
10601   case Intrinsic::x86_avx2_psrav_d:
10602   case Intrinsic::x86_avx2_psrav_d_256: {
10603     unsigned Opcode;
10604     switch (IntNo) {
10605     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10606     case Intrinsic::x86_avx2_psllv_d:
10607     case Intrinsic::x86_avx2_psllv_q:
10608     case Intrinsic::x86_avx2_psllv_d_256:
10609     case Intrinsic::x86_avx2_psllv_q_256:
10610       Opcode = ISD::SHL;
10611       break;
10612     case Intrinsic::x86_avx2_psrlv_d:
10613     case Intrinsic::x86_avx2_psrlv_q:
10614     case Intrinsic::x86_avx2_psrlv_d_256:
10615     case Intrinsic::x86_avx2_psrlv_q_256:
10616       Opcode = ISD::SRL;
10617       break;
10618     case Intrinsic::x86_avx2_psrav_d:
10619     case Intrinsic::x86_avx2_psrav_d_256:
10620       Opcode = ISD::SRA;
10621       break;
10622     }
10623     return DAG.getNode(Opcode, dl, Op.getValueType(),
10624                        Op.getOperand(1), Op.getOperand(2));
10625   }
10626
10627   case Intrinsic::x86_ssse3_pshuf_b_128:
10628   case Intrinsic::x86_avx2_pshuf_b:
10629     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10630                        Op.getOperand(1), Op.getOperand(2));
10631
10632   case Intrinsic::x86_ssse3_psign_b_128:
10633   case Intrinsic::x86_ssse3_psign_w_128:
10634   case Intrinsic::x86_ssse3_psign_d_128:
10635   case Intrinsic::x86_avx2_psign_b:
10636   case Intrinsic::x86_avx2_psign_w:
10637   case Intrinsic::x86_avx2_psign_d:
10638     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10639                        Op.getOperand(1), Op.getOperand(2));
10640
10641   case Intrinsic::x86_sse41_insertps:
10642     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10643                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10644
10645   case Intrinsic::x86_avx_vperm2f128_ps_256:
10646   case Intrinsic::x86_avx_vperm2f128_pd_256:
10647   case Intrinsic::x86_avx_vperm2f128_si_256:
10648   case Intrinsic::x86_avx2_vperm2i128:
10649     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10650                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10651
10652   case Intrinsic::x86_avx2_permd:
10653   case Intrinsic::x86_avx2_permps:
10654     // Operands intentionally swapped. Mask is last operand to intrinsic,
10655     // but second operand for node/intruction.
10656     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10657                        Op.getOperand(2), Op.getOperand(1));
10658
10659   case Intrinsic::x86_sse_sqrt_ps:
10660   case Intrinsic::x86_sse2_sqrt_pd:
10661   case Intrinsic::x86_avx_sqrt_ps_256:
10662   case Intrinsic::x86_avx_sqrt_pd_256:
10663     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10664
10665   // ptest and testp intrinsics. The intrinsic these come from are designed to
10666   // return an integer value, not just an instruction so lower it to the ptest
10667   // or testp pattern and a setcc for the result.
10668   case Intrinsic::x86_sse41_ptestz:
10669   case Intrinsic::x86_sse41_ptestc:
10670   case Intrinsic::x86_sse41_ptestnzc:
10671   case Intrinsic::x86_avx_ptestz_256:
10672   case Intrinsic::x86_avx_ptestc_256:
10673   case Intrinsic::x86_avx_ptestnzc_256:
10674   case Intrinsic::x86_avx_vtestz_ps:
10675   case Intrinsic::x86_avx_vtestc_ps:
10676   case Intrinsic::x86_avx_vtestnzc_ps:
10677   case Intrinsic::x86_avx_vtestz_pd:
10678   case Intrinsic::x86_avx_vtestc_pd:
10679   case Intrinsic::x86_avx_vtestnzc_pd:
10680   case Intrinsic::x86_avx_vtestz_ps_256:
10681   case Intrinsic::x86_avx_vtestc_ps_256:
10682   case Intrinsic::x86_avx_vtestnzc_ps_256:
10683   case Intrinsic::x86_avx_vtestz_pd_256:
10684   case Intrinsic::x86_avx_vtestc_pd_256:
10685   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10686     bool IsTestPacked = false;
10687     unsigned X86CC;
10688     switch (IntNo) {
10689     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10690     case Intrinsic::x86_avx_vtestz_ps:
10691     case Intrinsic::x86_avx_vtestz_pd:
10692     case Intrinsic::x86_avx_vtestz_ps_256:
10693     case Intrinsic::x86_avx_vtestz_pd_256:
10694       IsTestPacked = true; // Fallthrough
10695     case Intrinsic::x86_sse41_ptestz:
10696     case Intrinsic::x86_avx_ptestz_256:
10697       // ZF = 1
10698       X86CC = X86::COND_E;
10699       break;
10700     case Intrinsic::x86_avx_vtestc_ps:
10701     case Intrinsic::x86_avx_vtestc_pd:
10702     case Intrinsic::x86_avx_vtestc_ps_256:
10703     case Intrinsic::x86_avx_vtestc_pd_256:
10704       IsTestPacked = true; // Fallthrough
10705     case Intrinsic::x86_sse41_ptestc:
10706     case Intrinsic::x86_avx_ptestc_256:
10707       // CF = 1
10708       X86CC = X86::COND_B;
10709       break;
10710     case Intrinsic::x86_avx_vtestnzc_ps:
10711     case Intrinsic::x86_avx_vtestnzc_pd:
10712     case Intrinsic::x86_avx_vtestnzc_ps_256:
10713     case Intrinsic::x86_avx_vtestnzc_pd_256:
10714       IsTestPacked = true; // Fallthrough
10715     case Intrinsic::x86_sse41_ptestnzc:
10716     case Intrinsic::x86_avx_ptestnzc_256:
10717       // ZF and CF = 0
10718       X86CC = X86::COND_A;
10719       break;
10720     }
10721
10722     SDValue LHS = Op.getOperand(1);
10723     SDValue RHS = Op.getOperand(2);
10724     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10725     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10726     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10727     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10728     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10729   }
10730
10731   // SSE/AVX shift intrinsics
10732   case Intrinsic::x86_sse2_psll_w:
10733   case Intrinsic::x86_sse2_psll_d:
10734   case Intrinsic::x86_sse2_psll_q:
10735   case Intrinsic::x86_avx2_psll_w:
10736   case Intrinsic::x86_avx2_psll_d:
10737   case Intrinsic::x86_avx2_psll_q:
10738   case Intrinsic::x86_sse2_psrl_w:
10739   case Intrinsic::x86_sse2_psrl_d:
10740   case Intrinsic::x86_sse2_psrl_q:
10741   case Intrinsic::x86_avx2_psrl_w:
10742   case Intrinsic::x86_avx2_psrl_d:
10743   case Intrinsic::x86_avx2_psrl_q:
10744   case Intrinsic::x86_sse2_psra_w:
10745   case Intrinsic::x86_sse2_psra_d:
10746   case Intrinsic::x86_avx2_psra_w:
10747   case Intrinsic::x86_avx2_psra_d: {
10748     unsigned Opcode;
10749     switch (IntNo) {
10750     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10751     case Intrinsic::x86_sse2_psll_w:
10752     case Intrinsic::x86_sse2_psll_d:
10753     case Intrinsic::x86_sse2_psll_q:
10754     case Intrinsic::x86_avx2_psll_w:
10755     case Intrinsic::x86_avx2_psll_d:
10756     case Intrinsic::x86_avx2_psll_q:
10757       Opcode = X86ISD::VSHL;
10758       break;
10759     case Intrinsic::x86_sse2_psrl_w:
10760     case Intrinsic::x86_sse2_psrl_d:
10761     case Intrinsic::x86_sse2_psrl_q:
10762     case Intrinsic::x86_avx2_psrl_w:
10763     case Intrinsic::x86_avx2_psrl_d:
10764     case Intrinsic::x86_avx2_psrl_q:
10765       Opcode = X86ISD::VSRL;
10766       break;
10767     case Intrinsic::x86_sse2_psra_w:
10768     case Intrinsic::x86_sse2_psra_d:
10769     case Intrinsic::x86_avx2_psra_w:
10770     case Intrinsic::x86_avx2_psra_d:
10771       Opcode = X86ISD::VSRA;
10772       break;
10773     }
10774     return DAG.getNode(Opcode, dl, Op.getValueType(),
10775                        Op.getOperand(1), Op.getOperand(2));
10776   }
10777
10778   // SSE/AVX immediate shift intrinsics
10779   case Intrinsic::x86_sse2_pslli_w:
10780   case Intrinsic::x86_sse2_pslli_d:
10781   case Intrinsic::x86_sse2_pslli_q:
10782   case Intrinsic::x86_avx2_pslli_w:
10783   case Intrinsic::x86_avx2_pslli_d:
10784   case Intrinsic::x86_avx2_pslli_q:
10785   case Intrinsic::x86_sse2_psrli_w:
10786   case Intrinsic::x86_sse2_psrli_d:
10787   case Intrinsic::x86_sse2_psrli_q:
10788   case Intrinsic::x86_avx2_psrli_w:
10789   case Intrinsic::x86_avx2_psrli_d:
10790   case Intrinsic::x86_avx2_psrli_q:
10791   case Intrinsic::x86_sse2_psrai_w:
10792   case Intrinsic::x86_sse2_psrai_d:
10793   case Intrinsic::x86_avx2_psrai_w:
10794   case Intrinsic::x86_avx2_psrai_d: {
10795     unsigned Opcode;
10796     switch (IntNo) {
10797     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10798     case Intrinsic::x86_sse2_pslli_w:
10799     case Intrinsic::x86_sse2_pslli_d:
10800     case Intrinsic::x86_sse2_pslli_q:
10801     case Intrinsic::x86_avx2_pslli_w:
10802     case Intrinsic::x86_avx2_pslli_d:
10803     case Intrinsic::x86_avx2_pslli_q:
10804       Opcode = X86ISD::VSHLI;
10805       break;
10806     case Intrinsic::x86_sse2_psrli_w:
10807     case Intrinsic::x86_sse2_psrli_d:
10808     case Intrinsic::x86_sse2_psrli_q:
10809     case Intrinsic::x86_avx2_psrli_w:
10810     case Intrinsic::x86_avx2_psrli_d:
10811     case Intrinsic::x86_avx2_psrli_q:
10812       Opcode = X86ISD::VSRLI;
10813       break;
10814     case Intrinsic::x86_sse2_psrai_w:
10815     case Intrinsic::x86_sse2_psrai_d:
10816     case Intrinsic::x86_avx2_psrai_w:
10817     case Intrinsic::x86_avx2_psrai_d:
10818       Opcode = X86ISD::VSRAI;
10819       break;
10820     }
10821     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10822                                Op.getOperand(1), Op.getOperand(2), DAG);
10823   }
10824
10825   case Intrinsic::x86_sse42_pcmpistria128:
10826   case Intrinsic::x86_sse42_pcmpestria128:
10827   case Intrinsic::x86_sse42_pcmpistric128:
10828   case Intrinsic::x86_sse42_pcmpestric128:
10829   case Intrinsic::x86_sse42_pcmpistrio128:
10830   case Intrinsic::x86_sse42_pcmpestrio128:
10831   case Intrinsic::x86_sse42_pcmpistris128:
10832   case Intrinsic::x86_sse42_pcmpestris128:
10833   case Intrinsic::x86_sse42_pcmpistriz128:
10834   case Intrinsic::x86_sse42_pcmpestriz128: {
10835     unsigned Opcode;
10836     unsigned X86CC;
10837     switch (IntNo) {
10838     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10839     case Intrinsic::x86_sse42_pcmpistria128:
10840       Opcode = X86ISD::PCMPISTRI;
10841       X86CC = X86::COND_A;
10842       break;
10843     case Intrinsic::x86_sse42_pcmpestria128:
10844       Opcode = X86ISD::PCMPESTRI;
10845       X86CC = X86::COND_A;
10846       break;
10847     case Intrinsic::x86_sse42_pcmpistric128:
10848       Opcode = X86ISD::PCMPISTRI;
10849       X86CC = X86::COND_B;
10850       break;
10851     case Intrinsic::x86_sse42_pcmpestric128:
10852       Opcode = X86ISD::PCMPESTRI;
10853       X86CC = X86::COND_B;
10854       break;
10855     case Intrinsic::x86_sse42_pcmpistrio128:
10856       Opcode = X86ISD::PCMPISTRI;
10857       X86CC = X86::COND_O;
10858       break;
10859     case Intrinsic::x86_sse42_pcmpestrio128:
10860       Opcode = X86ISD::PCMPESTRI;
10861       X86CC = X86::COND_O;
10862       break;
10863     case Intrinsic::x86_sse42_pcmpistris128:
10864       Opcode = X86ISD::PCMPISTRI;
10865       X86CC = X86::COND_S;
10866       break;
10867     case Intrinsic::x86_sse42_pcmpestris128:
10868       Opcode = X86ISD::PCMPESTRI;
10869       X86CC = X86::COND_S;
10870       break;
10871     case Intrinsic::x86_sse42_pcmpistriz128:
10872       Opcode = X86ISD::PCMPISTRI;
10873       X86CC = X86::COND_E;
10874       break;
10875     case Intrinsic::x86_sse42_pcmpestriz128:
10876       Opcode = X86ISD::PCMPESTRI;
10877       X86CC = X86::COND_E;
10878       break;
10879     }
10880     SmallVector<SDValue, 5> NewOps;
10881     NewOps.append(Op->op_begin()+1, Op->op_end());
10882     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10883     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10884     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10885                                 DAG.getConstant(X86CC, MVT::i8),
10886                                 SDValue(PCMP.getNode(), 1));
10887     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10888   }
10889
10890   case Intrinsic::x86_sse42_pcmpistri128:
10891   case Intrinsic::x86_sse42_pcmpestri128: {
10892     unsigned Opcode;
10893     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10894       Opcode = X86ISD::PCMPISTRI;
10895     else
10896       Opcode = X86ISD::PCMPESTRI;
10897
10898     SmallVector<SDValue, 5> NewOps;
10899     NewOps.append(Op->op_begin()+1, Op->op_end());
10900     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10901     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10902   }
10903   case Intrinsic::x86_fma_vfmadd_ps:
10904   case Intrinsic::x86_fma_vfmadd_pd:
10905   case Intrinsic::x86_fma_vfmsub_ps:
10906   case Intrinsic::x86_fma_vfmsub_pd:
10907   case Intrinsic::x86_fma_vfnmadd_ps:
10908   case Intrinsic::x86_fma_vfnmadd_pd:
10909   case Intrinsic::x86_fma_vfnmsub_ps:
10910   case Intrinsic::x86_fma_vfnmsub_pd:
10911   case Intrinsic::x86_fma_vfmaddsub_ps:
10912   case Intrinsic::x86_fma_vfmaddsub_pd:
10913   case Intrinsic::x86_fma_vfmsubadd_ps:
10914   case Intrinsic::x86_fma_vfmsubadd_pd:
10915   case Intrinsic::x86_fma_vfmadd_ps_256:
10916   case Intrinsic::x86_fma_vfmadd_pd_256:
10917   case Intrinsic::x86_fma_vfmsub_ps_256:
10918   case Intrinsic::x86_fma_vfmsub_pd_256:
10919   case Intrinsic::x86_fma_vfnmadd_ps_256:
10920   case Intrinsic::x86_fma_vfnmadd_pd_256:
10921   case Intrinsic::x86_fma_vfnmsub_ps_256:
10922   case Intrinsic::x86_fma_vfnmsub_pd_256:
10923   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10924   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10925   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10926   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10927     unsigned Opc;
10928     switch (IntNo) {
10929     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10930     case Intrinsic::x86_fma_vfmadd_ps:
10931     case Intrinsic::x86_fma_vfmadd_pd:
10932     case Intrinsic::x86_fma_vfmadd_ps_256:
10933     case Intrinsic::x86_fma_vfmadd_pd_256:
10934       Opc = X86ISD::FMADD;
10935       break;
10936     case Intrinsic::x86_fma_vfmsub_ps:
10937     case Intrinsic::x86_fma_vfmsub_pd:
10938     case Intrinsic::x86_fma_vfmsub_ps_256:
10939     case Intrinsic::x86_fma_vfmsub_pd_256:
10940       Opc = X86ISD::FMSUB;
10941       break;
10942     case Intrinsic::x86_fma_vfnmadd_ps:
10943     case Intrinsic::x86_fma_vfnmadd_pd:
10944     case Intrinsic::x86_fma_vfnmadd_ps_256:
10945     case Intrinsic::x86_fma_vfnmadd_pd_256:
10946       Opc = X86ISD::FNMADD;
10947       break;
10948     case Intrinsic::x86_fma_vfnmsub_ps:
10949     case Intrinsic::x86_fma_vfnmsub_pd:
10950     case Intrinsic::x86_fma_vfnmsub_ps_256:
10951     case Intrinsic::x86_fma_vfnmsub_pd_256:
10952       Opc = X86ISD::FNMSUB;
10953       break;
10954     case Intrinsic::x86_fma_vfmaddsub_ps:
10955     case Intrinsic::x86_fma_vfmaddsub_pd:
10956     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10957     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10958       Opc = X86ISD::FMADDSUB;
10959       break;
10960     case Intrinsic::x86_fma_vfmsubadd_ps:
10961     case Intrinsic::x86_fma_vfmsubadd_pd:
10962     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10963     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10964       Opc = X86ISD::FMSUBADD;
10965       break;
10966     }
10967
10968     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10969                        Op.getOperand(2), Op.getOperand(3));
10970   }
10971   }
10972 }
10973
10974 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10975   DebugLoc dl = Op.getDebugLoc();
10976   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10977   switch (IntNo) {
10978   default: return SDValue();    // Don't custom lower most intrinsics.
10979
10980   // RDRAND/RDSEED intrinsics.
10981   case Intrinsic::x86_rdrand_16:
10982   case Intrinsic::x86_rdrand_32:
10983   case Intrinsic::x86_rdrand_64:
10984   case Intrinsic::x86_rdseed_16:
10985   case Intrinsic::x86_rdseed_32:
10986   case Intrinsic::x86_rdseed_64: {
10987     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10988                        IntNo == Intrinsic::x86_rdseed_32 ||
10989                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10990                                                             X86ISD::RDRAND;
10991     // Emit the node with the right value type.
10992     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10993     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10994
10995     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10996     // Otherwise return the value from Rand, which is always 0, casted to i32.
10997     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10998                       DAG.getConstant(1, Op->getValueType(1)),
10999                       DAG.getConstant(X86::COND_B, MVT::i32),
11000                       SDValue(Result.getNode(), 1) };
11001     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11002                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11003                                   Ops, array_lengthof(Ops));
11004
11005     // Return { result, isValid, chain }.
11006     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11007                        SDValue(Result.getNode(), 2));
11008   }
11009
11010   // XTEST intrinsics.
11011   case Intrinsic::x86_xtest: {
11012     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11013     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11014     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11015                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11016                                 InTrans);
11017     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11018     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11019                        Ret, SDValue(InTrans.getNode(), 1));
11020   }
11021   }
11022 }
11023
11024 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11025                                            SelectionDAG &DAG) const {
11026   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11027   MFI->setReturnAddressIsTaken(true);
11028
11029   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11030   DebugLoc dl = Op.getDebugLoc();
11031   EVT PtrVT = getPointerTy();
11032
11033   if (Depth > 0) {
11034     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11035     SDValue Offset =
11036       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11037     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11038                        DAG.getNode(ISD::ADD, dl, PtrVT,
11039                                    FrameAddr, Offset),
11040                        MachinePointerInfo(), false, false, false, 0);
11041   }
11042
11043   // Just load the return address.
11044   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11045   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11046                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11047 }
11048
11049 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11050   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11051   MFI->setFrameAddressIsTaken(true);
11052
11053   EVT VT = Op.getValueType();
11054   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
11055   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11056   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11057   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11058           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11059          "Invalid Frame Register!");
11060   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11061   while (Depth--)
11062     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11063                             MachinePointerInfo(),
11064                             false, false, false, 0);
11065   return FrameAddr;
11066 }
11067
11068 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11069                                                      SelectionDAG &DAG) const {
11070   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11071 }
11072
11073 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11074   SDValue Chain     = Op.getOperand(0);
11075   SDValue Offset    = Op.getOperand(1);
11076   SDValue Handler   = Op.getOperand(2);
11077   DebugLoc dl       = Op.getDebugLoc();
11078
11079   EVT PtrVT = getPointerTy();
11080   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11081   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11082           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11083          "Invalid Frame Register!");
11084   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11085   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11086
11087   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11088                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11089   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11090   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11091                        false, false, 0);
11092   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11093
11094   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11095                      DAG.getRegister(StoreAddrReg, PtrVT));
11096 }
11097
11098 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11099                                                SelectionDAG &DAG) const {
11100   DebugLoc DL = Op.getDebugLoc();
11101   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11102                      DAG.getVTList(MVT::i32, MVT::Other),
11103                      Op.getOperand(0), Op.getOperand(1));
11104 }
11105
11106 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11107                                                 SelectionDAG &DAG) const {
11108   DebugLoc DL = Op.getDebugLoc();
11109   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11110                      Op.getOperand(0), Op.getOperand(1));
11111 }
11112
11113 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11114   return Op.getOperand(0);
11115 }
11116
11117 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11118                                                 SelectionDAG &DAG) const {
11119   SDValue Root = Op.getOperand(0);
11120   SDValue Trmp = Op.getOperand(1); // trampoline
11121   SDValue FPtr = Op.getOperand(2); // nested function
11122   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11123   DebugLoc dl  = Op.getDebugLoc();
11124
11125   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11126   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11127
11128   if (Subtarget->is64Bit()) {
11129     SDValue OutChains[6];
11130
11131     // Large code-model.
11132     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11133     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11134
11135     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11136     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11137
11138     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11139
11140     // Load the pointer to the nested function into R11.
11141     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11142     SDValue Addr = Trmp;
11143     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11144                                 Addr, MachinePointerInfo(TrmpAddr),
11145                                 false, false, 0);
11146
11147     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11148                        DAG.getConstant(2, MVT::i64));
11149     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11150                                 MachinePointerInfo(TrmpAddr, 2),
11151                                 false, false, 2);
11152
11153     // Load the 'nest' parameter value into R10.
11154     // R10 is specified in X86CallingConv.td
11155     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11156     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11157                        DAG.getConstant(10, MVT::i64));
11158     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11159                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11160                                 false, false, 0);
11161
11162     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11163                        DAG.getConstant(12, MVT::i64));
11164     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11165                                 MachinePointerInfo(TrmpAddr, 12),
11166                                 false, false, 2);
11167
11168     // Jump to the nested function.
11169     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11170     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11171                        DAG.getConstant(20, MVT::i64));
11172     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11173                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11174                                 false, false, 0);
11175
11176     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11177     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11178                        DAG.getConstant(22, MVT::i64));
11179     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11180                                 MachinePointerInfo(TrmpAddr, 22),
11181                                 false, false, 0);
11182
11183     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11184   } else {
11185     const Function *Func =
11186       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11187     CallingConv::ID CC = Func->getCallingConv();
11188     unsigned NestReg;
11189
11190     switch (CC) {
11191     default:
11192       llvm_unreachable("Unsupported calling convention");
11193     case CallingConv::C:
11194     case CallingConv::X86_StdCall: {
11195       // Pass 'nest' parameter in ECX.
11196       // Must be kept in sync with X86CallingConv.td
11197       NestReg = X86::ECX;
11198
11199       // Check that ECX wasn't needed by an 'inreg' parameter.
11200       FunctionType *FTy = Func->getFunctionType();
11201       const AttributeSet &Attrs = Func->getAttributes();
11202
11203       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11204         unsigned InRegCount = 0;
11205         unsigned Idx = 1;
11206
11207         for (FunctionType::param_iterator I = FTy->param_begin(),
11208              E = FTy->param_end(); I != E; ++I, ++Idx)
11209           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11210             // FIXME: should only count parameters that are lowered to integers.
11211             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11212
11213         if (InRegCount > 2) {
11214           report_fatal_error("Nest register in use - reduce number of inreg"
11215                              " parameters!");
11216         }
11217       }
11218       break;
11219     }
11220     case CallingConv::X86_FastCall:
11221     case CallingConv::X86_ThisCall:
11222     case CallingConv::Fast:
11223       // Pass 'nest' parameter in EAX.
11224       // Must be kept in sync with X86CallingConv.td
11225       NestReg = X86::EAX;
11226       break;
11227     }
11228
11229     SDValue OutChains[4];
11230     SDValue Addr, Disp;
11231
11232     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11233                        DAG.getConstant(10, MVT::i32));
11234     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11235
11236     // This is storing the opcode for MOV32ri.
11237     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11238     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11239     OutChains[0] = DAG.getStore(Root, dl,
11240                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11241                                 Trmp, MachinePointerInfo(TrmpAddr),
11242                                 false, false, 0);
11243
11244     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11245                        DAG.getConstant(1, MVT::i32));
11246     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11247                                 MachinePointerInfo(TrmpAddr, 1),
11248                                 false, false, 1);
11249
11250     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11251     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11252                        DAG.getConstant(5, MVT::i32));
11253     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11254                                 MachinePointerInfo(TrmpAddr, 5),
11255                                 false, false, 1);
11256
11257     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11258                        DAG.getConstant(6, MVT::i32));
11259     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11260                                 MachinePointerInfo(TrmpAddr, 6),
11261                                 false, false, 1);
11262
11263     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11264   }
11265 }
11266
11267 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11268                                             SelectionDAG &DAG) const {
11269   /*
11270    The rounding mode is in bits 11:10 of FPSR, and has the following
11271    settings:
11272      00 Round to nearest
11273      01 Round to -inf
11274      10 Round to +inf
11275      11 Round to 0
11276
11277   FLT_ROUNDS, on the other hand, expects the following:
11278     -1 Undefined
11279      0 Round to 0
11280      1 Round to nearest
11281      2 Round to +inf
11282      3 Round to -inf
11283
11284   To perform the conversion, we do:
11285     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11286   */
11287
11288   MachineFunction &MF = DAG.getMachineFunction();
11289   const TargetMachine &TM = MF.getTarget();
11290   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11291   unsigned StackAlignment = TFI.getStackAlignment();
11292   EVT VT = Op.getValueType();
11293   DebugLoc DL = Op.getDebugLoc();
11294
11295   // Save FP Control Word to stack slot
11296   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11297   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11298
11299   MachineMemOperand *MMO =
11300    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11301                            MachineMemOperand::MOStore, 2, 2);
11302
11303   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11304   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11305                                           DAG.getVTList(MVT::Other),
11306                                           Ops, array_lengthof(Ops), MVT::i16,
11307                                           MMO);
11308
11309   // Load FP Control Word from stack slot
11310   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11311                             MachinePointerInfo(), false, false, false, 0);
11312
11313   // Transform as necessary
11314   SDValue CWD1 =
11315     DAG.getNode(ISD::SRL, DL, MVT::i16,
11316                 DAG.getNode(ISD::AND, DL, MVT::i16,
11317                             CWD, DAG.getConstant(0x800, MVT::i16)),
11318                 DAG.getConstant(11, MVT::i8));
11319   SDValue CWD2 =
11320     DAG.getNode(ISD::SRL, DL, MVT::i16,
11321                 DAG.getNode(ISD::AND, DL, MVT::i16,
11322                             CWD, DAG.getConstant(0x400, MVT::i16)),
11323                 DAG.getConstant(9, MVT::i8));
11324
11325   SDValue RetVal =
11326     DAG.getNode(ISD::AND, DL, MVT::i16,
11327                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11328                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11329                             DAG.getConstant(1, MVT::i16)),
11330                 DAG.getConstant(3, MVT::i16));
11331
11332   return DAG.getNode((VT.getSizeInBits() < 16 ?
11333                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11334 }
11335
11336 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11337   EVT VT = Op.getValueType();
11338   EVT OpVT = VT;
11339   unsigned NumBits = VT.getSizeInBits();
11340   DebugLoc dl = Op.getDebugLoc();
11341
11342   Op = Op.getOperand(0);
11343   if (VT == MVT::i8) {
11344     // Zero extend to i32 since there is not an i8 bsr.
11345     OpVT = MVT::i32;
11346     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11347   }
11348
11349   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11350   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11351   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11352
11353   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11354   SDValue Ops[] = {
11355     Op,
11356     DAG.getConstant(NumBits+NumBits-1, OpVT),
11357     DAG.getConstant(X86::COND_E, MVT::i8),
11358     Op.getValue(1)
11359   };
11360   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11361
11362   // Finally xor with NumBits-1.
11363   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11364
11365   if (VT == MVT::i8)
11366     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11367   return Op;
11368 }
11369
11370 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11371   EVT VT = Op.getValueType();
11372   EVT OpVT = VT;
11373   unsigned NumBits = VT.getSizeInBits();
11374   DebugLoc dl = Op.getDebugLoc();
11375
11376   Op = Op.getOperand(0);
11377   if (VT == MVT::i8) {
11378     // Zero extend to i32 since there is not an i8 bsr.
11379     OpVT = MVT::i32;
11380     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11381   }
11382
11383   // Issue a bsr (scan bits in reverse).
11384   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11385   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11386
11387   // And xor with NumBits-1.
11388   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11389
11390   if (VT == MVT::i8)
11391     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11392   return Op;
11393 }
11394
11395 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11396   EVT VT = Op.getValueType();
11397   unsigned NumBits = VT.getSizeInBits();
11398   DebugLoc dl = Op.getDebugLoc();
11399   Op = Op.getOperand(0);
11400
11401   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11402   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11403   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11404
11405   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11406   SDValue Ops[] = {
11407     Op,
11408     DAG.getConstant(NumBits, VT),
11409     DAG.getConstant(X86::COND_E, MVT::i8),
11410     Op.getValue(1)
11411   };
11412   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11413 }
11414
11415 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11416 // ones, and then concatenate the result back.
11417 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11418   EVT VT = Op.getValueType();
11419
11420   assert(VT.is256BitVector() && VT.isInteger() &&
11421          "Unsupported value type for operation");
11422
11423   unsigned NumElems = VT.getVectorNumElements();
11424   DebugLoc dl = Op.getDebugLoc();
11425
11426   // Extract the LHS vectors
11427   SDValue LHS = Op.getOperand(0);
11428   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11429   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11430
11431   // Extract the RHS vectors
11432   SDValue RHS = Op.getOperand(1);
11433   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11434   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11435
11436   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11437   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11438
11439   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11440                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11441                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11442 }
11443
11444 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11445   assert(Op.getValueType().is256BitVector() &&
11446          Op.getValueType().isInteger() &&
11447          "Only handle AVX 256-bit vector integer operation");
11448   return Lower256IntArith(Op, DAG);
11449 }
11450
11451 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11452   assert(Op.getValueType().is256BitVector() &&
11453          Op.getValueType().isInteger() &&
11454          "Only handle AVX 256-bit vector integer operation");
11455   return Lower256IntArith(Op, DAG);
11456 }
11457
11458 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11459                         SelectionDAG &DAG) {
11460   DebugLoc dl = Op.getDebugLoc();
11461   EVT VT = Op.getValueType();
11462
11463   // Decompose 256-bit ops into smaller 128-bit ops.
11464   if (VT.is256BitVector() && !Subtarget->hasInt256())
11465     return Lower256IntArith(Op, DAG);
11466
11467   SDValue A = Op.getOperand(0);
11468   SDValue B = Op.getOperand(1);
11469
11470   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11471   if (VT == MVT::v4i32) {
11472     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11473            "Should not custom lower when pmuldq is available!");
11474
11475     // Extract the odd parts.
11476     const int UnpackMask[] = { 1, -1, 3, -1 };
11477     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11478     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11479
11480     // Multiply the even parts.
11481     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11482     // Now multiply odd parts.
11483     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11484
11485     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11486     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11487
11488     // Merge the two vectors back together with a shuffle. This expands into 2
11489     // shuffles.
11490     const int ShufMask[] = { 0, 4, 2, 6 };
11491     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11492   }
11493
11494   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11495          "Only know how to lower V2I64/V4I64 multiply");
11496
11497   //  Ahi = psrlqi(a, 32);
11498   //  Bhi = psrlqi(b, 32);
11499   //
11500   //  AloBlo = pmuludq(a, b);
11501   //  AloBhi = pmuludq(a, Bhi);
11502   //  AhiBlo = pmuludq(Ahi, b);
11503
11504   //  AloBhi = psllqi(AloBhi, 32);
11505   //  AhiBlo = psllqi(AhiBlo, 32);
11506   //  return AloBlo + AloBhi + AhiBlo;
11507
11508   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11509
11510   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11511   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11512
11513   // Bit cast to 32-bit vectors for MULUDQ
11514   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11515   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11516   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11517   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11518   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11519
11520   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11521   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11522   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11523
11524   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11525   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11526
11527   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11528   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11529 }
11530
11531 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11532   EVT VT = Op.getValueType();
11533   EVT EltTy = VT.getVectorElementType();
11534   unsigned NumElts = VT.getVectorNumElements();
11535   SDValue N0 = Op.getOperand(0);
11536   DebugLoc dl = Op.getDebugLoc();
11537
11538   // Lower sdiv X, pow2-const.
11539   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11540   if (!C)
11541     return SDValue();
11542
11543   APInt SplatValue, SplatUndef;
11544   unsigned MinSplatBits;
11545   bool HasAnyUndefs;
11546   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11547     return SDValue();
11548
11549   if ((SplatValue != 0) &&
11550       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11551     unsigned lg2 = SplatValue.countTrailingZeros();
11552     // Splat the sign bit.
11553     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11554     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11555     // Add (N0 < 0) ? abs2 - 1 : 0;
11556     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11557     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11558     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11559     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11560     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11561
11562     // If we're dividing by a positive value, we're done.  Otherwise, we must
11563     // negate the result.
11564     if (SplatValue.isNonNegative())
11565       return SRA;
11566
11567     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11568     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11569     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11570   }
11571   return SDValue();
11572 }
11573
11574 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11575                                          const X86Subtarget *Subtarget) {
11576   EVT VT = Op.getValueType();
11577   DebugLoc dl = Op.getDebugLoc();
11578   SDValue R = Op.getOperand(0);
11579   SDValue Amt = Op.getOperand(1);
11580
11581   // Optimize shl/srl/sra with constant shift amount.
11582   if (isSplatVector(Amt.getNode())) {
11583     SDValue SclrAmt = Amt->getOperand(0);
11584     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11585       uint64_t ShiftAmt = C->getZExtValue();
11586
11587       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11588           (Subtarget->hasInt256() &&
11589            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11590         if (Op.getOpcode() == ISD::SHL)
11591           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11592                              DAG.getConstant(ShiftAmt, MVT::i32));
11593         if (Op.getOpcode() == ISD::SRL)
11594           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11595                              DAG.getConstant(ShiftAmt, MVT::i32));
11596         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11597           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11598                              DAG.getConstant(ShiftAmt, MVT::i32));
11599       }
11600
11601       if (VT == MVT::v16i8) {
11602         if (Op.getOpcode() == ISD::SHL) {
11603           // Make a large shift.
11604           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11605                                     DAG.getConstant(ShiftAmt, MVT::i32));
11606           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11607           // Zero out the rightmost bits.
11608           SmallVector<SDValue, 16> V(16,
11609                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11610                                                      MVT::i8));
11611           return DAG.getNode(ISD::AND, dl, VT, SHL,
11612                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11613         }
11614         if (Op.getOpcode() == ISD::SRL) {
11615           // Make a large shift.
11616           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11617                                     DAG.getConstant(ShiftAmt, MVT::i32));
11618           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11619           // Zero out the leftmost bits.
11620           SmallVector<SDValue, 16> V(16,
11621                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11622                                                      MVT::i8));
11623           return DAG.getNode(ISD::AND, dl, VT, SRL,
11624                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11625         }
11626         if (Op.getOpcode() == ISD::SRA) {
11627           if (ShiftAmt == 7) {
11628             // R s>> 7  ===  R s< 0
11629             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11630             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11631           }
11632
11633           // R s>> a === ((R u>> a) ^ m) - m
11634           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11635           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11636                                                          MVT::i8));
11637           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11638           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11639           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11640           return Res;
11641         }
11642         llvm_unreachable("Unknown shift opcode.");
11643       }
11644
11645       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11646         if (Op.getOpcode() == ISD::SHL) {
11647           // Make a large shift.
11648           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11649                                     DAG.getConstant(ShiftAmt, MVT::i32));
11650           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11651           // Zero out the rightmost bits.
11652           SmallVector<SDValue, 32> V(32,
11653                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11654                                                      MVT::i8));
11655           return DAG.getNode(ISD::AND, dl, VT, SHL,
11656                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11657         }
11658         if (Op.getOpcode() == ISD::SRL) {
11659           // Make a large shift.
11660           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11661                                     DAG.getConstant(ShiftAmt, MVT::i32));
11662           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11663           // Zero out the leftmost bits.
11664           SmallVector<SDValue, 32> V(32,
11665                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11666                                                      MVT::i8));
11667           return DAG.getNode(ISD::AND, dl, VT, SRL,
11668                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11669         }
11670         if (Op.getOpcode() == ISD::SRA) {
11671           if (ShiftAmt == 7) {
11672             // R s>> 7  ===  R s< 0
11673             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11674             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11675           }
11676
11677           // R s>> a === ((R u>> a) ^ m) - m
11678           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11679           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11680                                                          MVT::i8));
11681           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11682           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11683           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11684           return Res;
11685         }
11686         llvm_unreachable("Unknown shift opcode.");
11687       }
11688     }
11689   }
11690
11691   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11692   if (!Subtarget->is64Bit() &&
11693       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11694       Amt.getOpcode() == ISD::BITCAST &&
11695       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11696     Amt = Amt.getOperand(0);
11697     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11698                      VT.getVectorNumElements();
11699     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11700     uint64_t ShiftAmt = 0;
11701     for (unsigned i = 0; i != Ratio; ++i) {
11702       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11703       if (C == 0)
11704         return SDValue();
11705       // 6 == Log2(64)
11706       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11707     }
11708     // Check remaining shift amounts.
11709     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11710       uint64_t ShAmt = 0;
11711       for (unsigned j = 0; j != Ratio; ++j) {
11712         ConstantSDNode *C =
11713           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11714         if (C == 0)
11715           return SDValue();
11716         // 6 == Log2(64)
11717         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11718       }
11719       if (ShAmt != ShiftAmt)
11720         return SDValue();
11721     }
11722     switch (Op.getOpcode()) {
11723     default:
11724       llvm_unreachable("Unknown shift opcode!");
11725     case ISD::SHL:
11726       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11727                          DAG.getConstant(ShiftAmt, MVT::i32));
11728     case ISD::SRL:
11729       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11730                          DAG.getConstant(ShiftAmt, MVT::i32));
11731     case ISD::SRA:
11732       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11733                          DAG.getConstant(ShiftAmt, MVT::i32));
11734     }
11735   }
11736
11737   return SDValue();
11738 }
11739
11740 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11741                                         const X86Subtarget* Subtarget) {
11742   EVT VT = Op.getValueType();
11743   DebugLoc dl = Op.getDebugLoc();
11744   SDValue R = Op.getOperand(0);
11745   SDValue Amt = Op.getOperand(1);
11746
11747   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11748       VT == MVT::v4i32 || VT == MVT::v8i16 ||
11749       (Subtarget->hasInt256() &&
11750        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11751         VT == MVT::v8i32 || VT == MVT::v16i16))) {
11752     SDValue BaseShAmt;
11753     EVT EltVT = VT.getVectorElementType();
11754
11755     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11756       unsigned NumElts = VT.getVectorNumElements();
11757       unsigned i, j;
11758       for (i = 0; i != NumElts; ++i) {
11759         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11760           continue;
11761         break;
11762       }
11763       for (j = i; j != NumElts; ++j) {
11764         SDValue Arg = Amt.getOperand(j);
11765         if (Arg.getOpcode() == ISD::UNDEF) continue;
11766         if (Arg != Amt.getOperand(i))
11767           break;
11768       }
11769       if (i != NumElts && j == NumElts)
11770         BaseShAmt = Amt.getOperand(i);
11771     } else {
11772       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11773         Amt = Amt.getOperand(0);
11774       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11775                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11776         SDValue InVec = Amt.getOperand(0);
11777         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11778           unsigned NumElts = InVec.getValueType().getVectorNumElements();
11779           unsigned i = 0;
11780           for (; i != NumElts; ++i) {
11781             SDValue Arg = InVec.getOperand(i);
11782             if (Arg.getOpcode() == ISD::UNDEF) continue;
11783             BaseShAmt = Arg;
11784             break;
11785           }
11786         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11787            if (ConstantSDNode *C =
11788                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11789              unsigned SplatIdx =
11790                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11791              if (C->getZExtValue() == SplatIdx)
11792                BaseShAmt = InVec.getOperand(1);
11793            }
11794         }
11795         if (BaseShAmt.getNode() == 0)
11796           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11797                                   DAG.getIntPtrConstant(0));
11798       }
11799     }
11800
11801     if (BaseShAmt.getNode()) {
11802       if (EltVT.bitsGT(MVT::i32))
11803         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11804       else if (EltVT.bitsLT(MVT::i32))
11805         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11806
11807       switch (Op.getOpcode()) {
11808       default:
11809         llvm_unreachable("Unknown shift opcode!");
11810       case ISD::SHL:
11811         switch (VT.getSimpleVT().SimpleTy) {
11812         default: return SDValue();
11813         case MVT::v2i64:
11814         case MVT::v4i32:
11815         case MVT::v8i16:
11816         case MVT::v4i64:
11817         case MVT::v8i32:
11818         case MVT::v16i16:
11819           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11820         }
11821       case ISD::SRA:
11822         switch (VT.getSimpleVT().SimpleTy) {
11823         default: return SDValue();
11824         case MVT::v4i32:
11825         case MVT::v8i16:
11826         case MVT::v8i32:
11827         case MVT::v16i16:
11828           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11829         }
11830       case ISD::SRL:
11831         switch (VT.getSimpleVT().SimpleTy) {
11832         default: return SDValue();
11833         case MVT::v2i64:
11834         case MVT::v4i32:
11835         case MVT::v8i16:
11836         case MVT::v4i64:
11837         case MVT::v8i32:
11838         case MVT::v16i16:
11839           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11840         }
11841       }
11842     }
11843   }
11844
11845   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11846   if (!Subtarget->is64Bit() &&
11847       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11848       Amt.getOpcode() == ISD::BITCAST &&
11849       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11850     Amt = Amt.getOperand(0);
11851     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11852                      VT.getVectorNumElements();
11853     std::vector<SDValue> Vals(Ratio);
11854     for (unsigned i = 0; i != Ratio; ++i)
11855       Vals[i] = Amt.getOperand(i);
11856     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11857       for (unsigned j = 0; j != Ratio; ++j)
11858         if (Vals[j] != Amt.getOperand(i + j))
11859           return SDValue();
11860     }
11861     switch (Op.getOpcode()) {
11862     default:
11863       llvm_unreachable("Unknown shift opcode!");
11864     case ISD::SHL:
11865       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11866     case ISD::SRL:
11867       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11868     case ISD::SRA:
11869       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11870     }
11871   }
11872
11873   return SDValue();
11874 }
11875
11876 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11877
11878   EVT VT = Op.getValueType();
11879   DebugLoc dl = Op.getDebugLoc();
11880   SDValue R = Op.getOperand(0);
11881   SDValue Amt = Op.getOperand(1);
11882   SDValue V;
11883
11884   if (!Subtarget->hasSSE2())
11885     return SDValue();
11886
11887   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11888   if (V.getNode())
11889     return V;
11890
11891   V = LowerScalarVariableShift(Op, DAG, Subtarget);
11892   if (V.getNode())
11893       return V;
11894
11895   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11896   if (Subtarget->hasInt256()) {
11897     if (Op.getOpcode() == ISD::SRL &&
11898         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11899          VT == MVT::v4i64 || VT == MVT::v8i32))
11900       return Op;
11901     if (Op.getOpcode() == ISD::SHL &&
11902         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11903          VT == MVT::v4i64 || VT == MVT::v8i32))
11904       return Op;
11905     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11906       return Op;
11907   }
11908
11909   // Lower SHL with variable shift amount.
11910   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11911     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11912
11913     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11914     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11915     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11916     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11917   }
11918   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11919     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11920
11921     // a = a << 5;
11922     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11923     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11924
11925     // Turn 'a' into a mask suitable for VSELECT
11926     SDValue VSelM = DAG.getConstant(0x80, VT);
11927     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11928     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11929
11930     SDValue CM1 = DAG.getConstant(0x0f, VT);
11931     SDValue CM2 = DAG.getConstant(0x3f, VT);
11932
11933     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11934     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11935     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11936                             DAG.getConstant(4, MVT::i32), DAG);
11937     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11938     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11939
11940     // a += a
11941     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11942     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11943     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11944
11945     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11946     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11947     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11948                             DAG.getConstant(2, MVT::i32), DAG);
11949     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11950     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11951
11952     // a += a
11953     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11954     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11955     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11956
11957     // return VSELECT(r, r+r, a);
11958     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11959                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11960     return R;
11961   }
11962
11963   // Decompose 256-bit shifts into smaller 128-bit shifts.
11964   if (VT.is256BitVector()) {
11965     unsigned NumElems = VT.getVectorNumElements();
11966     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11967     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11968
11969     // Extract the two vectors
11970     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11971     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11972
11973     // Recreate the shift amount vectors
11974     SDValue Amt1, Amt2;
11975     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11976       // Constant shift amount
11977       SmallVector<SDValue, 4> Amt1Csts;
11978       SmallVector<SDValue, 4> Amt2Csts;
11979       for (unsigned i = 0; i != NumElems/2; ++i)
11980         Amt1Csts.push_back(Amt->getOperand(i));
11981       for (unsigned i = NumElems/2; i != NumElems; ++i)
11982         Amt2Csts.push_back(Amt->getOperand(i));
11983
11984       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11985                                  &Amt1Csts[0], NumElems/2);
11986       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11987                                  &Amt2Csts[0], NumElems/2);
11988     } else {
11989       // Variable shift amount
11990       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11991       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11992     }
11993
11994     // Issue new vector shifts for the smaller types
11995     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11996     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11997
11998     // Concatenate the result back
11999     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12000   }
12001
12002   return SDValue();
12003 }
12004
12005 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12006   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12007   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12008   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12009   // has only one use.
12010   SDNode *N = Op.getNode();
12011   SDValue LHS = N->getOperand(0);
12012   SDValue RHS = N->getOperand(1);
12013   unsigned BaseOp = 0;
12014   unsigned Cond = 0;
12015   DebugLoc DL = Op.getDebugLoc();
12016   switch (Op.getOpcode()) {
12017   default: llvm_unreachable("Unknown ovf instruction!");
12018   case ISD::SADDO:
12019     // A subtract of one will be selected as a INC. Note that INC doesn't
12020     // set CF, so we can't do this for UADDO.
12021     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12022       if (C->isOne()) {
12023         BaseOp = X86ISD::INC;
12024         Cond = X86::COND_O;
12025         break;
12026       }
12027     BaseOp = X86ISD::ADD;
12028     Cond = X86::COND_O;
12029     break;
12030   case ISD::UADDO:
12031     BaseOp = X86ISD::ADD;
12032     Cond = X86::COND_B;
12033     break;
12034   case ISD::SSUBO:
12035     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12036     // set CF, so we can't do this for USUBO.
12037     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12038       if (C->isOne()) {
12039         BaseOp = X86ISD::DEC;
12040         Cond = X86::COND_O;
12041         break;
12042       }
12043     BaseOp = X86ISD::SUB;
12044     Cond = X86::COND_O;
12045     break;
12046   case ISD::USUBO:
12047     BaseOp = X86ISD::SUB;
12048     Cond = X86::COND_B;
12049     break;
12050   case ISD::SMULO:
12051     BaseOp = X86ISD::SMUL;
12052     Cond = X86::COND_O;
12053     break;
12054   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12055     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12056                                  MVT::i32);
12057     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12058
12059     SDValue SetCC =
12060       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12061                   DAG.getConstant(X86::COND_O, MVT::i32),
12062                   SDValue(Sum.getNode(), 2));
12063
12064     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12065   }
12066   }
12067
12068   // Also sets EFLAGS.
12069   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12070   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12071
12072   SDValue SetCC =
12073     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12074                 DAG.getConstant(Cond, MVT::i32),
12075                 SDValue(Sum.getNode(), 1));
12076
12077   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12078 }
12079
12080 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12081                                                   SelectionDAG &DAG) const {
12082   DebugLoc dl = Op.getDebugLoc();
12083   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12084   EVT VT = Op.getValueType();
12085
12086   if (!Subtarget->hasSSE2() || !VT.isVector())
12087     return SDValue();
12088
12089   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12090                       ExtraVT.getScalarType().getSizeInBits();
12091   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12092
12093   switch (VT.getSimpleVT().SimpleTy) {
12094     default: return SDValue();
12095     case MVT::v8i32:
12096     case MVT::v16i16:
12097       if (!Subtarget->hasFp256())
12098         return SDValue();
12099       if (!Subtarget->hasInt256()) {
12100         // needs to be split
12101         unsigned NumElems = VT.getVectorNumElements();
12102
12103         // Extract the LHS vectors
12104         SDValue LHS = Op.getOperand(0);
12105         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12106         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12107
12108         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12109         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12110
12111         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12112         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12113         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12114                                    ExtraNumElems/2);
12115         SDValue Extra = DAG.getValueType(ExtraVT);
12116
12117         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12118         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12119
12120         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12121       }
12122       // fall through
12123     case MVT::v4i32:
12124     case MVT::v8i16: {
12125       // (sext (vzext x)) -> (vsext x)
12126       SDValue Op0 = Op.getOperand(0);
12127       SDValue Op00 = Op0.getOperand(0);
12128       SDValue Tmp1;
12129       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12130       if (Op0.getOpcode() == ISD::BITCAST &&
12131           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12132         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12133       if (Tmp1.getNode()) {
12134         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12135         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12136                "This optimization is invalid without a VZEXT.");
12137         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12138       }
12139
12140       // If the above didn't work, then just use Shift-Left + Shift-Right.
12141       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12142       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12143     }
12144   }
12145 }
12146
12147 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12148                                  SelectionDAG &DAG) {
12149   DebugLoc dl = Op.getDebugLoc();
12150   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12151     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12152   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12153     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12154
12155   // The only fence that needs an instruction is a sequentially-consistent
12156   // cross-thread fence.
12157   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12158     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12159     // no-sse2). There isn't any reason to disable it if the target processor
12160     // supports it.
12161     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12162       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12163
12164     SDValue Chain = Op.getOperand(0);
12165     SDValue Zero = DAG.getConstant(0, MVT::i32);
12166     SDValue Ops[] = {
12167       DAG.getRegister(X86::ESP, MVT::i32), // Base
12168       DAG.getTargetConstant(1, MVT::i8),   // Scale
12169       DAG.getRegister(0, MVT::i32),        // Index
12170       DAG.getTargetConstant(0, MVT::i32),  // Disp
12171       DAG.getRegister(0, MVT::i32),        // Segment.
12172       Zero,
12173       Chain
12174     };
12175     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12176     return SDValue(Res, 0);
12177   }
12178
12179   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12180   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12181 }
12182
12183 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12184                              SelectionDAG &DAG) {
12185   EVT T = Op.getValueType();
12186   DebugLoc DL = Op.getDebugLoc();
12187   unsigned Reg = 0;
12188   unsigned size = 0;
12189   switch(T.getSimpleVT().SimpleTy) {
12190   default: llvm_unreachable("Invalid value type!");
12191   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12192   case MVT::i16: Reg = X86::AX;  size = 2; break;
12193   case MVT::i32: Reg = X86::EAX; size = 4; break;
12194   case MVT::i64:
12195     assert(Subtarget->is64Bit() && "Node not type legal!");
12196     Reg = X86::RAX; size = 8;
12197     break;
12198   }
12199   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12200                                     Op.getOperand(2), SDValue());
12201   SDValue Ops[] = { cpIn.getValue(0),
12202                     Op.getOperand(1),
12203                     Op.getOperand(3),
12204                     DAG.getTargetConstant(size, MVT::i8),
12205                     cpIn.getValue(1) };
12206   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12207   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12208   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12209                                            Ops, array_lengthof(Ops), T, MMO);
12210   SDValue cpOut =
12211     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12212   return cpOut;
12213 }
12214
12215 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12216                                      SelectionDAG &DAG) {
12217   assert(Subtarget->is64Bit() && "Result not type legalized?");
12218   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12219   SDValue TheChain = Op.getOperand(0);
12220   DebugLoc dl = Op.getDebugLoc();
12221   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12222   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12223   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12224                                    rax.getValue(2));
12225   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12226                             DAG.getConstant(32, MVT::i8));
12227   SDValue Ops[] = {
12228     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12229     rdx.getValue(1)
12230   };
12231   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12232 }
12233
12234 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12235   EVT SrcVT = Op.getOperand(0).getValueType();
12236   EVT DstVT = Op.getValueType();
12237   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12238          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12239   assert((DstVT == MVT::i64 ||
12240           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12241          "Unexpected custom BITCAST");
12242   // i64 <=> MMX conversions are Legal.
12243   if (SrcVT==MVT::i64 && DstVT.isVector())
12244     return Op;
12245   if (DstVT==MVT::i64 && SrcVT.isVector())
12246     return Op;
12247   // MMX <=> MMX conversions are Legal.
12248   if (SrcVT.isVector() && DstVT.isVector())
12249     return Op;
12250   // All other conversions need to be expanded.
12251   return SDValue();
12252 }
12253
12254 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12255   SDNode *Node = Op.getNode();
12256   DebugLoc dl = Node->getDebugLoc();
12257   EVT T = Node->getValueType(0);
12258   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12259                               DAG.getConstant(0, T), Node->getOperand(2));
12260   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12261                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12262                        Node->getOperand(0),
12263                        Node->getOperand(1), negOp,
12264                        cast<AtomicSDNode>(Node)->getSrcValue(),
12265                        cast<AtomicSDNode>(Node)->getAlignment(),
12266                        cast<AtomicSDNode>(Node)->getOrdering(),
12267                        cast<AtomicSDNode>(Node)->getSynchScope());
12268 }
12269
12270 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12271   SDNode *Node = Op.getNode();
12272   DebugLoc dl = Node->getDebugLoc();
12273   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12274
12275   // Convert seq_cst store -> xchg
12276   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12277   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12278   //        (The only way to get a 16-byte store is cmpxchg16b)
12279   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12280   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12281       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12282     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12283                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12284                                  Node->getOperand(0),
12285                                  Node->getOperand(1), Node->getOperand(2),
12286                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12287                                  cast<AtomicSDNode>(Node)->getOrdering(),
12288                                  cast<AtomicSDNode>(Node)->getSynchScope());
12289     return Swap.getValue(1);
12290   }
12291   // Other atomic stores have a simple pattern.
12292   return Op;
12293 }
12294
12295 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12296   EVT VT = Op.getNode()->getValueType(0);
12297
12298   // Let legalize expand this if it isn't a legal type yet.
12299   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12300     return SDValue();
12301
12302   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12303
12304   unsigned Opc;
12305   bool ExtraOp = false;
12306   switch (Op.getOpcode()) {
12307   default: llvm_unreachable("Invalid code");
12308   case ISD::ADDC: Opc = X86ISD::ADD; break;
12309   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12310   case ISD::SUBC: Opc = X86ISD::SUB; break;
12311   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12312   }
12313
12314   if (!ExtraOp)
12315     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12316                        Op.getOperand(1));
12317   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12318                      Op.getOperand(1), Op.getOperand(2));
12319 }
12320
12321 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12322   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12323
12324   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12325   // which returns the values as { float, float } (in XMM0) or
12326   // { double, double } (which is returned in XMM0, XMM1).
12327   DebugLoc dl = Op.getDebugLoc();
12328   SDValue Arg = Op.getOperand(0);
12329   EVT ArgVT = Arg.getValueType();
12330   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12331
12332   ArgListTy Args;
12333   ArgListEntry Entry;
12334
12335   Entry.Node = Arg;
12336   Entry.Ty = ArgTy;
12337   Entry.isSExt = false;
12338   Entry.isZExt = false;
12339   Args.push_back(Entry);
12340
12341   bool isF64 = ArgVT == MVT::f64;
12342   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12343   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12344   // the results are returned via SRet in memory.
12345   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12346   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12347
12348   Type *RetTy = isF64
12349     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12350     : (Type*)VectorType::get(ArgTy, 4);
12351   TargetLowering::
12352     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12353                          false, false, false, false, 0,
12354                          CallingConv::C, /*isTaillCall=*/false,
12355                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12356                          Callee, Args, DAG, dl);
12357   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12358
12359   if (isF64)
12360     // Returned in xmm0 and xmm1.
12361     return CallResult.first;
12362
12363   // Returned in bits 0:31 and 32:64 xmm0.
12364   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12365                                CallResult.first, DAG.getIntPtrConstant(0));
12366   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12367                                CallResult.first, DAG.getIntPtrConstant(1));
12368   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12369   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12370 }
12371
12372 /// LowerOperation - Provide custom lowering hooks for some operations.
12373 ///
12374 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12375   switch (Op.getOpcode()) {
12376   default: llvm_unreachable("Should not custom lower this!");
12377   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12378   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12379   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12380   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12381   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12382   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12383   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12384   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12385   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12386   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12387   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12388   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12389   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12390   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12391   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12392   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12393   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12394   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12395   case ISD::SHL_PARTS:
12396   case ISD::SRA_PARTS:
12397   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12398   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12399   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12400   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12401   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12402   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12403   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12404   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12405   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12406   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12407   case ISD::FABS:               return LowerFABS(Op, DAG);
12408   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12409   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12410   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12411   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12412   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12413   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12414   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12415   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12416   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12417   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12418   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12419   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12420   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12421   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12422   case ISD::FRAME_TO_ARGS_OFFSET:
12423                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12424   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12425   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12426   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12427   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12428   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12429   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12430   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12431   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12432   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12433   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12434   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12435   case ISD::SRA:
12436   case ISD::SRL:
12437   case ISD::SHL:                return LowerShift(Op, DAG);
12438   case ISD::SADDO:
12439   case ISD::UADDO:
12440   case ISD::SSUBO:
12441   case ISD::USUBO:
12442   case ISD::SMULO:
12443   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12444   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12445   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12446   case ISD::ADDC:
12447   case ISD::ADDE:
12448   case ISD::SUBC:
12449   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12450   case ISD::ADD:                return LowerADD(Op, DAG);
12451   case ISD::SUB:                return LowerSUB(Op, DAG);
12452   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12453   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12454   }
12455 }
12456
12457 static void ReplaceATOMIC_LOAD(SDNode *Node,
12458                                   SmallVectorImpl<SDValue> &Results,
12459                                   SelectionDAG &DAG) {
12460   DebugLoc dl = Node->getDebugLoc();
12461   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12462
12463   // Convert wide load -> cmpxchg8b/cmpxchg16b
12464   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12465   //        (The only way to get a 16-byte load is cmpxchg16b)
12466   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12467   SDValue Zero = DAG.getConstant(0, VT);
12468   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12469                                Node->getOperand(0),
12470                                Node->getOperand(1), Zero, Zero,
12471                                cast<AtomicSDNode>(Node)->getMemOperand(),
12472                                cast<AtomicSDNode>(Node)->getOrdering(),
12473                                cast<AtomicSDNode>(Node)->getSynchScope());
12474   Results.push_back(Swap.getValue(0));
12475   Results.push_back(Swap.getValue(1));
12476 }
12477
12478 static void
12479 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12480                         SelectionDAG &DAG, unsigned NewOp) {
12481   DebugLoc dl = Node->getDebugLoc();
12482   assert (Node->getValueType(0) == MVT::i64 &&
12483           "Only know how to expand i64 atomics");
12484
12485   SDValue Chain = Node->getOperand(0);
12486   SDValue In1 = Node->getOperand(1);
12487   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12488                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12489   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12490                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12491   SDValue Ops[] = { Chain, In1, In2L, In2H };
12492   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12493   SDValue Result =
12494     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12495                             cast<MemSDNode>(Node)->getMemOperand());
12496   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12497   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12498   Results.push_back(Result.getValue(2));
12499 }
12500
12501 /// ReplaceNodeResults - Replace a node with an illegal result type
12502 /// with a new node built out of custom code.
12503 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12504                                            SmallVectorImpl<SDValue>&Results,
12505                                            SelectionDAG &DAG) const {
12506   DebugLoc dl = N->getDebugLoc();
12507   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12508   switch (N->getOpcode()) {
12509   default:
12510     llvm_unreachable("Do not know how to custom type legalize this operation!");
12511   case ISD::SIGN_EXTEND_INREG:
12512   case ISD::ADDC:
12513   case ISD::ADDE:
12514   case ISD::SUBC:
12515   case ISD::SUBE:
12516     // We don't want to expand or promote these.
12517     return;
12518   case ISD::FP_TO_SINT:
12519   case ISD::FP_TO_UINT: {
12520     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12521
12522     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12523       return;
12524
12525     std::pair<SDValue,SDValue> Vals =
12526         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12527     SDValue FIST = Vals.first, StackSlot = Vals.second;
12528     if (FIST.getNode() != 0) {
12529       EVT VT = N->getValueType(0);
12530       // Return a load from the stack slot.
12531       if (StackSlot.getNode() != 0)
12532         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12533                                       MachinePointerInfo(),
12534                                       false, false, false, 0));
12535       else
12536         Results.push_back(FIST);
12537     }
12538     return;
12539   }
12540   case ISD::UINT_TO_FP: {
12541     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12542     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12543         N->getValueType(0) != MVT::v2f32)
12544       return;
12545     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12546                                  N->getOperand(0));
12547     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12548                                      MVT::f64);
12549     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12550     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12551                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12552     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12553     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12554     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12555     return;
12556   }
12557   case ISD::FP_ROUND: {
12558     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12559         return;
12560     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12561     Results.push_back(V);
12562     return;
12563   }
12564   case ISD::READCYCLECOUNTER: {
12565     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12566     SDValue TheChain = N->getOperand(0);
12567     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12568     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12569                                      rd.getValue(1));
12570     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12571                                      eax.getValue(2));
12572     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12573     SDValue Ops[] = { eax, edx };
12574     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12575                                   array_lengthof(Ops)));
12576     Results.push_back(edx.getValue(1));
12577     return;
12578   }
12579   case ISD::ATOMIC_CMP_SWAP: {
12580     EVT T = N->getValueType(0);
12581     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12582     bool Regs64bit = T == MVT::i128;
12583     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12584     SDValue cpInL, cpInH;
12585     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12586                         DAG.getConstant(0, HalfT));
12587     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12588                         DAG.getConstant(1, HalfT));
12589     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12590                              Regs64bit ? X86::RAX : X86::EAX,
12591                              cpInL, SDValue());
12592     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12593                              Regs64bit ? X86::RDX : X86::EDX,
12594                              cpInH, cpInL.getValue(1));
12595     SDValue swapInL, swapInH;
12596     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12597                           DAG.getConstant(0, HalfT));
12598     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12599                           DAG.getConstant(1, HalfT));
12600     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12601                                Regs64bit ? X86::RBX : X86::EBX,
12602                                swapInL, cpInH.getValue(1));
12603     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12604                                Regs64bit ? X86::RCX : X86::ECX,
12605                                swapInH, swapInL.getValue(1));
12606     SDValue Ops[] = { swapInH.getValue(0),
12607                       N->getOperand(1),
12608                       swapInH.getValue(1) };
12609     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12610     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12611     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12612                                   X86ISD::LCMPXCHG8_DAG;
12613     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12614                                              Ops, array_lengthof(Ops), T, MMO);
12615     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12616                                         Regs64bit ? X86::RAX : X86::EAX,
12617                                         HalfT, Result.getValue(1));
12618     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12619                                         Regs64bit ? X86::RDX : X86::EDX,
12620                                         HalfT, cpOutL.getValue(2));
12621     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12622     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12623     Results.push_back(cpOutH.getValue(1));
12624     return;
12625   }
12626   case ISD::ATOMIC_LOAD_ADD:
12627   case ISD::ATOMIC_LOAD_AND:
12628   case ISD::ATOMIC_LOAD_NAND:
12629   case ISD::ATOMIC_LOAD_OR:
12630   case ISD::ATOMIC_LOAD_SUB:
12631   case ISD::ATOMIC_LOAD_XOR:
12632   case ISD::ATOMIC_LOAD_MAX:
12633   case ISD::ATOMIC_LOAD_MIN:
12634   case ISD::ATOMIC_LOAD_UMAX:
12635   case ISD::ATOMIC_LOAD_UMIN:
12636   case ISD::ATOMIC_SWAP: {
12637     unsigned Opc;
12638     switch (N->getOpcode()) {
12639     default: llvm_unreachable("Unexpected opcode");
12640     case ISD::ATOMIC_LOAD_ADD:
12641       Opc = X86ISD::ATOMADD64_DAG;
12642       break;
12643     case ISD::ATOMIC_LOAD_AND:
12644       Opc = X86ISD::ATOMAND64_DAG;
12645       break;
12646     case ISD::ATOMIC_LOAD_NAND:
12647       Opc = X86ISD::ATOMNAND64_DAG;
12648       break;
12649     case ISD::ATOMIC_LOAD_OR:
12650       Opc = X86ISD::ATOMOR64_DAG;
12651       break;
12652     case ISD::ATOMIC_LOAD_SUB:
12653       Opc = X86ISD::ATOMSUB64_DAG;
12654       break;
12655     case ISD::ATOMIC_LOAD_XOR:
12656       Opc = X86ISD::ATOMXOR64_DAG;
12657       break;
12658     case ISD::ATOMIC_LOAD_MAX:
12659       Opc = X86ISD::ATOMMAX64_DAG;
12660       break;
12661     case ISD::ATOMIC_LOAD_MIN:
12662       Opc = X86ISD::ATOMMIN64_DAG;
12663       break;
12664     case ISD::ATOMIC_LOAD_UMAX:
12665       Opc = X86ISD::ATOMUMAX64_DAG;
12666       break;
12667     case ISD::ATOMIC_LOAD_UMIN:
12668       Opc = X86ISD::ATOMUMIN64_DAG;
12669       break;
12670     case ISD::ATOMIC_SWAP:
12671       Opc = X86ISD::ATOMSWAP64_DAG;
12672       break;
12673     }
12674     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12675     return;
12676   }
12677   case ISD::ATOMIC_LOAD:
12678     ReplaceATOMIC_LOAD(N, Results, DAG);
12679   }
12680 }
12681
12682 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12683   switch (Opcode) {
12684   default: return NULL;
12685   case X86ISD::BSF:                return "X86ISD::BSF";
12686   case X86ISD::BSR:                return "X86ISD::BSR";
12687   case X86ISD::SHLD:               return "X86ISD::SHLD";
12688   case X86ISD::SHRD:               return "X86ISD::SHRD";
12689   case X86ISD::FAND:               return "X86ISD::FAND";
12690   case X86ISD::FOR:                return "X86ISD::FOR";
12691   case X86ISD::FXOR:               return "X86ISD::FXOR";
12692   case X86ISD::FSRL:               return "X86ISD::FSRL";
12693   case X86ISD::FILD:               return "X86ISD::FILD";
12694   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12695   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12696   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12697   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12698   case X86ISD::FLD:                return "X86ISD::FLD";
12699   case X86ISD::FST:                return "X86ISD::FST";
12700   case X86ISD::CALL:               return "X86ISD::CALL";
12701   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12702   case X86ISD::BT:                 return "X86ISD::BT";
12703   case X86ISD::CMP:                return "X86ISD::CMP";
12704   case X86ISD::COMI:               return "X86ISD::COMI";
12705   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12706   case X86ISD::SETCC:              return "X86ISD::SETCC";
12707   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12708   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12709   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12710   case X86ISD::CMOV:               return "X86ISD::CMOV";
12711   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12712   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12713   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12714   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12715   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12716   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12717   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12718   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12719   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12720   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12721   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12722   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12723   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12724   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12725   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12726   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12727   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12728   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12729   case X86ISD::HADD:               return "X86ISD::HADD";
12730   case X86ISD::HSUB:               return "X86ISD::HSUB";
12731   case X86ISD::FHADD:              return "X86ISD::FHADD";
12732   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12733   case X86ISD::UMAX:               return "X86ISD::UMAX";
12734   case X86ISD::UMIN:               return "X86ISD::UMIN";
12735   case X86ISD::SMAX:               return "X86ISD::SMAX";
12736   case X86ISD::SMIN:               return "X86ISD::SMIN";
12737   case X86ISD::FMAX:               return "X86ISD::FMAX";
12738   case X86ISD::FMIN:               return "X86ISD::FMIN";
12739   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12740   case X86ISD::FMINC:              return "X86ISD::FMINC";
12741   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12742   case X86ISD::FRCP:               return "X86ISD::FRCP";
12743   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12744   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12745   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12746   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12747   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12748   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12749   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12750   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12751   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12752   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12753   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12754   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12755   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12756   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12757   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12758   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12759   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12760   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12761   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12762   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12763   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12764   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12765   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12766   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12767   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12768   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12769   case X86ISD::VSHL:               return "X86ISD::VSHL";
12770   case X86ISD::VSRL:               return "X86ISD::VSRL";
12771   case X86ISD::VSRA:               return "X86ISD::VSRA";
12772   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12773   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12774   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12775   case X86ISD::CMPP:               return "X86ISD::CMPP";
12776   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12777   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12778   case X86ISD::ADD:                return "X86ISD::ADD";
12779   case X86ISD::SUB:                return "X86ISD::SUB";
12780   case X86ISD::ADC:                return "X86ISD::ADC";
12781   case X86ISD::SBB:                return "X86ISD::SBB";
12782   case X86ISD::SMUL:               return "X86ISD::SMUL";
12783   case X86ISD::UMUL:               return "X86ISD::UMUL";
12784   case X86ISD::INC:                return "X86ISD::INC";
12785   case X86ISD::DEC:                return "X86ISD::DEC";
12786   case X86ISD::OR:                 return "X86ISD::OR";
12787   case X86ISD::XOR:                return "X86ISD::XOR";
12788   case X86ISD::AND:                return "X86ISD::AND";
12789   case X86ISD::BLSI:               return "X86ISD::BLSI";
12790   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12791   case X86ISD::BLSR:               return "X86ISD::BLSR";
12792   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12793   case X86ISD::PTEST:              return "X86ISD::PTEST";
12794   case X86ISD::TESTP:              return "X86ISD::TESTP";
12795   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12796   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12797   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12798   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12799   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12800   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12801   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12802   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12803   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12804   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12805   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12806   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12807   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12808   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12809   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12810   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12811   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12812   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12813   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12814   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12815   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12816   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12817   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12818   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12819   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12820   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12821   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12822   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12823   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12824   case X86ISD::SAHF:               return "X86ISD::SAHF";
12825   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12826   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12827   case X86ISD::FMADD:              return "X86ISD::FMADD";
12828   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12829   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12830   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12831   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12832   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12833   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12834   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12835   case X86ISD::XTEST:              return "X86ISD::XTEST";
12836   }
12837 }
12838
12839 // isLegalAddressingMode - Return true if the addressing mode represented
12840 // by AM is legal for this target, for a load/store of the specified type.
12841 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12842                                               Type *Ty) const {
12843   // X86 supports extremely general addressing modes.
12844   CodeModel::Model M = getTargetMachine().getCodeModel();
12845   Reloc::Model R = getTargetMachine().getRelocationModel();
12846
12847   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12848   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12849     return false;
12850
12851   if (AM.BaseGV) {
12852     unsigned GVFlags =
12853       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12854
12855     // If a reference to this global requires an extra load, we can't fold it.
12856     if (isGlobalStubReference(GVFlags))
12857       return false;
12858
12859     // If BaseGV requires a register for the PIC base, we cannot also have a
12860     // BaseReg specified.
12861     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12862       return false;
12863
12864     // If lower 4G is not available, then we must use rip-relative addressing.
12865     if ((M != CodeModel::Small || R != Reloc::Static) &&
12866         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12867       return false;
12868   }
12869
12870   switch (AM.Scale) {
12871   case 0:
12872   case 1:
12873   case 2:
12874   case 4:
12875   case 8:
12876     // These scales always work.
12877     break;
12878   case 3:
12879   case 5:
12880   case 9:
12881     // These scales are formed with basereg+scalereg.  Only accept if there is
12882     // no basereg yet.
12883     if (AM.HasBaseReg)
12884       return false;
12885     break;
12886   default:  // Other stuff never works.
12887     return false;
12888   }
12889
12890   return true;
12891 }
12892
12893 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12894   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12895     return false;
12896   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12897   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12898   return NumBits1 > NumBits2;
12899 }
12900
12901 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12902   return isInt<32>(Imm);
12903 }
12904
12905 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12906   // Can also use sub to handle negated immediates.
12907   return isInt<32>(Imm);
12908 }
12909
12910 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12911   if (!VT1.isInteger() || !VT2.isInteger())
12912     return false;
12913   unsigned NumBits1 = VT1.getSizeInBits();
12914   unsigned NumBits2 = VT2.getSizeInBits();
12915   return NumBits1 > NumBits2;
12916 }
12917
12918 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12919   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12920   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12921 }
12922
12923 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12924   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12925   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12926 }
12927
12928 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12929   EVT VT1 = Val.getValueType();
12930   if (isZExtFree(VT1, VT2))
12931     return true;
12932
12933   if (Val.getOpcode() != ISD::LOAD)
12934     return false;
12935
12936   if (!VT1.isSimple() || !VT1.isInteger() ||
12937       !VT2.isSimple() || !VT2.isInteger())
12938     return false;
12939
12940   switch (VT1.getSimpleVT().SimpleTy) {
12941   default: break;
12942   case MVT::i8:
12943   case MVT::i16:
12944   case MVT::i32:
12945     // X86 has 8, 16, and 32-bit zero-extending loads.
12946     return true;
12947   }
12948
12949   return false;
12950 }
12951
12952 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12953   // i16 instructions are longer (0x66 prefix) and potentially slower.
12954   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12955 }
12956
12957 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12958 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12959 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12960 /// are assumed to be legal.
12961 bool
12962 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12963                                       EVT VT) const {
12964   // Very little shuffling can be done for 64-bit vectors right now.
12965   if (VT.getSizeInBits() == 64)
12966     return false;
12967
12968   // FIXME: pshufb, blends, shifts.
12969   return (VT.getVectorNumElements() == 2 ||
12970           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12971           isMOVLMask(M, VT) ||
12972           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12973           isPSHUFDMask(M, VT) ||
12974           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12975           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12976           isPALIGNRMask(M, VT, Subtarget) ||
12977           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12978           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12979           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12980           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
12981 }
12982
12983 bool
12984 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
12985                                           EVT VT) const {
12986   unsigned NumElts = VT.getVectorNumElements();
12987   // FIXME: This collection of masks seems suspect.
12988   if (NumElts == 2)
12989     return true;
12990   if (NumElts == 4 && VT.is128BitVector()) {
12991     return (isMOVLMask(Mask, VT)  ||
12992             isCommutedMOVLMask(Mask, VT, true) ||
12993             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
12994             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
12995   }
12996   return false;
12997 }
12998
12999 //===----------------------------------------------------------------------===//
13000 //                           X86 Scheduler Hooks
13001 //===----------------------------------------------------------------------===//
13002
13003 /// Utility function to emit xbegin specifying the start of an RTM region.
13004 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13005                                      const TargetInstrInfo *TII) {
13006   DebugLoc DL = MI->getDebugLoc();
13007
13008   const BasicBlock *BB = MBB->getBasicBlock();
13009   MachineFunction::iterator I = MBB;
13010   ++I;
13011
13012   // For the v = xbegin(), we generate
13013   //
13014   // thisMBB:
13015   //  xbegin sinkMBB
13016   //
13017   // mainMBB:
13018   //  eax = -1
13019   //
13020   // sinkMBB:
13021   //  v = eax
13022
13023   MachineBasicBlock *thisMBB = MBB;
13024   MachineFunction *MF = MBB->getParent();
13025   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13026   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13027   MF->insert(I, mainMBB);
13028   MF->insert(I, sinkMBB);
13029
13030   // Transfer the remainder of BB and its successor edges to sinkMBB.
13031   sinkMBB->splice(sinkMBB->begin(), MBB,
13032                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13033   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13034
13035   // thisMBB:
13036   //  xbegin sinkMBB
13037   //  # fallthrough to mainMBB
13038   //  # abortion to sinkMBB
13039   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13040   thisMBB->addSuccessor(mainMBB);
13041   thisMBB->addSuccessor(sinkMBB);
13042
13043   // mainMBB:
13044   //  EAX = -1
13045   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13046   mainMBB->addSuccessor(sinkMBB);
13047
13048   // sinkMBB:
13049   // EAX is live into the sinkMBB
13050   sinkMBB->addLiveIn(X86::EAX);
13051   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13052           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13053     .addReg(X86::EAX);
13054
13055   MI->eraseFromParent();
13056   return sinkMBB;
13057 }
13058
13059 // Get CMPXCHG opcode for the specified data type.
13060 static unsigned getCmpXChgOpcode(EVT VT) {
13061   switch (VT.getSimpleVT().SimpleTy) {
13062   case MVT::i8:  return X86::LCMPXCHG8;
13063   case MVT::i16: return X86::LCMPXCHG16;
13064   case MVT::i32: return X86::LCMPXCHG32;
13065   case MVT::i64: return X86::LCMPXCHG64;
13066   default:
13067     break;
13068   }
13069   llvm_unreachable("Invalid operand size!");
13070 }
13071
13072 // Get LOAD opcode for the specified data type.
13073 static unsigned getLoadOpcode(EVT VT) {
13074   switch (VT.getSimpleVT().SimpleTy) {
13075   case MVT::i8:  return X86::MOV8rm;
13076   case MVT::i16: return X86::MOV16rm;
13077   case MVT::i32: return X86::MOV32rm;
13078   case MVT::i64: return X86::MOV64rm;
13079   default:
13080     break;
13081   }
13082   llvm_unreachable("Invalid operand size!");
13083 }
13084
13085 // Get opcode of the non-atomic one from the specified atomic instruction.
13086 static unsigned getNonAtomicOpcode(unsigned Opc) {
13087   switch (Opc) {
13088   case X86::ATOMAND8:  return X86::AND8rr;
13089   case X86::ATOMAND16: return X86::AND16rr;
13090   case X86::ATOMAND32: return X86::AND32rr;
13091   case X86::ATOMAND64: return X86::AND64rr;
13092   case X86::ATOMOR8:   return X86::OR8rr;
13093   case X86::ATOMOR16:  return X86::OR16rr;
13094   case X86::ATOMOR32:  return X86::OR32rr;
13095   case X86::ATOMOR64:  return X86::OR64rr;
13096   case X86::ATOMXOR8:  return X86::XOR8rr;
13097   case X86::ATOMXOR16: return X86::XOR16rr;
13098   case X86::ATOMXOR32: return X86::XOR32rr;
13099   case X86::ATOMXOR64: return X86::XOR64rr;
13100   }
13101   llvm_unreachable("Unhandled atomic-load-op opcode!");
13102 }
13103
13104 // Get opcode of the non-atomic one from the specified atomic instruction with
13105 // extra opcode.
13106 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13107                                                unsigned &ExtraOpc) {
13108   switch (Opc) {
13109   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13110   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13111   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13112   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13113   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13114   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13115   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13116   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13117   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13118   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13119   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13120   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13121   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13122   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13123   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13124   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13125   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13126   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13127   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13128   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13129   }
13130   llvm_unreachable("Unhandled atomic-load-op opcode!");
13131 }
13132
13133 // Get opcode of the non-atomic one from the specified atomic instruction for
13134 // 64-bit data type on 32-bit target.
13135 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13136   switch (Opc) {
13137   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13138   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13139   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13140   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13141   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13142   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13143   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13144   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13145   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13146   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13147   }
13148   llvm_unreachable("Unhandled atomic-load-op opcode!");
13149 }
13150
13151 // Get opcode of the non-atomic one from the specified atomic instruction for
13152 // 64-bit data type on 32-bit target with extra opcode.
13153 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13154                                                    unsigned &HiOpc,
13155                                                    unsigned &ExtraOpc) {
13156   switch (Opc) {
13157   case X86::ATOMNAND6432:
13158     ExtraOpc = X86::NOT32r;
13159     HiOpc = X86::AND32rr;
13160     return X86::AND32rr;
13161   }
13162   llvm_unreachable("Unhandled atomic-load-op opcode!");
13163 }
13164
13165 // Get pseudo CMOV opcode from the specified data type.
13166 static unsigned getPseudoCMOVOpc(EVT VT) {
13167   switch (VT.getSimpleVT().SimpleTy) {
13168   case MVT::i8:  return X86::CMOV_GR8;
13169   case MVT::i16: return X86::CMOV_GR16;
13170   case MVT::i32: return X86::CMOV_GR32;
13171   default:
13172     break;
13173   }
13174   llvm_unreachable("Unknown CMOV opcode!");
13175 }
13176
13177 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13178 // They will be translated into a spin-loop or compare-exchange loop from
13179 //
13180 //    ...
13181 //    dst = atomic-fetch-op MI.addr, MI.val
13182 //    ...
13183 //
13184 // to
13185 //
13186 //    ...
13187 //    t1 = LOAD MI.addr
13188 // loop:
13189 //    t4 = phi(t1, t3 / loop)
13190 //    t2 = OP MI.val, t4
13191 //    EAX = t4
13192 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13193 //    t3 = EAX
13194 //    JNE loop
13195 // sink:
13196 //    dst = t3
13197 //    ...
13198 MachineBasicBlock *
13199 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13200                                        MachineBasicBlock *MBB) const {
13201   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13202   DebugLoc DL = MI->getDebugLoc();
13203
13204   MachineFunction *MF = MBB->getParent();
13205   MachineRegisterInfo &MRI = MF->getRegInfo();
13206
13207   const BasicBlock *BB = MBB->getBasicBlock();
13208   MachineFunction::iterator I = MBB;
13209   ++I;
13210
13211   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13212          "Unexpected number of operands");
13213
13214   assert(MI->hasOneMemOperand() &&
13215          "Expected atomic-load-op to have one memoperand");
13216
13217   // Memory Reference
13218   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13219   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13220
13221   unsigned DstReg, SrcReg;
13222   unsigned MemOpndSlot;
13223
13224   unsigned CurOp = 0;
13225
13226   DstReg = MI->getOperand(CurOp++).getReg();
13227   MemOpndSlot = CurOp;
13228   CurOp += X86::AddrNumOperands;
13229   SrcReg = MI->getOperand(CurOp++).getReg();
13230
13231   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13232   MVT::SimpleValueType VT = *RC->vt_begin();
13233   unsigned t1 = MRI.createVirtualRegister(RC);
13234   unsigned t2 = MRI.createVirtualRegister(RC);
13235   unsigned t3 = MRI.createVirtualRegister(RC);
13236   unsigned t4 = MRI.createVirtualRegister(RC);
13237   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13238
13239   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13240   unsigned LOADOpc = getLoadOpcode(VT);
13241
13242   // For the atomic load-arith operator, we generate
13243   //
13244   //  thisMBB:
13245   //    t1 = LOAD [MI.addr]
13246   //  mainMBB:
13247   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13248   //    t1 = OP MI.val, EAX
13249   //    EAX = t4
13250   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13251   //    t3 = EAX
13252   //    JNE mainMBB
13253   //  sinkMBB:
13254   //    dst = t3
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   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13271   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13272     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13273     if (NewMO.isReg())
13274       NewMO.setIsKill(false);
13275     MIB.addOperand(NewMO);
13276   }
13277   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13278     unsigned flags = (*MMOI)->getFlags();
13279     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13280     MachineMemOperand *MMO =
13281       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13282                                (*MMOI)->getSize(),
13283                                (*MMOI)->getBaseAlignment(),
13284                                (*MMOI)->getTBAAInfo(),
13285                                (*MMOI)->getRanges());
13286     MIB.addMemOperand(MMO);
13287   }
13288
13289   thisMBB->addSuccessor(mainMBB);
13290
13291   // mainMBB:
13292   MachineBasicBlock *origMainMBB = mainMBB;
13293
13294   // Add a PHI.
13295   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13296                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13297
13298   unsigned Opc = MI->getOpcode();
13299   switch (Opc) {
13300   default:
13301     llvm_unreachable("Unhandled atomic-load-op opcode!");
13302   case X86::ATOMAND8:
13303   case X86::ATOMAND16:
13304   case X86::ATOMAND32:
13305   case X86::ATOMAND64:
13306   case X86::ATOMOR8:
13307   case X86::ATOMOR16:
13308   case X86::ATOMOR32:
13309   case X86::ATOMOR64:
13310   case X86::ATOMXOR8:
13311   case X86::ATOMXOR16:
13312   case X86::ATOMXOR32:
13313   case X86::ATOMXOR64: {
13314     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13315     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13316       .addReg(t4);
13317     break;
13318   }
13319   case X86::ATOMNAND8:
13320   case X86::ATOMNAND16:
13321   case X86::ATOMNAND32:
13322   case X86::ATOMNAND64: {
13323     unsigned Tmp = MRI.createVirtualRegister(RC);
13324     unsigned NOTOpc;
13325     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13326     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13327       .addReg(t4);
13328     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13329     break;
13330   }
13331   case X86::ATOMMAX8:
13332   case X86::ATOMMAX16:
13333   case X86::ATOMMAX32:
13334   case X86::ATOMMAX64:
13335   case X86::ATOMMIN8:
13336   case X86::ATOMMIN16:
13337   case X86::ATOMMIN32:
13338   case X86::ATOMMIN64:
13339   case X86::ATOMUMAX8:
13340   case X86::ATOMUMAX16:
13341   case X86::ATOMUMAX32:
13342   case X86::ATOMUMAX64:
13343   case X86::ATOMUMIN8:
13344   case X86::ATOMUMIN16:
13345   case X86::ATOMUMIN32:
13346   case X86::ATOMUMIN64: {
13347     unsigned CMPOpc;
13348     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13349
13350     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13351       .addReg(SrcReg)
13352       .addReg(t4);
13353
13354     if (Subtarget->hasCMov()) {
13355       if (VT != MVT::i8) {
13356         // Native support
13357         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13358           .addReg(SrcReg)
13359           .addReg(t4);
13360       } else {
13361         // Promote i8 to i32 to use CMOV32
13362         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13363         const TargetRegisterClass *RC32 =
13364           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13365         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13366         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13367         unsigned Tmp = MRI.createVirtualRegister(RC32);
13368
13369         unsigned Undef = MRI.createVirtualRegister(RC32);
13370         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13371
13372         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13373           .addReg(Undef)
13374           .addReg(SrcReg)
13375           .addImm(X86::sub_8bit);
13376         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13377           .addReg(Undef)
13378           .addReg(t4)
13379           .addImm(X86::sub_8bit);
13380
13381         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13382           .addReg(SrcReg32)
13383           .addReg(AccReg32);
13384
13385         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13386           .addReg(Tmp, 0, X86::sub_8bit);
13387       }
13388     } else {
13389       // Use pseudo select and lower them.
13390       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13391              "Invalid atomic-load-op transformation!");
13392       unsigned SelOpc = getPseudoCMOVOpc(VT);
13393       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13394       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13395       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13396               .addReg(SrcReg).addReg(t4)
13397               .addImm(CC);
13398       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13399       // Replace the original PHI node as mainMBB is changed after CMOV
13400       // lowering.
13401       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13402         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13403       Phi->eraseFromParent();
13404     }
13405     break;
13406   }
13407   }
13408
13409   // Copy PhyReg back from virtual register.
13410   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13411     .addReg(t4);
13412
13413   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13414   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13415     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13416     if (NewMO.isReg())
13417       NewMO.setIsKill(false);
13418     MIB.addOperand(NewMO);
13419   }
13420   MIB.addReg(t2);
13421   MIB.setMemRefs(MMOBegin, MMOEnd);
13422
13423   // Copy PhyReg back to virtual register.
13424   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13425     .addReg(PhyReg);
13426
13427   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13428
13429   mainMBB->addSuccessor(origMainMBB);
13430   mainMBB->addSuccessor(sinkMBB);
13431
13432   // sinkMBB:
13433   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13434           TII->get(TargetOpcode::COPY), DstReg)
13435     .addReg(t3);
13436
13437   MI->eraseFromParent();
13438   return sinkMBB;
13439 }
13440
13441 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13442 // instructions. They will be translated into a spin-loop or compare-exchange
13443 // loop from
13444 //
13445 //    ...
13446 //    dst = atomic-fetch-op MI.addr, MI.val
13447 //    ...
13448 //
13449 // to
13450 //
13451 //    ...
13452 //    t1L = LOAD [MI.addr + 0]
13453 //    t1H = LOAD [MI.addr + 4]
13454 // loop:
13455 //    t4L = phi(t1L, t3L / loop)
13456 //    t4H = phi(t1H, t3H / loop)
13457 //    t2L = OP MI.val.lo, t4L
13458 //    t2H = OP MI.val.hi, t4H
13459 //    EAX = t4L
13460 //    EDX = t4H
13461 //    EBX = t2L
13462 //    ECX = t2H
13463 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13464 //    t3L = EAX
13465 //    t3H = EDX
13466 //    JNE loop
13467 // sink:
13468 //    dstL = t3L
13469 //    dstH = t3H
13470 //    ...
13471 MachineBasicBlock *
13472 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13473                                            MachineBasicBlock *MBB) const {
13474   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13475   DebugLoc DL = MI->getDebugLoc();
13476
13477   MachineFunction *MF = MBB->getParent();
13478   MachineRegisterInfo &MRI = MF->getRegInfo();
13479
13480   const BasicBlock *BB = MBB->getBasicBlock();
13481   MachineFunction::iterator I = MBB;
13482   ++I;
13483
13484   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13485          "Unexpected number of operands");
13486
13487   assert(MI->hasOneMemOperand() &&
13488          "Expected atomic-load-op32 to have one memoperand");
13489
13490   // Memory Reference
13491   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13492   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13493
13494   unsigned DstLoReg, DstHiReg;
13495   unsigned SrcLoReg, SrcHiReg;
13496   unsigned MemOpndSlot;
13497
13498   unsigned CurOp = 0;
13499
13500   DstLoReg = MI->getOperand(CurOp++).getReg();
13501   DstHiReg = MI->getOperand(CurOp++).getReg();
13502   MemOpndSlot = CurOp;
13503   CurOp += X86::AddrNumOperands;
13504   SrcLoReg = MI->getOperand(CurOp++).getReg();
13505   SrcHiReg = MI->getOperand(CurOp++).getReg();
13506
13507   const TargetRegisterClass *RC = &X86::GR32RegClass;
13508   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13509
13510   unsigned t1L = MRI.createVirtualRegister(RC);
13511   unsigned t1H = MRI.createVirtualRegister(RC);
13512   unsigned t2L = MRI.createVirtualRegister(RC);
13513   unsigned t2H = MRI.createVirtualRegister(RC);
13514   unsigned t3L = MRI.createVirtualRegister(RC);
13515   unsigned t3H = MRI.createVirtualRegister(RC);
13516   unsigned t4L = MRI.createVirtualRegister(RC);
13517   unsigned t4H = MRI.createVirtualRegister(RC);
13518
13519   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13520   unsigned LOADOpc = X86::MOV32rm;
13521
13522   // For the atomic load-arith operator, we generate
13523   //
13524   //  thisMBB:
13525   //    t1L = LOAD [MI.addr + 0]
13526   //    t1H = LOAD [MI.addr + 4]
13527   //  mainMBB:
13528   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13529   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13530   //    t2L = OP MI.val.lo, t4L
13531   //    t2H = OP MI.val.hi, t4H
13532   //    EBX = t2L
13533   //    ECX = t2H
13534   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13535   //    t3L = EAX
13536   //    t3H = EDX
13537   //    JNE loop
13538   //  sinkMBB:
13539   //    dstL = t3L
13540   //    dstH = t3H
13541
13542   MachineBasicBlock *thisMBB = MBB;
13543   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13544   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13545   MF->insert(I, mainMBB);
13546   MF->insert(I, sinkMBB);
13547
13548   MachineInstrBuilder MIB;
13549
13550   // Transfer the remainder of BB and its successor edges to sinkMBB.
13551   sinkMBB->splice(sinkMBB->begin(), MBB,
13552                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13553   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13554
13555   // thisMBB:
13556   // Lo
13557   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13558   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13559     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13560     if (NewMO.isReg())
13561       NewMO.setIsKill(false);
13562     MIB.addOperand(NewMO);
13563   }
13564   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13565     unsigned flags = (*MMOI)->getFlags();
13566     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13567     MachineMemOperand *MMO =
13568       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13569                                (*MMOI)->getSize(),
13570                                (*MMOI)->getBaseAlignment(),
13571                                (*MMOI)->getTBAAInfo(),
13572                                (*MMOI)->getRanges());
13573     MIB.addMemOperand(MMO);
13574   };
13575   MachineInstr *LowMI = MIB;
13576
13577   // Hi
13578   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13579   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13580     if (i == X86::AddrDisp) {
13581       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13582     } else {
13583       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13584       if (NewMO.isReg())
13585         NewMO.setIsKill(false);
13586       MIB.addOperand(NewMO);
13587     }
13588   }
13589   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13590
13591   thisMBB->addSuccessor(mainMBB);
13592
13593   // mainMBB:
13594   MachineBasicBlock *origMainMBB = mainMBB;
13595
13596   // Add PHIs.
13597   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13598                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13599   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13600                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13601
13602   unsigned Opc = MI->getOpcode();
13603   switch (Opc) {
13604   default:
13605     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13606   case X86::ATOMAND6432:
13607   case X86::ATOMOR6432:
13608   case X86::ATOMXOR6432:
13609   case X86::ATOMADD6432:
13610   case X86::ATOMSUB6432: {
13611     unsigned HiOpc;
13612     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13613     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13614       .addReg(SrcLoReg);
13615     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13616       .addReg(SrcHiReg);
13617     break;
13618   }
13619   case X86::ATOMNAND6432: {
13620     unsigned HiOpc, NOTOpc;
13621     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13622     unsigned TmpL = MRI.createVirtualRegister(RC);
13623     unsigned TmpH = MRI.createVirtualRegister(RC);
13624     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13625       .addReg(t4L);
13626     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13627       .addReg(t4H);
13628     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13629     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13630     break;
13631   }
13632   case X86::ATOMMAX6432:
13633   case X86::ATOMMIN6432:
13634   case X86::ATOMUMAX6432:
13635   case X86::ATOMUMIN6432: {
13636     unsigned HiOpc;
13637     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13638     unsigned cL = MRI.createVirtualRegister(RC8);
13639     unsigned cH = MRI.createVirtualRegister(RC8);
13640     unsigned cL32 = MRI.createVirtualRegister(RC);
13641     unsigned cH32 = MRI.createVirtualRegister(RC);
13642     unsigned cc = MRI.createVirtualRegister(RC);
13643     // cl := cmp src_lo, lo
13644     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13645       .addReg(SrcLoReg).addReg(t4L);
13646     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13647     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13648     // ch := cmp src_hi, hi
13649     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13650       .addReg(SrcHiReg).addReg(t4H);
13651     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13652     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13653     // cc := if (src_hi == hi) ? cl : ch;
13654     if (Subtarget->hasCMov()) {
13655       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13656         .addReg(cH32).addReg(cL32);
13657     } else {
13658       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13659               .addReg(cH32).addReg(cL32)
13660               .addImm(X86::COND_E);
13661       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13662     }
13663     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13664     if (Subtarget->hasCMov()) {
13665       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13666         .addReg(SrcLoReg).addReg(t4L);
13667       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13668         .addReg(SrcHiReg).addReg(t4H);
13669     } else {
13670       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13671               .addReg(SrcLoReg).addReg(t4L)
13672               .addImm(X86::COND_NE);
13673       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13674       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13675       // 2nd CMOV lowering.
13676       mainMBB->addLiveIn(X86::EFLAGS);
13677       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13678               .addReg(SrcHiReg).addReg(t4H)
13679               .addImm(X86::COND_NE);
13680       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13681       // Replace the original PHI node as mainMBB is changed after CMOV
13682       // lowering.
13683       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13684         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13685       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13686         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13687       PhiL->eraseFromParent();
13688       PhiH->eraseFromParent();
13689     }
13690     break;
13691   }
13692   case X86::ATOMSWAP6432: {
13693     unsigned HiOpc;
13694     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13695     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13696     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13697     break;
13698   }
13699   }
13700
13701   // Copy EDX:EAX back from HiReg:LoReg
13702   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13703   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13704   // Copy ECX:EBX from t1H:t1L
13705   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13706   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13707
13708   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13709   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13710     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13711     if (NewMO.isReg())
13712       NewMO.setIsKill(false);
13713     MIB.addOperand(NewMO);
13714   }
13715   MIB.setMemRefs(MMOBegin, MMOEnd);
13716
13717   // Copy EDX:EAX back to t3H:t3L
13718   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13719   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13720
13721   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13722
13723   mainMBB->addSuccessor(origMainMBB);
13724   mainMBB->addSuccessor(sinkMBB);
13725
13726   // sinkMBB:
13727   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13728           TII->get(TargetOpcode::COPY), DstLoReg)
13729     .addReg(t3L);
13730   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13731           TII->get(TargetOpcode::COPY), DstHiReg)
13732     .addReg(t3H);
13733
13734   MI->eraseFromParent();
13735   return sinkMBB;
13736 }
13737
13738 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13739 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13740 // in the .td file.
13741 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13742                                        const TargetInstrInfo *TII) {
13743   unsigned Opc;
13744   switch (MI->getOpcode()) {
13745   default: llvm_unreachable("illegal opcode!");
13746   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13747   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13748   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13749   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13750   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13751   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13752   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13753   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13754   }
13755
13756   DebugLoc dl = MI->getDebugLoc();
13757   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13758
13759   unsigned NumArgs = MI->getNumOperands();
13760   for (unsigned i = 1; i < NumArgs; ++i) {
13761     MachineOperand &Op = MI->getOperand(i);
13762     if (!(Op.isReg() && Op.isImplicit()))
13763       MIB.addOperand(Op);
13764   }
13765   if (MI->hasOneMemOperand())
13766     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13767
13768   BuildMI(*BB, MI, dl,
13769     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13770     .addReg(X86::XMM0);
13771
13772   MI->eraseFromParent();
13773   return BB;
13774 }
13775
13776 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13777 // defs in an instruction pattern
13778 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13779                                        const TargetInstrInfo *TII) {
13780   unsigned Opc;
13781   switch (MI->getOpcode()) {
13782   default: llvm_unreachable("illegal opcode!");
13783   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13784   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13785   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13786   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13787   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13788   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13789   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13790   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13791   }
13792
13793   DebugLoc dl = MI->getDebugLoc();
13794   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13795
13796   unsigned NumArgs = MI->getNumOperands(); // remove the results
13797   for (unsigned i = 1; i < NumArgs; ++i) {
13798     MachineOperand &Op = MI->getOperand(i);
13799     if (!(Op.isReg() && Op.isImplicit()))
13800       MIB.addOperand(Op);
13801   }
13802   if (MI->hasOneMemOperand())
13803     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13804
13805   BuildMI(*BB, MI, dl,
13806     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13807     .addReg(X86::ECX);
13808
13809   MI->eraseFromParent();
13810   return BB;
13811 }
13812
13813 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13814                                        const TargetInstrInfo *TII,
13815                                        const X86Subtarget* Subtarget) {
13816   DebugLoc dl = MI->getDebugLoc();
13817
13818   // Address into RAX/EAX, other two args into ECX, EDX.
13819   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13820   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13821   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13822   for (int i = 0; i < X86::AddrNumOperands; ++i)
13823     MIB.addOperand(MI->getOperand(i));
13824
13825   unsigned ValOps = X86::AddrNumOperands;
13826   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13827     .addReg(MI->getOperand(ValOps).getReg());
13828   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13829     .addReg(MI->getOperand(ValOps+1).getReg());
13830
13831   // The instruction doesn't actually take any operands though.
13832   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13833
13834   MI->eraseFromParent(); // The pseudo is gone now.
13835   return BB;
13836 }
13837
13838 MachineBasicBlock *
13839 X86TargetLowering::EmitVAARG64WithCustomInserter(
13840                    MachineInstr *MI,
13841                    MachineBasicBlock *MBB) const {
13842   // Emit va_arg instruction on X86-64.
13843
13844   // Operands to this pseudo-instruction:
13845   // 0  ) Output        : destination address (reg)
13846   // 1-5) Input         : va_list address (addr, i64mem)
13847   // 6  ) ArgSize       : Size (in bytes) of vararg type
13848   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13849   // 8  ) Align         : Alignment of type
13850   // 9  ) EFLAGS (implicit-def)
13851
13852   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13853   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13854
13855   unsigned DestReg = MI->getOperand(0).getReg();
13856   MachineOperand &Base = MI->getOperand(1);
13857   MachineOperand &Scale = MI->getOperand(2);
13858   MachineOperand &Index = MI->getOperand(3);
13859   MachineOperand &Disp = MI->getOperand(4);
13860   MachineOperand &Segment = MI->getOperand(5);
13861   unsigned ArgSize = MI->getOperand(6).getImm();
13862   unsigned ArgMode = MI->getOperand(7).getImm();
13863   unsigned Align = MI->getOperand(8).getImm();
13864
13865   // Memory Reference
13866   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13867   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13868   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13869
13870   // Machine Information
13871   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13872   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13873   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13874   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13875   DebugLoc DL = MI->getDebugLoc();
13876
13877   // struct va_list {
13878   //   i32   gp_offset
13879   //   i32   fp_offset
13880   //   i64   overflow_area (address)
13881   //   i64   reg_save_area (address)
13882   // }
13883   // sizeof(va_list) = 24
13884   // alignment(va_list) = 8
13885
13886   unsigned TotalNumIntRegs = 6;
13887   unsigned TotalNumXMMRegs = 8;
13888   bool UseGPOffset = (ArgMode == 1);
13889   bool UseFPOffset = (ArgMode == 2);
13890   unsigned MaxOffset = TotalNumIntRegs * 8 +
13891                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13892
13893   /* Align ArgSize to a multiple of 8 */
13894   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13895   bool NeedsAlign = (Align > 8);
13896
13897   MachineBasicBlock *thisMBB = MBB;
13898   MachineBasicBlock *overflowMBB;
13899   MachineBasicBlock *offsetMBB;
13900   MachineBasicBlock *endMBB;
13901
13902   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13903   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13904   unsigned OffsetReg = 0;
13905
13906   if (!UseGPOffset && !UseFPOffset) {
13907     // If we only pull from the overflow region, we don't create a branch.
13908     // We don't need to alter control flow.
13909     OffsetDestReg = 0; // unused
13910     OverflowDestReg = DestReg;
13911
13912     offsetMBB = NULL;
13913     overflowMBB = thisMBB;
13914     endMBB = thisMBB;
13915   } else {
13916     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13917     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13918     // If not, pull from overflow_area. (branch to overflowMBB)
13919     //
13920     //       thisMBB
13921     //         |     .
13922     //         |        .
13923     //     offsetMBB   overflowMBB
13924     //         |        .
13925     //         |     .
13926     //        endMBB
13927
13928     // Registers for the PHI in endMBB
13929     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13930     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13931
13932     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13933     MachineFunction *MF = MBB->getParent();
13934     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13935     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13936     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13937
13938     MachineFunction::iterator MBBIter = MBB;
13939     ++MBBIter;
13940
13941     // Insert the new basic blocks
13942     MF->insert(MBBIter, offsetMBB);
13943     MF->insert(MBBIter, overflowMBB);
13944     MF->insert(MBBIter, endMBB);
13945
13946     // Transfer the remainder of MBB and its successor edges to endMBB.
13947     endMBB->splice(endMBB->begin(), thisMBB,
13948                     llvm::next(MachineBasicBlock::iterator(MI)),
13949                     thisMBB->end());
13950     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13951
13952     // Make offsetMBB and overflowMBB successors of thisMBB
13953     thisMBB->addSuccessor(offsetMBB);
13954     thisMBB->addSuccessor(overflowMBB);
13955
13956     // endMBB is a successor of both offsetMBB and overflowMBB
13957     offsetMBB->addSuccessor(endMBB);
13958     overflowMBB->addSuccessor(endMBB);
13959
13960     // Load the offset value into a register
13961     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13962     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13963       .addOperand(Base)
13964       .addOperand(Scale)
13965       .addOperand(Index)
13966       .addDisp(Disp, UseFPOffset ? 4 : 0)
13967       .addOperand(Segment)
13968       .setMemRefs(MMOBegin, MMOEnd);
13969
13970     // Check if there is enough room left to pull this argument.
13971     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13972       .addReg(OffsetReg)
13973       .addImm(MaxOffset + 8 - ArgSizeA8);
13974
13975     // Branch to "overflowMBB" if offset >= max
13976     // Fall through to "offsetMBB" otherwise
13977     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13978       .addMBB(overflowMBB);
13979   }
13980
13981   // In offsetMBB, emit code to use the reg_save_area.
13982   if (offsetMBB) {
13983     assert(OffsetReg != 0);
13984
13985     // Read the reg_save_area address.
13986     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
13987     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
13988       .addOperand(Base)
13989       .addOperand(Scale)
13990       .addOperand(Index)
13991       .addDisp(Disp, 16)
13992       .addOperand(Segment)
13993       .setMemRefs(MMOBegin, MMOEnd);
13994
13995     // Zero-extend the offset
13996     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
13997       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
13998         .addImm(0)
13999         .addReg(OffsetReg)
14000         .addImm(X86::sub_32bit);
14001
14002     // Add the offset to the reg_save_area to get the final address.
14003     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14004       .addReg(OffsetReg64)
14005       .addReg(RegSaveReg);
14006
14007     // Compute the offset for the next argument
14008     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14009     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14010       .addReg(OffsetReg)
14011       .addImm(UseFPOffset ? 16 : 8);
14012
14013     // Store it back into the va_list.
14014     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14015       .addOperand(Base)
14016       .addOperand(Scale)
14017       .addOperand(Index)
14018       .addDisp(Disp, UseFPOffset ? 4 : 0)
14019       .addOperand(Segment)
14020       .addReg(NextOffsetReg)
14021       .setMemRefs(MMOBegin, MMOEnd);
14022
14023     // Jump to endMBB
14024     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14025       .addMBB(endMBB);
14026   }
14027
14028   //
14029   // Emit code to use overflow area
14030   //
14031
14032   // Load the overflow_area address into a register.
14033   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14034   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14035     .addOperand(Base)
14036     .addOperand(Scale)
14037     .addOperand(Index)
14038     .addDisp(Disp, 8)
14039     .addOperand(Segment)
14040     .setMemRefs(MMOBegin, MMOEnd);
14041
14042   // If we need to align it, do so. Otherwise, just copy the address
14043   // to OverflowDestReg.
14044   if (NeedsAlign) {
14045     // Align the overflow address
14046     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14047     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14048
14049     // aligned_addr = (addr + (align-1)) & ~(align-1)
14050     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14051       .addReg(OverflowAddrReg)
14052       .addImm(Align-1);
14053
14054     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14055       .addReg(TmpReg)
14056       .addImm(~(uint64_t)(Align-1));
14057   } else {
14058     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14059       .addReg(OverflowAddrReg);
14060   }
14061
14062   // Compute the next overflow address after this argument.
14063   // (the overflow address should be kept 8-byte aligned)
14064   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14065   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14066     .addReg(OverflowDestReg)
14067     .addImm(ArgSizeA8);
14068
14069   // Store the new overflow address.
14070   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14071     .addOperand(Base)
14072     .addOperand(Scale)
14073     .addOperand(Index)
14074     .addDisp(Disp, 8)
14075     .addOperand(Segment)
14076     .addReg(NextAddrReg)
14077     .setMemRefs(MMOBegin, MMOEnd);
14078
14079   // If we branched, emit the PHI to the front of endMBB.
14080   if (offsetMBB) {
14081     BuildMI(*endMBB, endMBB->begin(), DL,
14082             TII->get(X86::PHI), DestReg)
14083       .addReg(OffsetDestReg).addMBB(offsetMBB)
14084       .addReg(OverflowDestReg).addMBB(overflowMBB);
14085   }
14086
14087   // Erase the pseudo instruction
14088   MI->eraseFromParent();
14089
14090   return endMBB;
14091 }
14092
14093 MachineBasicBlock *
14094 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14095                                                  MachineInstr *MI,
14096                                                  MachineBasicBlock *MBB) const {
14097   // Emit code to save XMM registers to the stack. The ABI says that the
14098   // number of registers to save is given in %al, so it's theoretically
14099   // possible to do an indirect jump trick to avoid saving all of them,
14100   // however this code takes a simpler approach and just executes all
14101   // of the stores if %al is non-zero. It's less code, and it's probably
14102   // easier on the hardware branch predictor, and stores aren't all that
14103   // expensive anyway.
14104
14105   // Create the new basic blocks. One block contains all the XMM stores,
14106   // and one block is the final destination regardless of whether any
14107   // stores were performed.
14108   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14109   MachineFunction *F = MBB->getParent();
14110   MachineFunction::iterator MBBIter = MBB;
14111   ++MBBIter;
14112   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14113   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14114   F->insert(MBBIter, XMMSaveMBB);
14115   F->insert(MBBIter, EndMBB);
14116
14117   // Transfer the remainder of MBB and its successor edges to EndMBB.
14118   EndMBB->splice(EndMBB->begin(), MBB,
14119                  llvm::next(MachineBasicBlock::iterator(MI)),
14120                  MBB->end());
14121   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14122
14123   // The original block will now fall through to the XMM save block.
14124   MBB->addSuccessor(XMMSaveMBB);
14125   // The XMMSaveMBB will fall through to the end block.
14126   XMMSaveMBB->addSuccessor(EndMBB);
14127
14128   // Now add the instructions.
14129   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14130   DebugLoc DL = MI->getDebugLoc();
14131
14132   unsigned CountReg = MI->getOperand(0).getReg();
14133   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14134   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14135
14136   if (!Subtarget->isTargetWin64()) {
14137     // If %al is 0, branch around the XMM save block.
14138     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14139     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14140     MBB->addSuccessor(EndMBB);
14141   }
14142
14143   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14144   // In the XMM save block, save all the XMM argument registers.
14145   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14146     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14147     MachineMemOperand *MMO =
14148       F->getMachineMemOperand(
14149           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14150         MachineMemOperand::MOStore,
14151         /*Size=*/16, /*Align=*/16);
14152     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14153       .addFrameIndex(RegSaveFrameIndex)
14154       .addImm(/*Scale=*/1)
14155       .addReg(/*IndexReg=*/0)
14156       .addImm(/*Disp=*/Offset)
14157       .addReg(/*Segment=*/0)
14158       .addReg(MI->getOperand(i).getReg())
14159       .addMemOperand(MMO);
14160   }
14161
14162   MI->eraseFromParent();   // The pseudo instruction is gone now.
14163
14164   return EndMBB;
14165 }
14166
14167 // The EFLAGS operand of SelectItr might be missing a kill marker
14168 // because there were multiple uses of EFLAGS, and ISel didn't know
14169 // which to mark. Figure out whether SelectItr should have had a
14170 // kill marker, and set it if it should. Returns the correct kill
14171 // marker value.
14172 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14173                                      MachineBasicBlock* BB,
14174                                      const TargetRegisterInfo* TRI) {
14175   // Scan forward through BB for a use/def of EFLAGS.
14176   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14177   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14178     const MachineInstr& mi = *miI;
14179     if (mi.readsRegister(X86::EFLAGS))
14180       return false;
14181     if (mi.definesRegister(X86::EFLAGS))
14182       break; // Should have kill-flag - update below.
14183   }
14184
14185   // If we hit the end of the block, check whether EFLAGS is live into a
14186   // successor.
14187   if (miI == BB->end()) {
14188     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14189                                           sEnd = BB->succ_end();
14190          sItr != sEnd; ++sItr) {
14191       MachineBasicBlock* succ = *sItr;
14192       if (succ->isLiveIn(X86::EFLAGS))
14193         return false;
14194     }
14195   }
14196
14197   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14198   // out. SelectMI should have a kill flag on EFLAGS.
14199   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14200   return true;
14201 }
14202
14203 MachineBasicBlock *
14204 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14205                                      MachineBasicBlock *BB) const {
14206   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14207   DebugLoc DL = MI->getDebugLoc();
14208
14209   // To "insert" a SELECT_CC instruction, we actually have to insert the
14210   // diamond control-flow pattern.  The incoming instruction knows the
14211   // destination vreg to set, the condition code register to branch on, the
14212   // true/false values to select between, and a branch opcode to use.
14213   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14214   MachineFunction::iterator It = BB;
14215   ++It;
14216
14217   //  thisMBB:
14218   //  ...
14219   //   TrueVal = ...
14220   //   cmpTY ccX, r1, r2
14221   //   bCC copy1MBB
14222   //   fallthrough --> copy0MBB
14223   MachineBasicBlock *thisMBB = BB;
14224   MachineFunction *F = BB->getParent();
14225   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14226   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14227   F->insert(It, copy0MBB);
14228   F->insert(It, sinkMBB);
14229
14230   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14231   // live into the sink and copy blocks.
14232   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14233   if (!MI->killsRegister(X86::EFLAGS) &&
14234       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14235     copy0MBB->addLiveIn(X86::EFLAGS);
14236     sinkMBB->addLiveIn(X86::EFLAGS);
14237   }
14238
14239   // Transfer the remainder of BB and its successor edges to sinkMBB.
14240   sinkMBB->splice(sinkMBB->begin(), BB,
14241                   llvm::next(MachineBasicBlock::iterator(MI)),
14242                   BB->end());
14243   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14244
14245   // Add the true and fallthrough blocks as its successors.
14246   BB->addSuccessor(copy0MBB);
14247   BB->addSuccessor(sinkMBB);
14248
14249   // Create the conditional branch instruction.
14250   unsigned Opc =
14251     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14252   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14253
14254   //  copy0MBB:
14255   //   %FalseValue = ...
14256   //   # fallthrough to sinkMBB
14257   copy0MBB->addSuccessor(sinkMBB);
14258
14259   //  sinkMBB:
14260   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14261   //  ...
14262   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14263           TII->get(X86::PHI), MI->getOperand(0).getReg())
14264     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14265     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14266
14267   MI->eraseFromParent();   // The pseudo instruction is gone now.
14268   return sinkMBB;
14269 }
14270
14271 MachineBasicBlock *
14272 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14273                                         bool Is64Bit) const {
14274   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14275   DebugLoc DL = MI->getDebugLoc();
14276   MachineFunction *MF = BB->getParent();
14277   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14278
14279   assert(getTargetMachine().Options.EnableSegmentedStacks);
14280
14281   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14282   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14283
14284   // BB:
14285   //  ... [Till the alloca]
14286   // If stacklet is not large enough, jump to mallocMBB
14287   //
14288   // bumpMBB:
14289   //  Allocate by subtracting from RSP
14290   //  Jump to continueMBB
14291   //
14292   // mallocMBB:
14293   //  Allocate by call to runtime
14294   //
14295   // continueMBB:
14296   //  ...
14297   //  [rest of original BB]
14298   //
14299
14300   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14301   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14302   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14303
14304   MachineRegisterInfo &MRI = MF->getRegInfo();
14305   const TargetRegisterClass *AddrRegClass =
14306     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14307
14308   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14309     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14310     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14311     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14312     sizeVReg = MI->getOperand(1).getReg(),
14313     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14314
14315   MachineFunction::iterator MBBIter = BB;
14316   ++MBBIter;
14317
14318   MF->insert(MBBIter, bumpMBB);
14319   MF->insert(MBBIter, mallocMBB);
14320   MF->insert(MBBIter, continueMBB);
14321
14322   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14323                       (MachineBasicBlock::iterator(MI)), BB->end());
14324   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14325
14326   // Add code to the main basic block to check if the stack limit has been hit,
14327   // and if so, jump to mallocMBB otherwise to bumpMBB.
14328   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14329   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14330     .addReg(tmpSPVReg).addReg(sizeVReg);
14331   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14332     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14333     .addReg(SPLimitVReg);
14334   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14335
14336   // bumpMBB simply decreases the stack pointer, since we know the current
14337   // stacklet has enough space.
14338   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14339     .addReg(SPLimitVReg);
14340   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14341     .addReg(SPLimitVReg);
14342   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14343
14344   // Calls into a routine in libgcc to allocate more space from the heap.
14345   const uint32_t *RegMask =
14346     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14347   if (Is64Bit) {
14348     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14349       .addReg(sizeVReg);
14350     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14351       .addExternalSymbol("__morestack_allocate_stack_space")
14352       .addRegMask(RegMask)
14353       .addReg(X86::RDI, RegState::Implicit)
14354       .addReg(X86::RAX, RegState::ImplicitDefine);
14355   } else {
14356     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14357       .addImm(12);
14358     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14359     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14360       .addExternalSymbol("__morestack_allocate_stack_space")
14361       .addRegMask(RegMask)
14362       .addReg(X86::EAX, RegState::ImplicitDefine);
14363   }
14364
14365   if (!Is64Bit)
14366     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14367       .addImm(16);
14368
14369   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14370     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14371   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14372
14373   // Set up the CFG correctly.
14374   BB->addSuccessor(bumpMBB);
14375   BB->addSuccessor(mallocMBB);
14376   mallocMBB->addSuccessor(continueMBB);
14377   bumpMBB->addSuccessor(continueMBB);
14378
14379   // Take care of the PHI nodes.
14380   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14381           MI->getOperand(0).getReg())
14382     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14383     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14384
14385   // Delete the original pseudo instruction.
14386   MI->eraseFromParent();
14387
14388   // And we're done.
14389   return continueMBB;
14390 }
14391
14392 MachineBasicBlock *
14393 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14394                                           MachineBasicBlock *BB) const {
14395   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14396   DebugLoc DL = MI->getDebugLoc();
14397
14398   assert(!Subtarget->isTargetEnvMacho());
14399
14400   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14401   // non-trivial part is impdef of ESP.
14402
14403   if (Subtarget->isTargetWin64()) {
14404     if (Subtarget->isTargetCygMing()) {
14405       // ___chkstk(Mingw64):
14406       // Clobbers R10, R11, RAX and EFLAGS.
14407       // Updates RSP.
14408       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14409         .addExternalSymbol("___chkstk")
14410         .addReg(X86::RAX, RegState::Implicit)
14411         .addReg(X86::RSP, RegState::Implicit)
14412         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14413         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14414         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14415     } else {
14416       // __chkstk(MSVCRT): does not update stack pointer.
14417       // Clobbers R10, R11 and EFLAGS.
14418       // FIXME: RAX(allocated size) might be reused and not killed.
14419       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14420         .addExternalSymbol("__chkstk")
14421         .addReg(X86::RAX, RegState::Implicit)
14422         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14423       // RAX has the offset to subtracted from RSP.
14424       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14425         .addReg(X86::RSP)
14426         .addReg(X86::RAX);
14427     }
14428   } else {
14429     const char *StackProbeSymbol =
14430       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14431
14432     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14433       .addExternalSymbol(StackProbeSymbol)
14434       .addReg(X86::EAX, RegState::Implicit)
14435       .addReg(X86::ESP, RegState::Implicit)
14436       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14437       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14438       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14439   }
14440
14441   MI->eraseFromParent();   // The pseudo instruction is gone now.
14442   return BB;
14443 }
14444
14445 MachineBasicBlock *
14446 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14447                                       MachineBasicBlock *BB) const {
14448   // This is pretty easy.  We're taking the value that we received from
14449   // our load from the relocation, sticking it in either RDI (x86-64)
14450   // or EAX and doing an indirect call.  The return value will then
14451   // be in the normal return register.
14452   const X86InstrInfo *TII
14453     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14454   DebugLoc DL = MI->getDebugLoc();
14455   MachineFunction *F = BB->getParent();
14456
14457   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14458   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14459
14460   // Get a register mask for the lowered call.
14461   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14462   // proper register mask.
14463   const uint32_t *RegMask =
14464     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14465   if (Subtarget->is64Bit()) {
14466     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14467                                       TII->get(X86::MOV64rm), X86::RDI)
14468     .addReg(X86::RIP)
14469     .addImm(0).addReg(0)
14470     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14471                       MI->getOperand(3).getTargetFlags())
14472     .addReg(0);
14473     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14474     addDirectMem(MIB, X86::RDI);
14475     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14476   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14477     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14478                                       TII->get(X86::MOV32rm), X86::EAX)
14479     .addReg(0)
14480     .addImm(0).addReg(0)
14481     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14482                       MI->getOperand(3).getTargetFlags())
14483     .addReg(0);
14484     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14485     addDirectMem(MIB, X86::EAX);
14486     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14487   } else {
14488     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14489                                       TII->get(X86::MOV32rm), X86::EAX)
14490     .addReg(TII->getGlobalBaseReg(F))
14491     .addImm(0).addReg(0)
14492     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14493                       MI->getOperand(3).getTargetFlags())
14494     .addReg(0);
14495     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14496     addDirectMem(MIB, X86::EAX);
14497     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14498   }
14499
14500   MI->eraseFromParent(); // The pseudo instruction is gone now.
14501   return BB;
14502 }
14503
14504 MachineBasicBlock *
14505 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14506                                     MachineBasicBlock *MBB) const {
14507   DebugLoc DL = MI->getDebugLoc();
14508   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14509
14510   MachineFunction *MF = MBB->getParent();
14511   MachineRegisterInfo &MRI = MF->getRegInfo();
14512
14513   const BasicBlock *BB = MBB->getBasicBlock();
14514   MachineFunction::iterator I = MBB;
14515   ++I;
14516
14517   // Memory Reference
14518   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14519   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14520
14521   unsigned DstReg;
14522   unsigned MemOpndSlot = 0;
14523
14524   unsigned CurOp = 0;
14525
14526   DstReg = MI->getOperand(CurOp++).getReg();
14527   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14528   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14529   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14530   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14531
14532   MemOpndSlot = CurOp;
14533
14534   MVT PVT = getPointerTy();
14535   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14536          "Invalid Pointer Size!");
14537
14538   // For v = setjmp(buf), we generate
14539   //
14540   // thisMBB:
14541   //  buf[LabelOffset] = restoreMBB
14542   //  SjLjSetup restoreMBB
14543   //
14544   // mainMBB:
14545   //  v_main = 0
14546   //
14547   // sinkMBB:
14548   //  v = phi(main, restore)
14549   //
14550   // restoreMBB:
14551   //  v_restore = 1
14552
14553   MachineBasicBlock *thisMBB = MBB;
14554   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14555   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14556   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14557   MF->insert(I, mainMBB);
14558   MF->insert(I, sinkMBB);
14559   MF->push_back(restoreMBB);
14560
14561   MachineInstrBuilder MIB;
14562
14563   // Transfer the remainder of BB and its successor edges to sinkMBB.
14564   sinkMBB->splice(sinkMBB->begin(), MBB,
14565                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14566   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14567
14568   // thisMBB:
14569   unsigned PtrStoreOpc = 0;
14570   unsigned LabelReg = 0;
14571   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14572   Reloc::Model RM = getTargetMachine().getRelocationModel();
14573   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14574                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14575
14576   // Prepare IP either in reg or imm.
14577   if (!UseImmLabel) {
14578     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14579     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14580     LabelReg = MRI.createVirtualRegister(PtrRC);
14581     if (Subtarget->is64Bit()) {
14582       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14583               .addReg(X86::RIP)
14584               .addImm(0)
14585               .addReg(0)
14586               .addMBB(restoreMBB)
14587               .addReg(0);
14588     } else {
14589       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14590       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14591               .addReg(XII->getGlobalBaseReg(MF))
14592               .addImm(0)
14593               .addReg(0)
14594               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14595               .addReg(0);
14596     }
14597   } else
14598     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14599   // Store IP
14600   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14601   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14602     if (i == X86::AddrDisp)
14603       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14604     else
14605       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14606   }
14607   if (!UseImmLabel)
14608     MIB.addReg(LabelReg);
14609   else
14610     MIB.addMBB(restoreMBB);
14611   MIB.setMemRefs(MMOBegin, MMOEnd);
14612   // Setup
14613   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14614           .addMBB(restoreMBB);
14615   MIB.addRegMask(RegInfo->getNoPreservedMask());
14616   thisMBB->addSuccessor(mainMBB);
14617   thisMBB->addSuccessor(restoreMBB);
14618
14619   // mainMBB:
14620   //  EAX = 0
14621   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14622   mainMBB->addSuccessor(sinkMBB);
14623
14624   // sinkMBB:
14625   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14626           TII->get(X86::PHI), DstReg)
14627     .addReg(mainDstReg).addMBB(mainMBB)
14628     .addReg(restoreDstReg).addMBB(restoreMBB);
14629
14630   // restoreMBB:
14631   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14632   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14633   restoreMBB->addSuccessor(sinkMBB);
14634
14635   MI->eraseFromParent();
14636   return sinkMBB;
14637 }
14638
14639 MachineBasicBlock *
14640 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14641                                      MachineBasicBlock *MBB) const {
14642   DebugLoc DL = MI->getDebugLoc();
14643   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14644
14645   MachineFunction *MF = MBB->getParent();
14646   MachineRegisterInfo &MRI = MF->getRegInfo();
14647
14648   // Memory Reference
14649   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14650   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14651
14652   MVT PVT = getPointerTy();
14653   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14654          "Invalid Pointer Size!");
14655
14656   const TargetRegisterClass *RC =
14657     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14658   unsigned Tmp = MRI.createVirtualRegister(RC);
14659   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14660   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14661   unsigned SP = RegInfo->getStackRegister();
14662
14663   MachineInstrBuilder MIB;
14664
14665   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14666   const int64_t SPOffset = 2 * PVT.getStoreSize();
14667
14668   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14669   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14670
14671   // Reload FP
14672   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14673   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14674     MIB.addOperand(MI->getOperand(i));
14675   MIB.setMemRefs(MMOBegin, MMOEnd);
14676   // Reload IP
14677   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14678   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14679     if (i == X86::AddrDisp)
14680       MIB.addDisp(MI->getOperand(i), LabelOffset);
14681     else
14682       MIB.addOperand(MI->getOperand(i));
14683   }
14684   MIB.setMemRefs(MMOBegin, MMOEnd);
14685   // Reload SP
14686   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14687   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14688     if (i == X86::AddrDisp)
14689       MIB.addDisp(MI->getOperand(i), SPOffset);
14690     else
14691       MIB.addOperand(MI->getOperand(i));
14692   }
14693   MIB.setMemRefs(MMOBegin, MMOEnd);
14694   // Jump
14695   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14696
14697   MI->eraseFromParent();
14698   return MBB;
14699 }
14700
14701 MachineBasicBlock *
14702 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14703                                                MachineBasicBlock *BB) const {
14704   switch (MI->getOpcode()) {
14705   default: llvm_unreachable("Unexpected instr type to insert");
14706   case X86::TAILJMPd64:
14707   case X86::TAILJMPr64:
14708   case X86::TAILJMPm64:
14709     llvm_unreachable("TAILJMP64 would not be touched here.");
14710   case X86::TCRETURNdi64:
14711   case X86::TCRETURNri64:
14712   case X86::TCRETURNmi64:
14713     return BB;
14714   case X86::WIN_ALLOCA:
14715     return EmitLoweredWinAlloca(MI, BB);
14716   case X86::SEG_ALLOCA_32:
14717     return EmitLoweredSegAlloca(MI, BB, false);
14718   case X86::SEG_ALLOCA_64:
14719     return EmitLoweredSegAlloca(MI, BB, true);
14720   case X86::TLSCall_32:
14721   case X86::TLSCall_64:
14722     return EmitLoweredTLSCall(MI, BB);
14723   case X86::CMOV_GR8:
14724   case X86::CMOV_FR32:
14725   case X86::CMOV_FR64:
14726   case X86::CMOV_V4F32:
14727   case X86::CMOV_V2F64:
14728   case X86::CMOV_V2I64:
14729   case X86::CMOV_V8F32:
14730   case X86::CMOV_V4F64:
14731   case X86::CMOV_V4I64:
14732   case X86::CMOV_GR16:
14733   case X86::CMOV_GR32:
14734   case X86::CMOV_RFP32:
14735   case X86::CMOV_RFP64:
14736   case X86::CMOV_RFP80:
14737     return EmitLoweredSelect(MI, BB);
14738
14739   case X86::FP32_TO_INT16_IN_MEM:
14740   case X86::FP32_TO_INT32_IN_MEM:
14741   case X86::FP32_TO_INT64_IN_MEM:
14742   case X86::FP64_TO_INT16_IN_MEM:
14743   case X86::FP64_TO_INT32_IN_MEM:
14744   case X86::FP64_TO_INT64_IN_MEM:
14745   case X86::FP80_TO_INT16_IN_MEM:
14746   case X86::FP80_TO_INT32_IN_MEM:
14747   case X86::FP80_TO_INT64_IN_MEM: {
14748     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14749     DebugLoc DL = MI->getDebugLoc();
14750
14751     // Change the floating point control register to use "round towards zero"
14752     // mode when truncating to an integer value.
14753     MachineFunction *F = BB->getParent();
14754     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14755     addFrameReference(BuildMI(*BB, MI, DL,
14756                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14757
14758     // Load the old value of the high byte of the control word...
14759     unsigned OldCW =
14760       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14761     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14762                       CWFrameIdx);
14763
14764     // Set the high part to be round to zero...
14765     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14766       .addImm(0xC7F);
14767
14768     // Reload the modified control word now...
14769     addFrameReference(BuildMI(*BB, MI, DL,
14770                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14771
14772     // Restore the memory image of control word to original value
14773     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14774       .addReg(OldCW);
14775
14776     // Get the X86 opcode to use.
14777     unsigned Opc;
14778     switch (MI->getOpcode()) {
14779     default: llvm_unreachable("illegal opcode!");
14780     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14781     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14782     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14783     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14784     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14785     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14786     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14787     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14788     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14789     }
14790
14791     X86AddressMode AM;
14792     MachineOperand &Op = MI->getOperand(0);
14793     if (Op.isReg()) {
14794       AM.BaseType = X86AddressMode::RegBase;
14795       AM.Base.Reg = Op.getReg();
14796     } else {
14797       AM.BaseType = X86AddressMode::FrameIndexBase;
14798       AM.Base.FrameIndex = Op.getIndex();
14799     }
14800     Op = MI->getOperand(1);
14801     if (Op.isImm())
14802       AM.Scale = Op.getImm();
14803     Op = MI->getOperand(2);
14804     if (Op.isImm())
14805       AM.IndexReg = Op.getImm();
14806     Op = MI->getOperand(3);
14807     if (Op.isGlobal()) {
14808       AM.GV = Op.getGlobal();
14809     } else {
14810       AM.Disp = Op.getImm();
14811     }
14812     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14813                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14814
14815     // Reload the original control word now.
14816     addFrameReference(BuildMI(*BB, MI, DL,
14817                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14818
14819     MI->eraseFromParent();   // The pseudo instruction is gone now.
14820     return BB;
14821   }
14822     // String/text processing lowering.
14823   case X86::PCMPISTRM128REG:
14824   case X86::VPCMPISTRM128REG:
14825   case X86::PCMPISTRM128MEM:
14826   case X86::VPCMPISTRM128MEM:
14827   case X86::PCMPESTRM128REG:
14828   case X86::VPCMPESTRM128REG:
14829   case X86::PCMPESTRM128MEM:
14830   case X86::VPCMPESTRM128MEM:
14831     assert(Subtarget->hasSSE42() &&
14832            "Target must have SSE4.2 or AVX features enabled");
14833     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14834
14835   // String/text processing lowering.
14836   case X86::PCMPISTRIREG:
14837   case X86::VPCMPISTRIREG:
14838   case X86::PCMPISTRIMEM:
14839   case X86::VPCMPISTRIMEM:
14840   case X86::PCMPESTRIREG:
14841   case X86::VPCMPESTRIREG:
14842   case X86::PCMPESTRIMEM:
14843   case X86::VPCMPESTRIMEM:
14844     assert(Subtarget->hasSSE42() &&
14845            "Target must have SSE4.2 or AVX features enabled");
14846     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14847
14848   // Thread synchronization.
14849   case X86::MONITOR:
14850     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14851
14852   // xbegin
14853   case X86::XBEGIN:
14854     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14855
14856   // Atomic Lowering.
14857   case X86::ATOMAND8:
14858   case X86::ATOMAND16:
14859   case X86::ATOMAND32:
14860   case X86::ATOMAND64:
14861     // Fall through
14862   case X86::ATOMOR8:
14863   case X86::ATOMOR16:
14864   case X86::ATOMOR32:
14865   case X86::ATOMOR64:
14866     // Fall through
14867   case X86::ATOMXOR16:
14868   case X86::ATOMXOR8:
14869   case X86::ATOMXOR32:
14870   case X86::ATOMXOR64:
14871     // Fall through
14872   case X86::ATOMNAND8:
14873   case X86::ATOMNAND16:
14874   case X86::ATOMNAND32:
14875   case X86::ATOMNAND64:
14876     // Fall through
14877   case X86::ATOMMAX8:
14878   case X86::ATOMMAX16:
14879   case X86::ATOMMAX32:
14880   case X86::ATOMMAX64:
14881     // Fall through
14882   case X86::ATOMMIN8:
14883   case X86::ATOMMIN16:
14884   case X86::ATOMMIN32:
14885   case X86::ATOMMIN64:
14886     // Fall through
14887   case X86::ATOMUMAX8:
14888   case X86::ATOMUMAX16:
14889   case X86::ATOMUMAX32:
14890   case X86::ATOMUMAX64:
14891     // Fall through
14892   case X86::ATOMUMIN8:
14893   case X86::ATOMUMIN16:
14894   case X86::ATOMUMIN32:
14895   case X86::ATOMUMIN64:
14896     return EmitAtomicLoadArith(MI, BB);
14897
14898   // This group does 64-bit operations on a 32-bit host.
14899   case X86::ATOMAND6432:
14900   case X86::ATOMOR6432:
14901   case X86::ATOMXOR6432:
14902   case X86::ATOMNAND6432:
14903   case X86::ATOMADD6432:
14904   case X86::ATOMSUB6432:
14905   case X86::ATOMMAX6432:
14906   case X86::ATOMMIN6432:
14907   case X86::ATOMUMAX6432:
14908   case X86::ATOMUMIN6432:
14909   case X86::ATOMSWAP6432:
14910     return EmitAtomicLoadArith6432(MI, BB);
14911
14912   case X86::VASTART_SAVE_XMM_REGS:
14913     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14914
14915   case X86::VAARG_64:
14916     return EmitVAARG64WithCustomInserter(MI, BB);
14917
14918   case X86::EH_SjLj_SetJmp32:
14919   case X86::EH_SjLj_SetJmp64:
14920     return emitEHSjLjSetJmp(MI, BB);
14921
14922   case X86::EH_SjLj_LongJmp32:
14923   case X86::EH_SjLj_LongJmp64:
14924     return emitEHSjLjLongJmp(MI, BB);
14925   }
14926 }
14927
14928 //===----------------------------------------------------------------------===//
14929 //                           X86 Optimization Hooks
14930 //===----------------------------------------------------------------------===//
14931
14932 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14933                                                        APInt &KnownZero,
14934                                                        APInt &KnownOne,
14935                                                        const SelectionDAG &DAG,
14936                                                        unsigned Depth) const {
14937   unsigned BitWidth = KnownZero.getBitWidth();
14938   unsigned Opc = Op.getOpcode();
14939   assert((Opc >= ISD::BUILTIN_OP_END ||
14940           Opc == ISD::INTRINSIC_WO_CHAIN ||
14941           Opc == ISD::INTRINSIC_W_CHAIN ||
14942           Opc == ISD::INTRINSIC_VOID) &&
14943          "Should use MaskedValueIsZero if you don't know whether Op"
14944          " is a target node!");
14945
14946   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14947   switch (Opc) {
14948   default: break;
14949   case X86ISD::ADD:
14950   case X86ISD::SUB:
14951   case X86ISD::ADC:
14952   case X86ISD::SBB:
14953   case X86ISD::SMUL:
14954   case X86ISD::UMUL:
14955   case X86ISD::INC:
14956   case X86ISD::DEC:
14957   case X86ISD::OR:
14958   case X86ISD::XOR:
14959   case X86ISD::AND:
14960     // These nodes' second result is a boolean.
14961     if (Op.getResNo() == 0)
14962       break;
14963     // Fallthrough
14964   case X86ISD::SETCC:
14965     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14966     break;
14967   case ISD::INTRINSIC_WO_CHAIN: {
14968     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14969     unsigned NumLoBits = 0;
14970     switch (IntId) {
14971     default: break;
14972     case Intrinsic::x86_sse_movmsk_ps:
14973     case Intrinsic::x86_avx_movmsk_ps_256:
14974     case Intrinsic::x86_sse2_movmsk_pd:
14975     case Intrinsic::x86_avx_movmsk_pd_256:
14976     case Intrinsic::x86_mmx_pmovmskb:
14977     case Intrinsic::x86_sse2_pmovmskb_128:
14978     case Intrinsic::x86_avx2_pmovmskb: {
14979       // High bits of movmskp{s|d}, pmovmskb are known zero.
14980       switch (IntId) {
14981         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14982         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
14983         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
14984         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
14985         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
14986         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
14987         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
14988         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
14989       }
14990       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
14991       break;
14992     }
14993     }
14994     break;
14995   }
14996   }
14997 }
14998
14999 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15000                                                          unsigned Depth) const {
15001   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15002   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15003     return Op.getValueType().getScalarType().getSizeInBits();
15004
15005   // Fallback case.
15006   return 1;
15007 }
15008
15009 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15010 /// node is a GlobalAddress + offset.
15011 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15012                                        const GlobalValue* &GA,
15013                                        int64_t &Offset) const {
15014   if (N->getOpcode() == X86ISD::Wrapper) {
15015     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15016       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15017       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15018       return true;
15019     }
15020   }
15021   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15022 }
15023
15024 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15025 /// same as extracting the high 128-bit part of 256-bit vector and then
15026 /// inserting the result into the low part of a new 256-bit vector
15027 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15028   EVT VT = SVOp->getValueType(0);
15029   unsigned NumElems = VT.getVectorNumElements();
15030
15031   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15032   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15033     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15034         SVOp->getMaskElt(j) >= 0)
15035       return false;
15036
15037   return true;
15038 }
15039
15040 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15041 /// same as extracting the low 128-bit part of 256-bit vector and then
15042 /// inserting the result into the high part of a new 256-bit vector
15043 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15044   EVT VT = SVOp->getValueType(0);
15045   unsigned NumElems = VT.getVectorNumElements();
15046
15047   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15048   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15049     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15050         SVOp->getMaskElt(j) >= 0)
15051       return false;
15052
15053   return true;
15054 }
15055
15056 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15057 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15058                                         TargetLowering::DAGCombinerInfo &DCI,
15059                                         const X86Subtarget* Subtarget) {
15060   DebugLoc dl = N->getDebugLoc();
15061   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15062   SDValue V1 = SVOp->getOperand(0);
15063   SDValue V2 = SVOp->getOperand(1);
15064   EVT VT = SVOp->getValueType(0);
15065   unsigned NumElems = VT.getVectorNumElements();
15066
15067   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15068       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15069     //
15070     //                   0,0,0,...
15071     //                      |
15072     //    V      UNDEF    BUILD_VECTOR    UNDEF
15073     //     \      /           \           /
15074     //  CONCAT_VECTOR         CONCAT_VECTOR
15075     //         \                  /
15076     //          \                /
15077     //          RESULT: V + zero extended
15078     //
15079     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15080         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15081         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15082       return SDValue();
15083
15084     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15085       return SDValue();
15086
15087     // To match the shuffle mask, the first half of the mask should
15088     // be exactly the first vector, and all the rest a splat with the
15089     // first element of the second one.
15090     for (unsigned i = 0; i != NumElems/2; ++i)
15091       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15092           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15093         return SDValue();
15094
15095     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15096     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15097       if (Ld->hasNUsesOfValue(1, 0)) {
15098         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15099         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15100         SDValue ResNode =
15101           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15102                                   array_lengthof(Ops),
15103                                   Ld->getMemoryVT(),
15104                                   Ld->getPointerInfo(),
15105                                   Ld->getAlignment(),
15106                                   false/*isVolatile*/, true/*ReadMem*/,
15107                                   false/*WriteMem*/);
15108
15109         // Make sure the newly-created LOAD is in the same position as Ld in
15110         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15111         // and update uses of Ld's output chain to use the TokenFactor.
15112         if (Ld->hasAnyUseOfValue(1)) {
15113           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15114                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15115           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15116           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15117                                  SDValue(ResNode.getNode(), 1));
15118         }
15119
15120         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15121       }
15122     }
15123
15124     // Emit a zeroed vector and insert the desired subvector on its
15125     // first half.
15126     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15127     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15128     return DCI.CombineTo(N, InsV);
15129   }
15130
15131   //===--------------------------------------------------------------------===//
15132   // Combine some shuffles into subvector extracts and inserts:
15133   //
15134
15135   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15136   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15137     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15138     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15139     return DCI.CombineTo(N, InsV);
15140   }
15141
15142   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15143   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15144     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15145     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15146     return DCI.CombineTo(N, InsV);
15147   }
15148
15149   return SDValue();
15150 }
15151
15152 /// PerformShuffleCombine - Performs several different shuffle combines.
15153 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15154                                      TargetLowering::DAGCombinerInfo &DCI,
15155                                      const X86Subtarget *Subtarget) {
15156   DebugLoc dl = N->getDebugLoc();
15157   EVT VT = N->getValueType(0);
15158
15159   // Don't create instructions with illegal types after legalize types has run.
15160   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15161   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15162     return SDValue();
15163
15164   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15165   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15166       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15167     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15168
15169   // Only handle 128 wide vector from here on.
15170   if (!VT.is128BitVector())
15171     return SDValue();
15172
15173   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15174   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15175   // consecutive, non-overlapping, and in the right order.
15176   SmallVector<SDValue, 16> Elts;
15177   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15178     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15179
15180   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15181 }
15182
15183 /// PerformTruncateCombine - Converts truncate operation to
15184 /// a sequence of vector shuffle operations.
15185 /// It is possible when we truncate 256-bit vector to 128-bit vector
15186 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15187                                       TargetLowering::DAGCombinerInfo &DCI,
15188                                       const X86Subtarget *Subtarget)  {
15189   return SDValue();
15190 }
15191
15192 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15193 /// specific shuffle of a load can be folded into a single element load.
15194 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15195 /// shuffles have been customed lowered so we need to handle those here.
15196 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15197                                          TargetLowering::DAGCombinerInfo &DCI) {
15198   if (DCI.isBeforeLegalizeOps())
15199     return SDValue();
15200
15201   SDValue InVec = N->getOperand(0);
15202   SDValue EltNo = N->getOperand(1);
15203
15204   if (!isa<ConstantSDNode>(EltNo))
15205     return SDValue();
15206
15207   EVT VT = InVec.getValueType();
15208
15209   bool HasShuffleIntoBitcast = false;
15210   if (InVec.getOpcode() == ISD::BITCAST) {
15211     // Don't duplicate a load with other uses.
15212     if (!InVec.hasOneUse())
15213       return SDValue();
15214     EVT BCVT = InVec.getOperand(0).getValueType();
15215     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15216       return SDValue();
15217     InVec = InVec.getOperand(0);
15218     HasShuffleIntoBitcast = true;
15219   }
15220
15221   if (!isTargetShuffle(InVec.getOpcode()))
15222     return SDValue();
15223
15224   // Don't duplicate a load with other uses.
15225   if (!InVec.hasOneUse())
15226     return SDValue();
15227
15228   SmallVector<int, 16> ShuffleMask;
15229   bool UnaryShuffle;
15230   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15231                             UnaryShuffle))
15232     return SDValue();
15233
15234   // Select the input vector, guarding against out of range extract vector.
15235   unsigned NumElems = VT.getVectorNumElements();
15236   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15237   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15238   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15239                                          : InVec.getOperand(1);
15240
15241   // If inputs to shuffle are the same for both ops, then allow 2 uses
15242   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15243
15244   if (LdNode.getOpcode() == ISD::BITCAST) {
15245     // Don't duplicate a load with other uses.
15246     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15247       return SDValue();
15248
15249     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15250     LdNode = LdNode.getOperand(0);
15251   }
15252
15253   if (!ISD::isNormalLoad(LdNode.getNode()))
15254     return SDValue();
15255
15256   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15257
15258   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15259     return SDValue();
15260
15261   if (HasShuffleIntoBitcast) {
15262     // If there's a bitcast before the shuffle, check if the load type and
15263     // alignment is valid.
15264     unsigned Align = LN0->getAlignment();
15265     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15266     unsigned NewAlign = TLI.getDataLayout()->
15267       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15268
15269     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15270       return SDValue();
15271   }
15272
15273   // All checks match so transform back to vector_shuffle so that DAG combiner
15274   // can finish the job
15275   DebugLoc dl = N->getDebugLoc();
15276
15277   // Create shuffle node taking into account the case that its a unary shuffle
15278   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15279   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15280                                  InVec.getOperand(0), Shuffle,
15281                                  &ShuffleMask[0]);
15282   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15283   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15284                      EltNo);
15285 }
15286
15287 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15288 /// generation and convert it from being a bunch of shuffles and extracts
15289 /// to a simple store and scalar loads to extract the elements.
15290 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15291                                          TargetLowering::DAGCombinerInfo &DCI) {
15292   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15293   if (NewOp.getNode())
15294     return NewOp;
15295
15296   SDValue InputVector = N->getOperand(0);
15297   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15298   // from mmx to v2i32 has a single usage.
15299   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15300       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15301       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15302     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15303                        N->getValueType(0),
15304                        InputVector.getNode()->getOperand(0));
15305
15306   // Only operate on vectors of 4 elements, where the alternative shuffling
15307   // gets to be more expensive.
15308   if (InputVector.getValueType() != MVT::v4i32)
15309     return SDValue();
15310
15311   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15312   // single use which is a sign-extend or zero-extend, and all elements are
15313   // used.
15314   SmallVector<SDNode *, 4> Uses;
15315   unsigned ExtractedElements = 0;
15316   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15317        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15318     if (UI.getUse().getResNo() != InputVector.getResNo())
15319       return SDValue();
15320
15321     SDNode *Extract = *UI;
15322     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15323       return SDValue();
15324
15325     if (Extract->getValueType(0) != MVT::i32)
15326       return SDValue();
15327     if (!Extract->hasOneUse())
15328       return SDValue();
15329     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15330         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15331       return SDValue();
15332     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15333       return SDValue();
15334
15335     // Record which element was extracted.
15336     ExtractedElements |=
15337       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15338
15339     Uses.push_back(Extract);
15340   }
15341
15342   // If not all the elements were used, this may not be worthwhile.
15343   if (ExtractedElements != 15)
15344     return SDValue();
15345
15346   // Ok, we've now decided to do the transformation.
15347   DebugLoc dl = InputVector.getDebugLoc();
15348
15349   // Store the value to a temporary stack slot.
15350   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15351   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15352                             MachinePointerInfo(), false, false, 0);
15353
15354   // Replace each use (extract) with a load of the appropriate element.
15355   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15356        UE = Uses.end(); UI != UE; ++UI) {
15357     SDNode *Extract = *UI;
15358
15359     // cOMpute the element's address.
15360     SDValue Idx = Extract->getOperand(1);
15361     unsigned EltSize =
15362         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15363     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15364     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15365     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15366
15367     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15368                                      StackPtr, OffsetVal);
15369
15370     // Load the scalar.
15371     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15372                                      ScalarAddr, MachinePointerInfo(),
15373                                      false, false, false, 0);
15374
15375     // Replace the exact with the load.
15376     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15377   }
15378
15379   // The replacement was made in place; don't return anything.
15380   return SDValue();
15381 }
15382
15383 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15384 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15385                                    SDValue RHS, SelectionDAG &DAG,
15386                                    const X86Subtarget *Subtarget) {
15387   if (!VT.isVector())
15388     return 0;
15389
15390   switch (VT.getSimpleVT().SimpleTy) {
15391   default: return 0;
15392   case MVT::v32i8:
15393   case MVT::v16i16:
15394   case MVT::v8i32:
15395     if (!Subtarget->hasAVX2())
15396       return 0;
15397   case MVT::v16i8:
15398   case MVT::v8i16:
15399   case MVT::v4i32:
15400     if (!Subtarget->hasSSE2())
15401       return 0;
15402   }
15403
15404   // SSE2 has only a small subset of the operations.
15405   bool hasUnsigned = Subtarget->hasSSE41() ||
15406                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15407   bool hasSigned = Subtarget->hasSSE41() ||
15408                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15409
15410   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15411
15412   // Check for x CC y ? x : y.
15413   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15414       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15415     switch (CC) {
15416     default: break;
15417     case ISD::SETULT:
15418     case ISD::SETULE:
15419       return hasUnsigned ? X86ISD::UMIN : 0;
15420     case ISD::SETUGT:
15421     case ISD::SETUGE:
15422       return hasUnsigned ? X86ISD::UMAX : 0;
15423     case ISD::SETLT:
15424     case ISD::SETLE:
15425       return hasSigned ? X86ISD::SMIN : 0;
15426     case ISD::SETGT:
15427     case ISD::SETGE:
15428       return hasSigned ? X86ISD::SMAX : 0;
15429     }
15430   // Check for x CC y ? y : x -- a min/max with reversed arms.
15431   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15432              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15433     switch (CC) {
15434     default: break;
15435     case ISD::SETULT:
15436     case ISD::SETULE:
15437       return hasUnsigned ? X86ISD::UMAX : 0;
15438     case ISD::SETUGT:
15439     case ISD::SETUGE:
15440       return hasUnsigned ? X86ISD::UMIN : 0;
15441     case ISD::SETLT:
15442     case ISD::SETLE:
15443       return hasSigned ? X86ISD::SMAX : 0;
15444     case ISD::SETGT:
15445     case ISD::SETGE:
15446       return hasSigned ? X86ISD::SMIN : 0;
15447     }
15448   }
15449
15450   return 0;
15451 }
15452
15453 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15454 /// nodes.
15455 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15456                                     TargetLowering::DAGCombinerInfo &DCI,
15457                                     const X86Subtarget *Subtarget) {
15458   DebugLoc DL = N->getDebugLoc();
15459   SDValue Cond = N->getOperand(0);
15460   // Get the LHS/RHS of the select.
15461   SDValue LHS = N->getOperand(1);
15462   SDValue RHS = N->getOperand(2);
15463   EVT VT = LHS.getValueType();
15464
15465   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15466   // instructions match the semantics of the common C idiom x<y?x:y but not
15467   // x<=y?x:y, because of how they handle negative zero (which can be
15468   // ignored in unsafe-math mode).
15469   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15470       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15471       (Subtarget->hasSSE2() ||
15472        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15473     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15474
15475     unsigned Opcode = 0;
15476     // Check for x CC y ? x : y.
15477     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15478         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15479       switch (CC) {
15480       default: break;
15481       case ISD::SETULT:
15482         // Converting this to a min would handle NaNs incorrectly, and swapping
15483         // the operands would cause it to handle comparisons between positive
15484         // and negative zero incorrectly.
15485         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15486           if (!DAG.getTarget().Options.UnsafeFPMath &&
15487               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15488             break;
15489           std::swap(LHS, RHS);
15490         }
15491         Opcode = X86ISD::FMIN;
15492         break;
15493       case ISD::SETOLE:
15494         // Converting this to a min would handle comparisons between positive
15495         // and negative zero incorrectly.
15496         if (!DAG.getTarget().Options.UnsafeFPMath &&
15497             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15498           break;
15499         Opcode = X86ISD::FMIN;
15500         break;
15501       case ISD::SETULE:
15502         // Converting this to a min would handle both negative zeros and NaNs
15503         // incorrectly, but we can swap the operands to fix both.
15504         std::swap(LHS, RHS);
15505       case ISD::SETOLT:
15506       case ISD::SETLT:
15507       case ISD::SETLE:
15508         Opcode = X86ISD::FMIN;
15509         break;
15510
15511       case ISD::SETOGE:
15512         // Converting this to a max would handle comparisons between positive
15513         // and negative zero incorrectly.
15514         if (!DAG.getTarget().Options.UnsafeFPMath &&
15515             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15516           break;
15517         Opcode = X86ISD::FMAX;
15518         break;
15519       case ISD::SETUGT:
15520         // Converting this to a max would handle NaNs incorrectly, and swapping
15521         // the operands would cause it to handle comparisons between positive
15522         // and negative zero incorrectly.
15523         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15524           if (!DAG.getTarget().Options.UnsafeFPMath &&
15525               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15526             break;
15527           std::swap(LHS, RHS);
15528         }
15529         Opcode = X86ISD::FMAX;
15530         break;
15531       case ISD::SETUGE:
15532         // Converting this to a max would handle both negative zeros and NaNs
15533         // incorrectly, but we can swap the operands to fix both.
15534         std::swap(LHS, RHS);
15535       case ISD::SETOGT:
15536       case ISD::SETGT:
15537       case ISD::SETGE:
15538         Opcode = X86ISD::FMAX;
15539         break;
15540       }
15541     // Check for x CC y ? y : x -- a min/max with reversed arms.
15542     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15543                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15544       switch (CC) {
15545       default: break;
15546       case ISD::SETOGE:
15547         // Converting this to a min would handle comparisons between positive
15548         // and negative zero incorrectly, and swapping the operands would
15549         // cause it to handle NaNs incorrectly.
15550         if (!DAG.getTarget().Options.UnsafeFPMath &&
15551             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15552           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15553             break;
15554           std::swap(LHS, RHS);
15555         }
15556         Opcode = X86ISD::FMIN;
15557         break;
15558       case ISD::SETUGT:
15559         // Converting this to a min would handle NaNs incorrectly.
15560         if (!DAG.getTarget().Options.UnsafeFPMath &&
15561             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15562           break;
15563         Opcode = X86ISD::FMIN;
15564         break;
15565       case ISD::SETUGE:
15566         // Converting this to a min would handle both negative zeros and NaNs
15567         // incorrectly, but we can swap the operands to fix both.
15568         std::swap(LHS, RHS);
15569       case ISD::SETOGT:
15570       case ISD::SETGT:
15571       case ISD::SETGE:
15572         Opcode = X86ISD::FMIN;
15573         break;
15574
15575       case ISD::SETULT:
15576         // Converting this to a max would handle NaNs incorrectly.
15577         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15578           break;
15579         Opcode = X86ISD::FMAX;
15580         break;
15581       case ISD::SETOLE:
15582         // Converting this to a max would handle comparisons between positive
15583         // and negative zero incorrectly, and swapping the operands would
15584         // cause it to handle NaNs incorrectly.
15585         if (!DAG.getTarget().Options.UnsafeFPMath &&
15586             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15587           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15588             break;
15589           std::swap(LHS, RHS);
15590         }
15591         Opcode = X86ISD::FMAX;
15592         break;
15593       case ISD::SETULE:
15594         // Converting this to a max would handle both negative zeros and NaNs
15595         // incorrectly, but we can swap the operands to fix both.
15596         std::swap(LHS, RHS);
15597       case ISD::SETOLT:
15598       case ISD::SETLT:
15599       case ISD::SETLE:
15600         Opcode = X86ISD::FMAX;
15601         break;
15602       }
15603     }
15604
15605     if (Opcode)
15606       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15607   }
15608
15609   // If this is a select between two integer constants, try to do some
15610   // optimizations.
15611   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15612     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15613       // Don't do this for crazy integer types.
15614       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15615         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15616         // so that TrueC (the true value) is larger than FalseC.
15617         bool NeedsCondInvert = false;
15618
15619         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15620             // Efficiently invertible.
15621             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15622              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15623               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15624           NeedsCondInvert = true;
15625           std::swap(TrueC, FalseC);
15626         }
15627
15628         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15629         if (FalseC->getAPIntValue() == 0 &&
15630             TrueC->getAPIntValue().isPowerOf2()) {
15631           if (NeedsCondInvert) // Invert the condition if needed.
15632             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15633                                DAG.getConstant(1, Cond.getValueType()));
15634
15635           // Zero extend the condition if needed.
15636           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15637
15638           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15639           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15640                              DAG.getConstant(ShAmt, MVT::i8));
15641         }
15642
15643         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15644         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15645           if (NeedsCondInvert) // Invert the condition if needed.
15646             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15647                                DAG.getConstant(1, Cond.getValueType()));
15648
15649           // Zero extend the condition if needed.
15650           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15651                              FalseC->getValueType(0), Cond);
15652           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15653                              SDValue(FalseC, 0));
15654         }
15655
15656         // Optimize cases that will turn into an LEA instruction.  This requires
15657         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15658         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15659           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15660           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15661
15662           bool isFastMultiplier = false;
15663           if (Diff < 10) {
15664             switch ((unsigned char)Diff) {
15665               default: break;
15666               case 1:  // result = add base, cond
15667               case 2:  // result = lea base(    , cond*2)
15668               case 3:  // result = lea base(cond, cond*2)
15669               case 4:  // result = lea base(    , cond*4)
15670               case 5:  // result = lea base(cond, cond*4)
15671               case 8:  // result = lea base(    , cond*8)
15672               case 9:  // result = lea base(cond, cond*8)
15673                 isFastMultiplier = true;
15674                 break;
15675             }
15676           }
15677
15678           if (isFastMultiplier) {
15679             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15680             if (NeedsCondInvert) // Invert the condition if needed.
15681               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15682                                  DAG.getConstant(1, Cond.getValueType()));
15683
15684             // Zero extend the condition if needed.
15685             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15686                                Cond);
15687             // Scale the condition by the difference.
15688             if (Diff != 1)
15689               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15690                                  DAG.getConstant(Diff, Cond.getValueType()));
15691
15692             // Add the base if non-zero.
15693             if (FalseC->getAPIntValue() != 0)
15694               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15695                                  SDValue(FalseC, 0));
15696             return Cond;
15697           }
15698         }
15699       }
15700   }
15701
15702   // Canonicalize max and min:
15703   // (x > y) ? x : y -> (x >= y) ? x : y
15704   // (x < y) ? x : y -> (x <= y) ? x : y
15705   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15706   // the need for an extra compare
15707   // against zero. e.g.
15708   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15709   // subl   %esi, %edi
15710   // testl  %edi, %edi
15711   // movl   $0, %eax
15712   // cmovgl %edi, %eax
15713   // =>
15714   // xorl   %eax, %eax
15715   // subl   %esi, $edi
15716   // cmovsl %eax, %edi
15717   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15718       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15719       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15720     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15721     switch (CC) {
15722     default: break;
15723     case ISD::SETLT:
15724     case ISD::SETGT: {
15725       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15726       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15727                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15728       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15729     }
15730     }
15731   }
15732
15733   // Match VSELECTs into subs with unsigned saturation.
15734   if (!DCI.isBeforeLegalize() &&
15735       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15736       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15737       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15738        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15739     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15740
15741     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15742     // left side invert the predicate to simplify logic below.
15743     SDValue Other;
15744     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15745       Other = RHS;
15746       CC = ISD::getSetCCInverse(CC, true);
15747     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15748       Other = LHS;
15749     }
15750
15751     if (Other.getNode() && Other->getNumOperands() == 2 &&
15752         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15753       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15754       SDValue CondRHS = Cond->getOperand(1);
15755
15756       // Look for a general sub with unsigned saturation first.
15757       // x >= y ? x-y : 0 --> subus x, y
15758       // x >  y ? x-y : 0 --> subus x, y
15759       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15760           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15761         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15762
15763       // If the RHS is a constant we have to reverse the const canonicalization.
15764       // x > C-1 ? x+-C : 0 --> subus x, C
15765       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15766           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15767         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15768         if (CondRHS.getConstantOperandVal(0) == -A-1)
15769           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15770                              DAG.getConstant(-A, VT));
15771       }
15772
15773       // Another special case: If C was a sign bit, the sub has been
15774       // canonicalized into a xor.
15775       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15776       //        it's safe to decanonicalize the xor?
15777       // x s< 0 ? x^C : 0 --> subus x, C
15778       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15779           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15780           isSplatVector(OpRHS.getNode())) {
15781         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15782         if (A.isSignBit())
15783           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15784       }
15785     }
15786   }
15787
15788   // Try to match a min/max vector operation.
15789   if (!DCI.isBeforeLegalize() &&
15790       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15791     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15792       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15793
15794   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15795   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15796       Cond.getOpcode() == ISD::SETCC) {
15797
15798     assert(Cond.getValueType().isVector() &&
15799            "vector select expects a vector selector!");
15800
15801     EVT IntVT = Cond.getValueType();
15802     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15803     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15804
15805     if (!TValIsAllOnes && !FValIsAllZeros) {
15806       // Try invert the condition if true value is not all 1s and false value
15807       // is not all 0s.
15808       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15809       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15810
15811       if (TValIsAllZeros || FValIsAllOnes) {
15812         SDValue CC = Cond.getOperand(2);
15813         ISD::CondCode NewCC =
15814           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15815                                Cond.getOperand(0).getValueType().isInteger());
15816         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15817         std::swap(LHS, RHS);
15818         TValIsAllOnes = FValIsAllOnes;
15819         FValIsAllZeros = TValIsAllZeros;
15820       }
15821     }
15822
15823     if (TValIsAllOnes || FValIsAllZeros) {
15824       SDValue Ret;
15825
15826       if (TValIsAllOnes && FValIsAllZeros)
15827         Ret = Cond;
15828       else if (TValIsAllOnes)
15829         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15830                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15831       else if (FValIsAllZeros)
15832         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15833                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15834
15835       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15836     }
15837   }
15838
15839   // If we know that this node is legal then we know that it is going to be
15840   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15841   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15842   // to simplify previous instructions.
15843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15844   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15845       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15846     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15847
15848     // Don't optimize vector selects that map to mask-registers.
15849     if (BitWidth == 1)
15850       return SDValue();
15851
15852     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15853     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15854
15855     APInt KnownZero, KnownOne;
15856     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15857                                           DCI.isBeforeLegalizeOps());
15858     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15859         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15860       DCI.CommitTargetLoweringOpt(TLO);
15861   }
15862
15863   return SDValue();
15864 }
15865
15866 // Check whether a boolean test is testing a boolean value generated by
15867 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15868 // code.
15869 //
15870 // Simplify the following patterns:
15871 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15872 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15873 // to (Op EFLAGS Cond)
15874 //
15875 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15876 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15877 // to (Op EFLAGS !Cond)
15878 //
15879 // where Op could be BRCOND or CMOV.
15880 //
15881 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15882   // Quit if not CMP and SUB with its value result used.
15883   if (Cmp.getOpcode() != X86ISD::CMP &&
15884       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15885       return SDValue();
15886
15887   // Quit if not used as a boolean value.
15888   if (CC != X86::COND_E && CC != X86::COND_NE)
15889     return SDValue();
15890
15891   // Check CMP operands. One of them should be 0 or 1 and the other should be
15892   // an SetCC or extended from it.
15893   SDValue Op1 = Cmp.getOperand(0);
15894   SDValue Op2 = Cmp.getOperand(1);
15895
15896   SDValue SetCC;
15897   const ConstantSDNode* C = 0;
15898   bool needOppositeCond = (CC == X86::COND_E);
15899   bool checkAgainstTrue = false; // Is it a comparison against 1?
15900
15901   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15902     SetCC = Op2;
15903   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15904     SetCC = Op1;
15905   else // Quit if all operands are not constants.
15906     return SDValue();
15907
15908   if (C->getZExtValue() == 1) {
15909     needOppositeCond = !needOppositeCond;
15910     checkAgainstTrue = true;
15911   } else if (C->getZExtValue() != 0)
15912     // Quit if the constant is neither 0 or 1.
15913     return SDValue();
15914
15915   bool truncatedToBoolWithAnd = false;
15916   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15917   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15918          SetCC.getOpcode() == ISD::TRUNCATE ||
15919          SetCC.getOpcode() == ISD::AND) {
15920     if (SetCC.getOpcode() == ISD::AND) {
15921       int OpIdx = -1;
15922       ConstantSDNode *CS;
15923       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15924           CS->getZExtValue() == 1)
15925         OpIdx = 1;
15926       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15927           CS->getZExtValue() == 1)
15928         OpIdx = 0;
15929       if (OpIdx == -1)
15930         break;
15931       SetCC = SetCC.getOperand(OpIdx);
15932       truncatedToBoolWithAnd = true;
15933     } else
15934       SetCC = SetCC.getOperand(0);
15935   }
15936
15937   switch (SetCC.getOpcode()) {
15938   case X86ISD::SETCC_CARRY:
15939     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15940     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15941     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15942     // truncated to i1 using 'and'.
15943     if (checkAgainstTrue && !truncatedToBoolWithAnd)
15944       break;
15945     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15946            "Invalid use of SETCC_CARRY!");
15947     // FALL THROUGH
15948   case X86ISD::SETCC:
15949     // Set the condition code or opposite one if necessary.
15950     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15951     if (needOppositeCond)
15952       CC = X86::GetOppositeBranchCondition(CC);
15953     return SetCC.getOperand(1);
15954   case X86ISD::CMOV: {
15955     // Check whether false/true value has canonical one, i.e. 0 or 1.
15956     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15957     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15958     // Quit if true value is not a constant.
15959     if (!TVal)
15960       return SDValue();
15961     // Quit if false value is not a constant.
15962     if (!FVal) {
15963       SDValue Op = SetCC.getOperand(0);
15964       // Skip 'zext' or 'trunc' node.
15965       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15966           Op.getOpcode() == ISD::TRUNCATE)
15967         Op = Op.getOperand(0);
15968       // A special case for rdrand/rdseed, where 0 is set if false cond is
15969       // found.
15970       if ((Op.getOpcode() != X86ISD::RDRAND &&
15971            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15972         return SDValue();
15973     }
15974     // Quit if false value is not the constant 0 or 1.
15975     bool FValIsFalse = true;
15976     if (FVal && FVal->getZExtValue() != 0) {
15977       if (FVal->getZExtValue() != 1)
15978         return SDValue();
15979       // If FVal is 1, opposite cond is needed.
15980       needOppositeCond = !needOppositeCond;
15981       FValIsFalse = false;
15982     }
15983     // Quit if TVal is not the constant opposite of FVal.
15984     if (FValIsFalse && TVal->getZExtValue() != 1)
15985       return SDValue();
15986     if (!FValIsFalse && TVal->getZExtValue() != 0)
15987       return SDValue();
15988     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
15989     if (needOppositeCond)
15990       CC = X86::GetOppositeBranchCondition(CC);
15991     return SetCC.getOperand(3);
15992   }
15993   }
15994
15995   return SDValue();
15996 }
15997
15998 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
15999 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16000                                   TargetLowering::DAGCombinerInfo &DCI,
16001                                   const X86Subtarget *Subtarget) {
16002   DebugLoc DL = N->getDebugLoc();
16003
16004   // If the flag operand isn't dead, don't touch this CMOV.
16005   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16006     return SDValue();
16007
16008   SDValue FalseOp = N->getOperand(0);
16009   SDValue TrueOp = N->getOperand(1);
16010   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16011   SDValue Cond = N->getOperand(3);
16012
16013   if (CC == X86::COND_E || CC == X86::COND_NE) {
16014     switch (Cond.getOpcode()) {
16015     default: break;
16016     case X86ISD::BSR:
16017     case X86ISD::BSF:
16018       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16019       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16020         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16021     }
16022   }
16023
16024   SDValue Flags;
16025
16026   Flags = checkBoolTestSetCCCombine(Cond, CC);
16027   if (Flags.getNode() &&
16028       // Extra check as FCMOV only supports a subset of X86 cond.
16029       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16030     SDValue Ops[] = { FalseOp, TrueOp,
16031                       DAG.getConstant(CC, MVT::i8), Flags };
16032     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16033                        Ops, array_lengthof(Ops));
16034   }
16035
16036   // If this is a select between two integer constants, try to do some
16037   // optimizations.  Note that the operands are ordered the opposite of SELECT
16038   // operands.
16039   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16040     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16041       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16042       // larger than FalseC (the false value).
16043       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16044         CC = X86::GetOppositeBranchCondition(CC);
16045         std::swap(TrueC, FalseC);
16046         std::swap(TrueOp, FalseOp);
16047       }
16048
16049       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16050       // This is efficient for any integer data type (including i8/i16) and
16051       // shift amount.
16052       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16053         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16054                            DAG.getConstant(CC, MVT::i8), Cond);
16055
16056         // Zero extend the condition if needed.
16057         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16058
16059         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16060         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16061                            DAG.getConstant(ShAmt, MVT::i8));
16062         if (N->getNumValues() == 2)  // Dead flag value?
16063           return DCI.CombineTo(N, Cond, SDValue());
16064         return Cond;
16065       }
16066
16067       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16068       // for any integer data type, including i8/i16.
16069       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16070         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16071                            DAG.getConstant(CC, MVT::i8), Cond);
16072
16073         // Zero extend the condition if needed.
16074         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16075                            FalseC->getValueType(0), Cond);
16076         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16077                            SDValue(FalseC, 0));
16078
16079         if (N->getNumValues() == 2)  // Dead flag value?
16080           return DCI.CombineTo(N, Cond, SDValue());
16081         return Cond;
16082       }
16083
16084       // Optimize cases that will turn into an LEA instruction.  This requires
16085       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16086       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16087         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16088         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16089
16090         bool isFastMultiplier = false;
16091         if (Diff < 10) {
16092           switch ((unsigned char)Diff) {
16093           default: break;
16094           case 1:  // result = add base, cond
16095           case 2:  // result = lea base(    , cond*2)
16096           case 3:  // result = lea base(cond, cond*2)
16097           case 4:  // result = lea base(    , cond*4)
16098           case 5:  // result = lea base(cond, cond*4)
16099           case 8:  // result = lea base(    , cond*8)
16100           case 9:  // result = lea base(cond, cond*8)
16101             isFastMultiplier = true;
16102             break;
16103           }
16104         }
16105
16106         if (isFastMultiplier) {
16107           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16108           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16109                              DAG.getConstant(CC, MVT::i8), Cond);
16110           // Zero extend the condition if needed.
16111           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16112                              Cond);
16113           // Scale the condition by the difference.
16114           if (Diff != 1)
16115             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16116                                DAG.getConstant(Diff, Cond.getValueType()));
16117
16118           // Add the base if non-zero.
16119           if (FalseC->getAPIntValue() != 0)
16120             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16121                                SDValue(FalseC, 0));
16122           if (N->getNumValues() == 2)  // Dead flag value?
16123             return DCI.CombineTo(N, Cond, SDValue());
16124           return Cond;
16125         }
16126       }
16127     }
16128   }
16129
16130   // Handle these cases:
16131   //   (select (x != c), e, c) -> select (x != c), e, x),
16132   //   (select (x == c), c, e) -> select (x == c), x, e)
16133   // where the c is an integer constant, and the "select" is the combination
16134   // of CMOV and CMP.
16135   //
16136   // The rationale for this change is that the conditional-move from a constant
16137   // needs two instructions, however, conditional-move from a register needs
16138   // only one instruction.
16139   //
16140   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16141   //  some instruction-combining opportunities. This opt needs to be
16142   //  postponed as late as possible.
16143   //
16144   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16145     // the DCI.xxxx conditions are provided to postpone the optimization as
16146     // late as possible.
16147
16148     ConstantSDNode *CmpAgainst = 0;
16149     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16150         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16151         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16152
16153       if (CC == X86::COND_NE &&
16154           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16155         CC = X86::GetOppositeBranchCondition(CC);
16156         std::swap(TrueOp, FalseOp);
16157       }
16158
16159       if (CC == X86::COND_E &&
16160           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16161         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16162                           DAG.getConstant(CC, MVT::i8), Cond };
16163         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16164                            array_lengthof(Ops));
16165       }
16166     }
16167   }
16168
16169   return SDValue();
16170 }
16171
16172 /// PerformMulCombine - Optimize a single multiply with constant into two
16173 /// in order to implement it with two cheaper instructions, e.g.
16174 /// LEA + SHL, LEA + LEA.
16175 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16176                                  TargetLowering::DAGCombinerInfo &DCI) {
16177   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16178     return SDValue();
16179
16180   EVT VT = N->getValueType(0);
16181   if (VT != MVT::i64)
16182     return SDValue();
16183
16184   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16185   if (!C)
16186     return SDValue();
16187   uint64_t MulAmt = C->getZExtValue();
16188   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16189     return SDValue();
16190
16191   uint64_t MulAmt1 = 0;
16192   uint64_t MulAmt2 = 0;
16193   if ((MulAmt % 9) == 0) {
16194     MulAmt1 = 9;
16195     MulAmt2 = MulAmt / 9;
16196   } else if ((MulAmt % 5) == 0) {
16197     MulAmt1 = 5;
16198     MulAmt2 = MulAmt / 5;
16199   } else if ((MulAmt % 3) == 0) {
16200     MulAmt1 = 3;
16201     MulAmt2 = MulAmt / 3;
16202   }
16203   if (MulAmt2 &&
16204       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16205     DebugLoc DL = N->getDebugLoc();
16206
16207     if (isPowerOf2_64(MulAmt2) &&
16208         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16209       // If second multiplifer is pow2, issue it first. We want the multiply by
16210       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16211       // is an add.
16212       std::swap(MulAmt1, MulAmt2);
16213
16214     SDValue NewMul;
16215     if (isPowerOf2_64(MulAmt1))
16216       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16217                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16218     else
16219       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16220                            DAG.getConstant(MulAmt1, VT));
16221
16222     if (isPowerOf2_64(MulAmt2))
16223       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16224                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16225     else
16226       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16227                            DAG.getConstant(MulAmt2, VT));
16228
16229     // Do not add new nodes to DAG combiner worklist.
16230     DCI.CombineTo(N, NewMul, false);
16231   }
16232   return SDValue();
16233 }
16234
16235 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16236   SDValue N0 = N->getOperand(0);
16237   SDValue N1 = N->getOperand(1);
16238   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16239   EVT VT = N0.getValueType();
16240
16241   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16242   // since the result of setcc_c is all zero's or all ones.
16243   if (VT.isInteger() && !VT.isVector() &&
16244       N1C && N0.getOpcode() == ISD::AND &&
16245       N0.getOperand(1).getOpcode() == ISD::Constant) {
16246     SDValue N00 = N0.getOperand(0);
16247     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16248         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16249           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16250          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16251       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16252       APInt ShAmt = N1C->getAPIntValue();
16253       Mask = Mask.shl(ShAmt);
16254       if (Mask != 0)
16255         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16256                            N00, DAG.getConstant(Mask, VT));
16257     }
16258   }
16259
16260   // Hardware support for vector shifts is sparse which makes us scalarize the
16261   // vector operations in many cases. Also, on sandybridge ADD is faster than
16262   // shl.
16263   // (shl V, 1) -> add V,V
16264   if (isSplatVector(N1.getNode())) {
16265     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16266     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16267     // We shift all of the values by one. In many cases we do not have
16268     // hardware support for this operation. This is better expressed as an ADD
16269     // of two values.
16270     if (N1C && (1 == N1C->getZExtValue())) {
16271       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16272     }
16273   }
16274
16275   return SDValue();
16276 }
16277
16278 /// PerformShiftCombine - Combine shifts.
16279 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16280                                    TargetLowering::DAGCombinerInfo &DCI,
16281                                    const X86Subtarget *Subtarget) {
16282   if (N->getOpcode() == ISD::SHL) {
16283     SDValue V = PerformSHLCombine(N, DAG);
16284     if (V.getNode()) return V;
16285   }
16286
16287   return SDValue();
16288 }
16289
16290 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16291 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16292 // and friends.  Likewise for OR -> CMPNEQSS.
16293 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16294                             TargetLowering::DAGCombinerInfo &DCI,
16295                             const X86Subtarget *Subtarget) {
16296   unsigned opcode;
16297
16298   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16299   // we're requiring SSE2 for both.
16300   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16301     SDValue N0 = N->getOperand(0);
16302     SDValue N1 = N->getOperand(1);
16303     SDValue CMP0 = N0->getOperand(1);
16304     SDValue CMP1 = N1->getOperand(1);
16305     DebugLoc DL = N->getDebugLoc();
16306
16307     // The SETCCs should both refer to the same CMP.
16308     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16309       return SDValue();
16310
16311     SDValue CMP00 = CMP0->getOperand(0);
16312     SDValue CMP01 = CMP0->getOperand(1);
16313     EVT     VT    = CMP00.getValueType();
16314
16315     if (VT == MVT::f32 || VT == MVT::f64) {
16316       bool ExpectingFlags = false;
16317       // Check for any users that want flags:
16318       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16319            !ExpectingFlags && UI != UE; ++UI)
16320         switch (UI->getOpcode()) {
16321         default:
16322         case ISD::BR_CC:
16323         case ISD::BRCOND:
16324         case ISD::SELECT:
16325           ExpectingFlags = true;
16326           break;
16327         case ISD::CopyToReg:
16328         case ISD::SIGN_EXTEND:
16329         case ISD::ZERO_EXTEND:
16330         case ISD::ANY_EXTEND:
16331           break;
16332         }
16333
16334       if (!ExpectingFlags) {
16335         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16336         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16337
16338         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16339           X86::CondCode tmp = cc0;
16340           cc0 = cc1;
16341           cc1 = tmp;
16342         }
16343
16344         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16345             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16346           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16347           X86ISD::NodeType NTOperator = is64BitFP ?
16348             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16349           // FIXME: need symbolic constants for these magic numbers.
16350           // See X86ATTInstPrinter.cpp:printSSECC().
16351           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16352           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16353                                               DAG.getConstant(x86cc, MVT::i8));
16354           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16355                                               OnesOrZeroesF);
16356           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16357                                       DAG.getConstant(1, MVT::i32));
16358           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16359           return OneBitOfTruth;
16360         }
16361       }
16362     }
16363   }
16364   return SDValue();
16365 }
16366
16367 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16368 /// so it can be folded inside ANDNP.
16369 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16370   EVT VT = N->getValueType(0);
16371
16372   // Match direct AllOnes for 128 and 256-bit vectors
16373   if (ISD::isBuildVectorAllOnes(N))
16374     return true;
16375
16376   // Look through a bit convert.
16377   if (N->getOpcode() == ISD::BITCAST)
16378     N = N->getOperand(0).getNode();
16379
16380   // Sometimes the operand may come from a insert_subvector building a 256-bit
16381   // allones vector
16382   if (VT.is256BitVector() &&
16383       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16384     SDValue V1 = N->getOperand(0);
16385     SDValue V2 = N->getOperand(1);
16386
16387     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16388         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16389         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16390         ISD::isBuildVectorAllOnes(V2.getNode()))
16391       return true;
16392   }
16393
16394   return false;
16395 }
16396
16397 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16398 // register. In most cases we actually compare or select YMM-sized registers
16399 // and mixing the two types creates horrible code. This method optimizes
16400 // some of the transition sequences.
16401 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16402                                  TargetLowering::DAGCombinerInfo &DCI,
16403                                  const X86Subtarget *Subtarget) {
16404   EVT VT = N->getValueType(0);
16405   if (!VT.is256BitVector())
16406     return SDValue();
16407
16408   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16409           N->getOpcode() == ISD::ZERO_EXTEND ||
16410           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16411
16412   SDValue Narrow = N->getOperand(0);
16413   EVT NarrowVT = Narrow->getValueType(0);
16414   if (!NarrowVT.is128BitVector())
16415     return SDValue();
16416
16417   if (Narrow->getOpcode() != ISD::XOR &&
16418       Narrow->getOpcode() != ISD::AND &&
16419       Narrow->getOpcode() != ISD::OR)
16420     return SDValue();
16421
16422   SDValue N0  = Narrow->getOperand(0);
16423   SDValue N1  = Narrow->getOperand(1);
16424   DebugLoc DL = Narrow->getDebugLoc();
16425
16426   // The Left side has to be a trunc.
16427   if (N0.getOpcode() != ISD::TRUNCATE)
16428     return SDValue();
16429
16430   // The type of the truncated inputs.
16431   EVT WideVT = N0->getOperand(0)->getValueType(0);
16432   if (WideVT != VT)
16433     return SDValue();
16434
16435   // The right side has to be a 'trunc' or a constant vector.
16436   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16437   bool RHSConst = (isSplatVector(N1.getNode()) &&
16438                    isa<ConstantSDNode>(N1->getOperand(0)));
16439   if (!RHSTrunc && !RHSConst)
16440     return SDValue();
16441
16442   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16443
16444   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16445     return SDValue();
16446
16447   // Set N0 and N1 to hold the inputs to the new wide operation.
16448   N0 = N0->getOperand(0);
16449   if (RHSConst) {
16450     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16451                      N1->getOperand(0));
16452     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16453     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16454   } else if (RHSTrunc) {
16455     N1 = N1->getOperand(0);
16456   }
16457
16458   // Generate the wide operation.
16459   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16460   unsigned Opcode = N->getOpcode();
16461   switch (Opcode) {
16462   case ISD::ANY_EXTEND:
16463     return Op;
16464   case ISD::ZERO_EXTEND: {
16465     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16466     APInt Mask = APInt::getAllOnesValue(InBits);
16467     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16468     return DAG.getNode(ISD::AND, DL, VT,
16469                        Op, DAG.getConstant(Mask, VT));
16470   }
16471   case ISD::SIGN_EXTEND:
16472     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16473                        Op, DAG.getValueType(NarrowVT));
16474   default:
16475     llvm_unreachable("Unexpected opcode");
16476   }
16477 }
16478
16479 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16480                                  TargetLowering::DAGCombinerInfo &DCI,
16481                                  const X86Subtarget *Subtarget) {
16482   EVT VT = N->getValueType(0);
16483   if (DCI.isBeforeLegalizeOps())
16484     return SDValue();
16485
16486   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16487   if (R.getNode())
16488     return R;
16489
16490   // Create BLSI, and BLSR instructions
16491   // BLSI is X & (-X)
16492   // BLSR is X & (X-1)
16493   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16494     SDValue N0 = N->getOperand(0);
16495     SDValue N1 = N->getOperand(1);
16496     DebugLoc DL = N->getDebugLoc();
16497
16498     // Check LHS for neg
16499     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16500         isZero(N0.getOperand(0)))
16501       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16502
16503     // Check RHS for neg
16504     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16505         isZero(N1.getOperand(0)))
16506       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16507
16508     // Check LHS for X-1
16509     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16510         isAllOnes(N0.getOperand(1)))
16511       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16512
16513     // Check RHS for X-1
16514     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16515         isAllOnes(N1.getOperand(1)))
16516       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16517
16518     return SDValue();
16519   }
16520
16521   // Want to form ANDNP nodes:
16522   // 1) In the hopes of then easily combining them with OR and AND nodes
16523   //    to form PBLEND/PSIGN.
16524   // 2) To match ANDN packed intrinsics
16525   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16526     return SDValue();
16527
16528   SDValue N0 = N->getOperand(0);
16529   SDValue N1 = N->getOperand(1);
16530   DebugLoc DL = N->getDebugLoc();
16531
16532   // Check LHS for vnot
16533   if (N0.getOpcode() == ISD::XOR &&
16534       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16535       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16536     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16537
16538   // Check RHS for vnot
16539   if (N1.getOpcode() == ISD::XOR &&
16540       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16541       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16542     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16543
16544   return SDValue();
16545 }
16546
16547 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16548                                 TargetLowering::DAGCombinerInfo &DCI,
16549                                 const X86Subtarget *Subtarget) {
16550   EVT VT = N->getValueType(0);
16551   if (DCI.isBeforeLegalizeOps())
16552     return SDValue();
16553
16554   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16555   if (R.getNode())
16556     return R;
16557
16558   SDValue N0 = N->getOperand(0);
16559   SDValue N1 = N->getOperand(1);
16560
16561   // look for psign/blend
16562   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16563     if (!Subtarget->hasSSSE3() ||
16564         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16565       return SDValue();
16566
16567     // Canonicalize pandn to RHS
16568     if (N0.getOpcode() == X86ISD::ANDNP)
16569       std::swap(N0, N1);
16570     // or (and (m, y), (pandn m, x))
16571     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16572       SDValue Mask = N1.getOperand(0);
16573       SDValue X    = N1.getOperand(1);
16574       SDValue Y;
16575       if (N0.getOperand(0) == Mask)
16576         Y = N0.getOperand(1);
16577       if (N0.getOperand(1) == Mask)
16578         Y = N0.getOperand(0);
16579
16580       // Check to see if the mask appeared in both the AND and ANDNP and
16581       if (!Y.getNode())
16582         return SDValue();
16583
16584       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16585       // Look through mask bitcast.
16586       if (Mask.getOpcode() == ISD::BITCAST)
16587         Mask = Mask.getOperand(0);
16588       if (X.getOpcode() == ISD::BITCAST)
16589         X = X.getOperand(0);
16590       if (Y.getOpcode() == ISD::BITCAST)
16591         Y = Y.getOperand(0);
16592
16593       EVT MaskVT = Mask.getValueType();
16594
16595       // Validate that the Mask operand is a vector sra node.
16596       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16597       // there is no psrai.b
16598       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16599       unsigned SraAmt = ~0;
16600       if (Mask.getOpcode() == ISD::SRA) {
16601         SDValue Amt = Mask.getOperand(1);
16602         if (isSplatVector(Amt.getNode())) {
16603           SDValue SclrAmt = Amt->getOperand(0);
16604           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16605             SraAmt = C->getZExtValue();
16606         }
16607       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16608         SDValue SraC = Mask.getOperand(1);
16609         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16610       }
16611       if ((SraAmt + 1) != EltBits)
16612         return SDValue();
16613
16614       DebugLoc DL = N->getDebugLoc();
16615
16616       // Now we know we at least have a plendvb with the mask val.  See if
16617       // we can form a psignb/w/d.
16618       // psign = x.type == y.type == mask.type && y = sub(0, x);
16619       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16620           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16621           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16622         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16623                "Unsupported VT for PSIGN");
16624         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16625         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16626       }
16627       // PBLENDVB only available on SSE 4.1
16628       if (!Subtarget->hasSSE41())
16629         return SDValue();
16630
16631       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16632
16633       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16634       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16635       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16636       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16637       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16638     }
16639   }
16640
16641   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16642     return SDValue();
16643
16644   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16645   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16646     std::swap(N0, N1);
16647   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16648     return SDValue();
16649   if (!N0.hasOneUse() || !N1.hasOneUse())
16650     return SDValue();
16651
16652   SDValue ShAmt0 = N0.getOperand(1);
16653   if (ShAmt0.getValueType() != MVT::i8)
16654     return SDValue();
16655   SDValue ShAmt1 = N1.getOperand(1);
16656   if (ShAmt1.getValueType() != MVT::i8)
16657     return SDValue();
16658   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16659     ShAmt0 = ShAmt0.getOperand(0);
16660   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16661     ShAmt1 = ShAmt1.getOperand(0);
16662
16663   DebugLoc DL = N->getDebugLoc();
16664   unsigned Opc = X86ISD::SHLD;
16665   SDValue Op0 = N0.getOperand(0);
16666   SDValue Op1 = N1.getOperand(0);
16667   if (ShAmt0.getOpcode() == ISD::SUB) {
16668     Opc = X86ISD::SHRD;
16669     std::swap(Op0, Op1);
16670     std::swap(ShAmt0, ShAmt1);
16671   }
16672
16673   unsigned Bits = VT.getSizeInBits();
16674   if (ShAmt1.getOpcode() == ISD::SUB) {
16675     SDValue Sum = ShAmt1.getOperand(0);
16676     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16677       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16678       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16679         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16680       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16681         return DAG.getNode(Opc, DL, VT,
16682                            Op0, Op1,
16683                            DAG.getNode(ISD::TRUNCATE, DL,
16684                                        MVT::i8, ShAmt0));
16685     }
16686   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16687     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16688     if (ShAmt0C &&
16689         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16690       return DAG.getNode(Opc, DL, VT,
16691                          N0.getOperand(0), N1.getOperand(0),
16692                          DAG.getNode(ISD::TRUNCATE, DL,
16693                                        MVT::i8, ShAmt0));
16694   }
16695
16696   return SDValue();
16697 }
16698
16699 // Generate NEG and CMOV for integer abs.
16700 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16701   EVT VT = N->getValueType(0);
16702
16703   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16704   // 8-bit integer abs to NEG and CMOV.
16705   if (VT.isInteger() && VT.getSizeInBits() == 8)
16706     return SDValue();
16707
16708   SDValue N0 = N->getOperand(0);
16709   SDValue N1 = N->getOperand(1);
16710   DebugLoc DL = N->getDebugLoc();
16711
16712   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16713   // and change it to SUB and CMOV.
16714   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16715       N0.getOpcode() == ISD::ADD &&
16716       N0.getOperand(1) == N1 &&
16717       N1.getOpcode() == ISD::SRA &&
16718       N1.getOperand(0) == N0.getOperand(0))
16719     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16720       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16721         // Generate SUB & CMOV.
16722         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16723                                   DAG.getConstant(0, VT), N0.getOperand(0));
16724
16725         SDValue Ops[] = { N0.getOperand(0), Neg,
16726                           DAG.getConstant(X86::COND_GE, MVT::i8),
16727                           SDValue(Neg.getNode(), 1) };
16728         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16729                            Ops, array_lengthof(Ops));
16730       }
16731   return SDValue();
16732 }
16733
16734 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16735 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16736                                  TargetLowering::DAGCombinerInfo &DCI,
16737                                  const X86Subtarget *Subtarget) {
16738   EVT VT = N->getValueType(0);
16739   if (DCI.isBeforeLegalizeOps())
16740     return SDValue();
16741
16742   if (Subtarget->hasCMov()) {
16743     SDValue RV = performIntegerAbsCombine(N, DAG);
16744     if (RV.getNode())
16745       return RV;
16746   }
16747
16748   // Try forming BMI if it is available.
16749   if (!Subtarget->hasBMI())
16750     return SDValue();
16751
16752   if (VT != MVT::i32 && VT != MVT::i64)
16753     return SDValue();
16754
16755   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16756
16757   // Create BLSMSK instructions by finding X ^ (X-1)
16758   SDValue N0 = N->getOperand(0);
16759   SDValue N1 = N->getOperand(1);
16760   DebugLoc DL = N->getDebugLoc();
16761
16762   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16763       isAllOnes(N0.getOperand(1)))
16764     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16765
16766   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16767       isAllOnes(N1.getOperand(1)))
16768     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16769
16770   return SDValue();
16771 }
16772
16773 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16774 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16775                                   TargetLowering::DAGCombinerInfo &DCI,
16776                                   const X86Subtarget *Subtarget) {
16777   LoadSDNode *Ld = cast<LoadSDNode>(N);
16778   EVT RegVT = Ld->getValueType(0);
16779   EVT MemVT = Ld->getMemoryVT();
16780   DebugLoc dl = Ld->getDebugLoc();
16781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16782   unsigned RegSz = RegVT.getSizeInBits();
16783
16784   // On Sandybridge unaligned 256bit loads are inefficient.
16785   ISD::LoadExtType Ext = Ld->getExtensionType();
16786   unsigned Alignment = Ld->getAlignment();
16787   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16788   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16789       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16790     unsigned NumElems = RegVT.getVectorNumElements();
16791     if (NumElems < 2)
16792       return SDValue();
16793
16794     SDValue Ptr = Ld->getBasePtr();
16795     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16796
16797     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16798                                   NumElems/2);
16799     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16800                                 Ld->getPointerInfo(), Ld->isVolatile(),
16801                                 Ld->isNonTemporal(), Ld->isInvariant(),
16802                                 Alignment);
16803     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16804     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16805                                 Ld->getPointerInfo(), Ld->isVolatile(),
16806                                 Ld->isNonTemporal(), Ld->isInvariant(),
16807                                 std::min(16U, Alignment));
16808     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16809                              Load1.getValue(1),
16810                              Load2.getValue(1));
16811
16812     SDValue NewVec = DAG.getUNDEF(RegVT);
16813     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16814     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16815     return DCI.CombineTo(N, NewVec, TF, true);
16816   }
16817
16818   // If this is a vector EXT Load then attempt to optimize it using a
16819   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16820   // expansion is still better than scalar code.
16821   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16822   // emit a shuffle and a arithmetic shift.
16823   // TODO: It is possible to support ZExt by zeroing the undef values
16824   // during the shuffle phase or after the shuffle.
16825   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16826       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16827     assert(MemVT != RegVT && "Cannot extend to the same type");
16828     assert(MemVT.isVector() && "Must load a vector from memory");
16829
16830     unsigned NumElems = RegVT.getVectorNumElements();
16831     unsigned MemSz = MemVT.getSizeInBits();
16832     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16833
16834     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16835       return SDValue();
16836
16837     // All sizes must be a power of two.
16838     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16839       return SDValue();
16840
16841     // Attempt to load the original value using scalar loads.
16842     // Find the largest scalar type that divides the total loaded size.
16843     MVT SclrLoadTy = MVT::i8;
16844     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16845          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16846       MVT Tp = (MVT::SimpleValueType)tp;
16847       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16848         SclrLoadTy = Tp;
16849       }
16850     }
16851
16852     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16853     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16854         (64 <= MemSz))
16855       SclrLoadTy = MVT::f64;
16856
16857     // Calculate the number of scalar loads that we need to perform
16858     // in order to load our vector from memory.
16859     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16860     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16861       return SDValue();
16862
16863     unsigned loadRegZize = RegSz;
16864     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16865       loadRegZize /= 2;
16866
16867     // Represent our vector as a sequence of elements which are the
16868     // largest scalar that we can load.
16869     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16870       loadRegZize/SclrLoadTy.getSizeInBits());
16871
16872     // Represent the data using the same element type that is stored in
16873     // memory. In practice, we ''widen'' MemVT.
16874     EVT WideVecVT =
16875           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16876                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16877
16878     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16879       "Invalid vector type");
16880
16881     // We can't shuffle using an illegal type.
16882     if (!TLI.isTypeLegal(WideVecVT))
16883       return SDValue();
16884
16885     SmallVector<SDValue, 8> Chains;
16886     SDValue Ptr = Ld->getBasePtr();
16887     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16888                                         TLI.getPointerTy());
16889     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16890
16891     for (unsigned i = 0; i < NumLoads; ++i) {
16892       // Perform a single load.
16893       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16894                                        Ptr, Ld->getPointerInfo(),
16895                                        Ld->isVolatile(), Ld->isNonTemporal(),
16896                                        Ld->isInvariant(), Ld->getAlignment());
16897       Chains.push_back(ScalarLoad.getValue(1));
16898       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16899       // another round of DAGCombining.
16900       if (i == 0)
16901         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16902       else
16903         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16904                           ScalarLoad, DAG.getIntPtrConstant(i));
16905
16906       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16907     }
16908
16909     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16910                                Chains.size());
16911
16912     // Bitcast the loaded value to a vector of the original element type, in
16913     // the size of the target vector type.
16914     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16915     unsigned SizeRatio = RegSz/MemSz;
16916
16917     if (Ext == ISD::SEXTLOAD) {
16918       // If we have SSE4.1 we can directly emit a VSEXT node.
16919       if (Subtarget->hasSSE41()) {
16920         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16921         return DCI.CombineTo(N, Sext, TF, true);
16922       }
16923
16924       // Otherwise we'll shuffle the small elements in the high bits of the
16925       // larger type and perform an arithmetic shift. If the shift is not legal
16926       // it's better to scalarize.
16927       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16928         return SDValue();
16929
16930       // Redistribute the loaded elements into the different locations.
16931       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16932       for (unsigned i = 0; i != NumElems; ++i)
16933         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16934
16935       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16936                                            DAG.getUNDEF(WideVecVT),
16937                                            &ShuffleVec[0]);
16938
16939       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16940
16941       // Build the arithmetic shift.
16942       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16943                      MemVT.getVectorElementType().getSizeInBits();
16944       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16945                           DAG.getConstant(Amt, RegVT));
16946
16947       return DCI.CombineTo(N, Shuff, TF, true);
16948     }
16949
16950     // Redistribute the loaded elements into the different locations.
16951     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16952     for (unsigned i = 0; i != NumElems; ++i)
16953       ShuffleVec[i*SizeRatio] = i;
16954
16955     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16956                                          DAG.getUNDEF(WideVecVT),
16957                                          &ShuffleVec[0]);
16958
16959     // Bitcast to the requested type.
16960     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16961     // Replace the original load with the new sequence
16962     // and return the new chain.
16963     return DCI.CombineTo(N, Shuff, TF, true);
16964   }
16965
16966   return SDValue();
16967 }
16968
16969 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16970 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16971                                    const X86Subtarget *Subtarget) {
16972   StoreSDNode *St = cast<StoreSDNode>(N);
16973   EVT VT = St->getValue().getValueType();
16974   EVT StVT = St->getMemoryVT();
16975   DebugLoc dl = St->getDebugLoc();
16976   SDValue StoredVal = St->getOperand(1);
16977   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16978
16979   // If we are saving a concatenation of two XMM registers, perform two stores.
16980   // On Sandy Bridge, 256-bit memory operations are executed by two
16981   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
16982   // memory  operation.
16983   unsigned Alignment = St->getAlignment();
16984   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
16985   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
16986       StVT == VT && !IsAligned) {
16987     unsigned NumElems = VT.getVectorNumElements();
16988     if (NumElems < 2)
16989       return SDValue();
16990
16991     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
16992     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
16993
16994     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
16995     SDValue Ptr0 = St->getBasePtr();
16996     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
16997
16998     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
16999                                 St->getPointerInfo(), St->isVolatile(),
17000                                 St->isNonTemporal(), Alignment);
17001     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17002                                 St->getPointerInfo(), St->isVolatile(),
17003                                 St->isNonTemporal(),
17004                                 std::min(16U, Alignment));
17005     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17006   }
17007
17008   // Optimize trunc store (of multiple scalars) to shuffle and store.
17009   // First, pack all of the elements in one place. Next, store to memory
17010   // in fewer chunks.
17011   if (St->isTruncatingStore() && VT.isVector()) {
17012     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17013     unsigned NumElems = VT.getVectorNumElements();
17014     assert(StVT != VT && "Cannot truncate to the same type");
17015     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17016     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17017
17018     // From, To sizes and ElemCount must be pow of two
17019     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17020     // We are going to use the original vector elt for storing.
17021     // Accumulated smaller vector elements must be a multiple of the store size.
17022     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17023
17024     unsigned SizeRatio  = FromSz / ToSz;
17025
17026     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17027
17028     // Create a type on which we perform the shuffle
17029     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17030             StVT.getScalarType(), NumElems*SizeRatio);
17031
17032     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17033
17034     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17035     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17036     for (unsigned i = 0; i != NumElems; ++i)
17037       ShuffleVec[i] = i * SizeRatio;
17038
17039     // Can't shuffle using an illegal type.
17040     if (!TLI.isTypeLegal(WideVecVT))
17041       return SDValue();
17042
17043     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17044                                          DAG.getUNDEF(WideVecVT),
17045                                          &ShuffleVec[0]);
17046     // At this point all of the data is stored at the bottom of the
17047     // register. We now need to save it to mem.
17048
17049     // Find the largest store unit
17050     MVT StoreType = MVT::i8;
17051     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17052          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17053       MVT Tp = (MVT::SimpleValueType)tp;
17054       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17055         StoreType = Tp;
17056     }
17057
17058     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17059     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17060         (64 <= NumElems * ToSz))
17061       StoreType = MVT::f64;
17062
17063     // Bitcast the original vector into a vector of store-size units
17064     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17065             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17066     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17067     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17068     SmallVector<SDValue, 8> Chains;
17069     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17070                                         TLI.getPointerTy());
17071     SDValue Ptr = St->getBasePtr();
17072
17073     // Perform one or more big stores into memory.
17074     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17075       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17076                                    StoreType, ShuffWide,
17077                                    DAG.getIntPtrConstant(i));
17078       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17079                                 St->getPointerInfo(), St->isVolatile(),
17080                                 St->isNonTemporal(), St->getAlignment());
17081       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17082       Chains.push_back(Ch);
17083     }
17084
17085     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17086                                Chains.size());
17087   }
17088
17089   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17090   // the FP state in cases where an emms may be missing.
17091   // A preferable solution to the general problem is to figure out the right
17092   // places to insert EMMS.  This qualifies as a quick hack.
17093
17094   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17095   if (VT.getSizeInBits() != 64)
17096     return SDValue();
17097
17098   const Function *F = DAG.getMachineFunction().getFunction();
17099   bool NoImplicitFloatOps = F->getAttributes().
17100     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17101   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17102                      && Subtarget->hasSSE2();
17103   if ((VT.isVector() ||
17104        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17105       isa<LoadSDNode>(St->getValue()) &&
17106       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17107       St->getChain().hasOneUse() && !St->isVolatile()) {
17108     SDNode* LdVal = St->getValue().getNode();
17109     LoadSDNode *Ld = 0;
17110     int TokenFactorIndex = -1;
17111     SmallVector<SDValue, 8> Ops;
17112     SDNode* ChainVal = St->getChain().getNode();
17113     // Must be a store of a load.  We currently handle two cases:  the load
17114     // is a direct child, and it's under an intervening TokenFactor.  It is
17115     // possible to dig deeper under nested TokenFactors.
17116     if (ChainVal == LdVal)
17117       Ld = cast<LoadSDNode>(St->getChain());
17118     else if (St->getValue().hasOneUse() &&
17119              ChainVal->getOpcode() == ISD::TokenFactor) {
17120       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17121         if (ChainVal->getOperand(i).getNode() == LdVal) {
17122           TokenFactorIndex = i;
17123           Ld = cast<LoadSDNode>(St->getValue());
17124         } else
17125           Ops.push_back(ChainVal->getOperand(i));
17126       }
17127     }
17128
17129     if (!Ld || !ISD::isNormalLoad(Ld))
17130       return SDValue();
17131
17132     // If this is not the MMX case, i.e. we are just turning i64 load/store
17133     // into f64 load/store, avoid the transformation if there are multiple
17134     // uses of the loaded value.
17135     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17136       return SDValue();
17137
17138     DebugLoc LdDL = Ld->getDebugLoc();
17139     DebugLoc StDL = N->getDebugLoc();
17140     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17141     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17142     // pair instead.
17143     if (Subtarget->is64Bit() || F64IsLegal) {
17144       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17145       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17146                                   Ld->getPointerInfo(), Ld->isVolatile(),
17147                                   Ld->isNonTemporal(), Ld->isInvariant(),
17148                                   Ld->getAlignment());
17149       SDValue NewChain = NewLd.getValue(1);
17150       if (TokenFactorIndex != -1) {
17151         Ops.push_back(NewChain);
17152         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17153                                Ops.size());
17154       }
17155       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17156                           St->getPointerInfo(),
17157                           St->isVolatile(), St->isNonTemporal(),
17158                           St->getAlignment());
17159     }
17160
17161     // Otherwise, lower to two pairs of 32-bit loads / stores.
17162     SDValue LoAddr = Ld->getBasePtr();
17163     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17164                                  DAG.getConstant(4, MVT::i32));
17165
17166     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17167                                Ld->getPointerInfo(),
17168                                Ld->isVolatile(), Ld->isNonTemporal(),
17169                                Ld->isInvariant(), Ld->getAlignment());
17170     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17171                                Ld->getPointerInfo().getWithOffset(4),
17172                                Ld->isVolatile(), Ld->isNonTemporal(),
17173                                Ld->isInvariant(),
17174                                MinAlign(Ld->getAlignment(), 4));
17175
17176     SDValue NewChain = LoLd.getValue(1);
17177     if (TokenFactorIndex != -1) {
17178       Ops.push_back(LoLd);
17179       Ops.push_back(HiLd);
17180       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17181                              Ops.size());
17182     }
17183
17184     LoAddr = St->getBasePtr();
17185     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17186                          DAG.getConstant(4, MVT::i32));
17187
17188     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17189                                 St->getPointerInfo(),
17190                                 St->isVolatile(), St->isNonTemporal(),
17191                                 St->getAlignment());
17192     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17193                                 St->getPointerInfo().getWithOffset(4),
17194                                 St->isVolatile(),
17195                                 St->isNonTemporal(),
17196                                 MinAlign(St->getAlignment(), 4));
17197     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17198   }
17199   return SDValue();
17200 }
17201
17202 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17203 /// and return the operands for the horizontal operation in LHS and RHS.  A
17204 /// horizontal operation performs the binary operation on successive elements
17205 /// of its first operand, then on successive elements of its second operand,
17206 /// returning the resulting values in a vector.  For example, if
17207 ///   A = < float a0, float a1, float a2, float a3 >
17208 /// and
17209 ///   B = < float b0, float b1, float b2, float b3 >
17210 /// then the result of doing a horizontal operation on A and B is
17211 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17212 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17213 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17214 /// set to A, RHS to B, and the routine returns 'true'.
17215 /// Note that the binary operation should have the property that if one of the
17216 /// operands is UNDEF then the result is UNDEF.
17217 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17218   // Look for the following pattern: if
17219   //   A = < float a0, float a1, float a2, float a3 >
17220   //   B = < float b0, float b1, float b2, float b3 >
17221   // and
17222   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17223   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17224   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17225   // which is A horizontal-op B.
17226
17227   // At least one of the operands should be a vector shuffle.
17228   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17229       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17230     return false;
17231
17232   EVT VT = LHS.getValueType();
17233
17234   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17235          "Unsupported vector type for horizontal add/sub");
17236
17237   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17238   // operate independently on 128-bit lanes.
17239   unsigned NumElts = VT.getVectorNumElements();
17240   unsigned NumLanes = VT.getSizeInBits()/128;
17241   unsigned NumLaneElts = NumElts / NumLanes;
17242   assert((NumLaneElts % 2 == 0) &&
17243          "Vector type should have an even number of elements in each lane");
17244   unsigned HalfLaneElts = NumLaneElts/2;
17245
17246   // View LHS in the form
17247   //   LHS = VECTOR_SHUFFLE A, B, LMask
17248   // If LHS is not a shuffle then pretend it is the shuffle
17249   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17250   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17251   // type VT.
17252   SDValue A, B;
17253   SmallVector<int, 16> LMask(NumElts);
17254   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17255     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17256       A = LHS.getOperand(0);
17257     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17258       B = LHS.getOperand(1);
17259     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17260     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17261   } else {
17262     if (LHS.getOpcode() != ISD::UNDEF)
17263       A = LHS;
17264     for (unsigned i = 0; i != NumElts; ++i)
17265       LMask[i] = i;
17266   }
17267
17268   // Likewise, view RHS in the form
17269   //   RHS = VECTOR_SHUFFLE C, D, RMask
17270   SDValue C, D;
17271   SmallVector<int, 16> RMask(NumElts);
17272   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17273     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17274       C = RHS.getOperand(0);
17275     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17276       D = RHS.getOperand(1);
17277     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17278     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17279   } else {
17280     if (RHS.getOpcode() != ISD::UNDEF)
17281       C = RHS;
17282     for (unsigned i = 0; i != NumElts; ++i)
17283       RMask[i] = i;
17284   }
17285
17286   // Check that the shuffles are both shuffling the same vectors.
17287   if (!(A == C && B == D) && !(A == D && B == C))
17288     return false;
17289
17290   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17291   if (!A.getNode() && !B.getNode())
17292     return false;
17293
17294   // If A and B occur in reverse order in RHS, then "swap" them (which means
17295   // rewriting the mask).
17296   if (A != C)
17297     CommuteVectorShuffleMask(RMask, NumElts);
17298
17299   // At this point LHS and RHS are equivalent to
17300   //   LHS = VECTOR_SHUFFLE A, B, LMask
17301   //   RHS = VECTOR_SHUFFLE A, B, RMask
17302   // Check that the masks correspond to performing a horizontal operation.
17303   for (unsigned i = 0; i != NumElts; ++i) {
17304     int LIdx = LMask[i], RIdx = RMask[i];
17305
17306     // Ignore any UNDEF components.
17307     if (LIdx < 0 || RIdx < 0 ||
17308         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17309         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17310       continue;
17311
17312     // Check that successive elements are being operated on.  If not, this is
17313     // not a horizontal operation.
17314     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17315     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17316     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17317     if (!(LIdx == Index && RIdx == Index + 1) &&
17318         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17319       return false;
17320   }
17321
17322   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17323   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17324   return true;
17325 }
17326
17327 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17328 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17329                                   const X86Subtarget *Subtarget) {
17330   EVT VT = N->getValueType(0);
17331   SDValue LHS = N->getOperand(0);
17332   SDValue RHS = N->getOperand(1);
17333
17334   // Try to synthesize horizontal adds from adds of shuffles.
17335   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17336        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17337       isHorizontalBinOp(LHS, RHS, true))
17338     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17339   return SDValue();
17340 }
17341
17342 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17343 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17344                                   const X86Subtarget *Subtarget) {
17345   EVT VT = N->getValueType(0);
17346   SDValue LHS = N->getOperand(0);
17347   SDValue RHS = N->getOperand(1);
17348
17349   // Try to synthesize horizontal subs from subs of shuffles.
17350   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17351        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17352       isHorizontalBinOp(LHS, RHS, false))
17353     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17354   return SDValue();
17355 }
17356
17357 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17358 /// X86ISD::FXOR nodes.
17359 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17360   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17361   // F[X]OR(0.0, x) -> x
17362   // F[X]OR(x, 0.0) -> x
17363   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17364     if (C->getValueAPF().isPosZero())
17365       return N->getOperand(1);
17366   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17367     if (C->getValueAPF().isPosZero())
17368       return N->getOperand(0);
17369   return SDValue();
17370 }
17371
17372 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17373 /// X86ISD::FMAX nodes.
17374 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17375   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17376
17377   // Only perform optimizations if UnsafeMath is used.
17378   if (!DAG.getTarget().Options.UnsafeFPMath)
17379     return SDValue();
17380
17381   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17382   // into FMINC and FMAXC, which are Commutative operations.
17383   unsigned NewOp = 0;
17384   switch (N->getOpcode()) {
17385     default: llvm_unreachable("unknown opcode");
17386     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17387     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17388   }
17389
17390   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17391                      N->getOperand(0), N->getOperand(1));
17392 }
17393
17394 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17395 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17396   // FAND(0.0, x) -> 0.0
17397   // FAND(x, 0.0) -> 0.0
17398   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17399     if (C->getValueAPF().isPosZero())
17400       return N->getOperand(0);
17401   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17402     if (C->getValueAPF().isPosZero())
17403       return N->getOperand(1);
17404   return SDValue();
17405 }
17406
17407 static SDValue PerformBTCombine(SDNode *N,
17408                                 SelectionDAG &DAG,
17409                                 TargetLowering::DAGCombinerInfo &DCI) {
17410   // BT ignores high bits in the bit index operand.
17411   SDValue Op1 = N->getOperand(1);
17412   if (Op1.hasOneUse()) {
17413     unsigned BitWidth = Op1.getValueSizeInBits();
17414     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17415     APInt KnownZero, KnownOne;
17416     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17417                                           !DCI.isBeforeLegalizeOps());
17418     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17419     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17420         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17421       DCI.CommitTargetLoweringOpt(TLO);
17422   }
17423   return SDValue();
17424 }
17425
17426 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17427   SDValue Op = N->getOperand(0);
17428   if (Op.getOpcode() == ISD::BITCAST)
17429     Op = Op.getOperand(0);
17430   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17431   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17432       VT.getVectorElementType().getSizeInBits() ==
17433       OpVT.getVectorElementType().getSizeInBits()) {
17434     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17435   }
17436   return SDValue();
17437 }
17438
17439 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17440                                                const X86Subtarget *Subtarget) {
17441   EVT VT = N->getValueType(0);
17442   if (!VT.isVector())
17443     return SDValue();
17444
17445   SDValue N0 = N->getOperand(0);
17446   SDValue N1 = N->getOperand(1);
17447   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17448   DebugLoc dl = N->getDebugLoc();
17449
17450   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17451   // both SSE and AVX2 since there is no sign-extended shift right
17452   // operation on a vector with 64-bit elements.
17453   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17454   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17455   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17456       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17457     SDValue N00 = N0.getOperand(0);
17458
17459     // EXTLOAD has a better solution on AVX2,
17460     // it may be replaced with X86ISD::VSEXT node.
17461     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17462       if (!ISD::isNormalLoad(N00.getNode()))
17463         return SDValue();
17464
17465     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17466         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17467                                   N00, N1);
17468       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17469     }
17470   }
17471   return SDValue();
17472 }
17473
17474 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17475                                   TargetLowering::DAGCombinerInfo &DCI,
17476                                   const X86Subtarget *Subtarget) {
17477   if (!DCI.isBeforeLegalizeOps())
17478     return SDValue();
17479
17480   if (!Subtarget->hasFp256())
17481     return SDValue();
17482
17483   EVT VT = N->getValueType(0);
17484   if (VT.isVector() && VT.getSizeInBits() == 256) {
17485     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17486     if (R.getNode())
17487       return R;
17488   }
17489
17490   return SDValue();
17491 }
17492
17493 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17494                                  const X86Subtarget* Subtarget) {
17495   DebugLoc dl = N->getDebugLoc();
17496   EVT VT = N->getValueType(0);
17497
17498   // Let legalize expand this if it isn't a legal type yet.
17499   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17500     return SDValue();
17501
17502   EVT ScalarVT = VT.getScalarType();
17503   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17504       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17505     return SDValue();
17506
17507   SDValue A = N->getOperand(0);
17508   SDValue B = N->getOperand(1);
17509   SDValue C = N->getOperand(2);
17510
17511   bool NegA = (A.getOpcode() == ISD::FNEG);
17512   bool NegB = (B.getOpcode() == ISD::FNEG);
17513   bool NegC = (C.getOpcode() == ISD::FNEG);
17514
17515   // Negative multiplication when NegA xor NegB
17516   bool NegMul = (NegA != NegB);
17517   if (NegA)
17518     A = A.getOperand(0);
17519   if (NegB)
17520     B = B.getOperand(0);
17521   if (NegC)
17522     C = C.getOperand(0);
17523
17524   unsigned Opcode;
17525   if (!NegMul)
17526     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17527   else
17528     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17529
17530   return DAG.getNode(Opcode, dl, VT, A, B, C);
17531 }
17532
17533 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17534                                   TargetLowering::DAGCombinerInfo &DCI,
17535                                   const X86Subtarget *Subtarget) {
17536   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17537   //           (and (i32 x86isd::setcc_carry), 1)
17538   // This eliminates the zext. This transformation is necessary because
17539   // ISD::SETCC is always legalized to i8.
17540   DebugLoc dl = N->getDebugLoc();
17541   SDValue N0 = N->getOperand(0);
17542   EVT VT = N->getValueType(0);
17543
17544   if (N0.getOpcode() == ISD::AND &&
17545       N0.hasOneUse() &&
17546       N0.getOperand(0).hasOneUse()) {
17547     SDValue N00 = N0.getOperand(0);
17548     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17549       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17550       if (!C || C->getZExtValue() != 1)
17551         return SDValue();
17552       return DAG.getNode(ISD::AND, dl, VT,
17553                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17554                                      N00.getOperand(0), N00.getOperand(1)),
17555                          DAG.getConstant(1, VT));
17556     }
17557   }
17558
17559   if (VT.is256BitVector()) {
17560     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17561     if (R.getNode())
17562       return R;
17563   }
17564
17565   return SDValue();
17566 }
17567
17568 // Optimize x == -y --> x+y == 0
17569 //          x != -y --> x+y != 0
17570 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17571   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17572   SDValue LHS = N->getOperand(0);
17573   SDValue RHS = N->getOperand(1);
17574
17575   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17576     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17577       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17578         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17579                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17580         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17581                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17582       }
17583   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17584     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17585       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17586         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17587                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17588         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17589                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17590       }
17591   return SDValue();
17592 }
17593
17594 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17595 // as "sbb reg,reg", since it can be extended without zext and produces
17596 // an all-ones bit which is more useful than 0/1 in some cases.
17597 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17598   return DAG.getNode(ISD::AND, DL, MVT::i8,
17599                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17600                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17601                      DAG.getConstant(1, MVT::i8));
17602 }
17603
17604 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17605 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17606                                    TargetLowering::DAGCombinerInfo &DCI,
17607                                    const X86Subtarget *Subtarget) {
17608   DebugLoc DL = N->getDebugLoc();
17609   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17610   SDValue EFLAGS = N->getOperand(1);
17611
17612   if (CC == X86::COND_A) {
17613     // Try to convert COND_A into COND_B in an attempt to facilitate
17614     // materializing "setb reg".
17615     //
17616     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17617     // cannot take an immediate as its first operand.
17618     //
17619     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17620         EFLAGS.getValueType().isInteger() &&
17621         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17622       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17623                                    EFLAGS.getNode()->getVTList(),
17624                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17625       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17626       return MaterializeSETB(DL, NewEFLAGS, DAG);
17627     }
17628   }
17629
17630   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17631   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17632   // cases.
17633   if (CC == X86::COND_B)
17634     return MaterializeSETB(DL, EFLAGS, DAG);
17635
17636   SDValue Flags;
17637
17638   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17639   if (Flags.getNode()) {
17640     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17641     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17642   }
17643
17644   return SDValue();
17645 }
17646
17647 // Optimize branch condition evaluation.
17648 //
17649 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17650                                     TargetLowering::DAGCombinerInfo &DCI,
17651                                     const X86Subtarget *Subtarget) {
17652   DebugLoc DL = N->getDebugLoc();
17653   SDValue Chain = N->getOperand(0);
17654   SDValue Dest = N->getOperand(1);
17655   SDValue EFLAGS = N->getOperand(3);
17656   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17657
17658   SDValue Flags;
17659
17660   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17661   if (Flags.getNode()) {
17662     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17663     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17664                        Flags);
17665   }
17666
17667   return SDValue();
17668 }
17669
17670 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17671                                         const X86TargetLowering *XTLI) {
17672   SDValue Op0 = N->getOperand(0);
17673   EVT InVT = Op0->getValueType(0);
17674
17675   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17676   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17677     DebugLoc dl = N->getDebugLoc();
17678     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17679     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17680     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17681   }
17682
17683   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17684   // a 32-bit target where SSE doesn't support i64->FP operations.
17685   if (Op0.getOpcode() == ISD::LOAD) {
17686     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17687     EVT VT = Ld->getValueType(0);
17688     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17689         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17690         !XTLI->getSubtarget()->is64Bit() &&
17691         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17692       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17693                                           Ld->getChain(), Op0, DAG);
17694       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17695       return FILDChain;
17696     }
17697   }
17698   return SDValue();
17699 }
17700
17701 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17702 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17703                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17704   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17705   // the result is either zero or one (depending on the input carry bit).
17706   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17707   if (X86::isZeroNode(N->getOperand(0)) &&
17708       X86::isZeroNode(N->getOperand(1)) &&
17709       // We don't have a good way to replace an EFLAGS use, so only do this when
17710       // dead right now.
17711       SDValue(N, 1).use_empty()) {
17712     DebugLoc DL = N->getDebugLoc();
17713     EVT VT = N->getValueType(0);
17714     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17715     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17716                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17717                                            DAG.getConstant(X86::COND_B,MVT::i8),
17718                                            N->getOperand(2)),
17719                                DAG.getConstant(1, VT));
17720     return DCI.CombineTo(N, Res1, CarryOut);
17721   }
17722
17723   return SDValue();
17724 }
17725
17726 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17727 //      (add Y, (setne X, 0)) -> sbb -1, Y
17728 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17729 //      (sub (setne X, 0), Y) -> adc -1, Y
17730 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17731   DebugLoc DL = N->getDebugLoc();
17732
17733   // Look through ZExts.
17734   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17735   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17736     return SDValue();
17737
17738   SDValue SetCC = Ext.getOperand(0);
17739   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17740     return SDValue();
17741
17742   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17743   if (CC != X86::COND_E && CC != X86::COND_NE)
17744     return SDValue();
17745
17746   SDValue Cmp = SetCC.getOperand(1);
17747   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17748       !X86::isZeroNode(Cmp.getOperand(1)) ||
17749       !Cmp.getOperand(0).getValueType().isInteger())
17750     return SDValue();
17751
17752   SDValue CmpOp0 = Cmp.getOperand(0);
17753   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17754                                DAG.getConstant(1, CmpOp0.getValueType()));
17755
17756   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17757   if (CC == X86::COND_NE)
17758     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17759                        DL, OtherVal.getValueType(), OtherVal,
17760                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17761   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17762                      DL, OtherVal.getValueType(), OtherVal,
17763                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17764 }
17765
17766 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17767 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17768                                  const X86Subtarget *Subtarget) {
17769   EVT VT = N->getValueType(0);
17770   SDValue Op0 = N->getOperand(0);
17771   SDValue Op1 = N->getOperand(1);
17772
17773   // Try to synthesize horizontal adds from adds of shuffles.
17774   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17775        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17776       isHorizontalBinOp(Op0, Op1, true))
17777     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17778
17779   return OptimizeConditionalInDecrement(N, DAG);
17780 }
17781
17782 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17783                                  const X86Subtarget *Subtarget) {
17784   SDValue Op0 = N->getOperand(0);
17785   SDValue Op1 = N->getOperand(1);
17786
17787   // X86 can't encode an immediate LHS of a sub. See if we can push the
17788   // negation into a preceding instruction.
17789   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17790     // If the RHS of the sub is a XOR with one use and a constant, invert the
17791     // immediate. Then add one to the LHS of the sub so we can turn
17792     // X-Y -> X+~Y+1, saving one register.
17793     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17794         isa<ConstantSDNode>(Op1.getOperand(1))) {
17795       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17796       EVT VT = Op0.getValueType();
17797       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17798                                    Op1.getOperand(0),
17799                                    DAG.getConstant(~XorC, VT));
17800       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17801                          DAG.getConstant(C->getAPIntValue()+1, VT));
17802     }
17803   }
17804
17805   // Try to synthesize horizontal adds from adds of shuffles.
17806   EVT VT = N->getValueType(0);
17807   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17808        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17809       isHorizontalBinOp(Op0, Op1, true))
17810     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17811
17812   return OptimizeConditionalInDecrement(N, DAG);
17813 }
17814
17815 /// performVZEXTCombine - Performs build vector combines
17816 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17817                                         TargetLowering::DAGCombinerInfo &DCI,
17818                                         const X86Subtarget *Subtarget) {
17819   // (vzext (bitcast (vzext (x)) -> (vzext x)
17820   SDValue In = N->getOperand(0);
17821   while (In.getOpcode() == ISD::BITCAST)
17822     In = In.getOperand(0);
17823
17824   if (In.getOpcode() != X86ISD::VZEXT)
17825     return SDValue();
17826
17827   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17828                      In.getOperand(0));
17829 }
17830
17831 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17832                                              DAGCombinerInfo &DCI) const {
17833   SelectionDAG &DAG = DCI.DAG;
17834   switch (N->getOpcode()) {
17835   default: break;
17836   case ISD::EXTRACT_VECTOR_ELT:
17837     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17838   case ISD::VSELECT:
17839   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17840   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17841   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17842   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17843   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17844   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17845   case ISD::SHL:
17846   case ISD::SRA:
17847   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17848   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17849   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17850   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17851   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17852   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17853   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17854   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17855   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17856   case X86ISD::FXOR:
17857   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17858   case X86ISD::FMIN:
17859   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17860   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17861   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17862   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17863   case ISD::ANY_EXTEND:
17864   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17865   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17866   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17867   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17868   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17869   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17870   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17871   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17872   case X86ISD::SHUFP:       // Handle all target specific shuffles
17873   case X86ISD::PALIGNR:
17874   case X86ISD::UNPCKH:
17875   case X86ISD::UNPCKL:
17876   case X86ISD::MOVHLPS:
17877   case X86ISD::MOVLHPS:
17878   case X86ISD::PSHUFD:
17879   case X86ISD::PSHUFHW:
17880   case X86ISD::PSHUFLW:
17881   case X86ISD::MOVSS:
17882   case X86ISD::MOVSD:
17883   case X86ISD::VPERMILP:
17884   case X86ISD::VPERM2X128:
17885   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17886   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17887   }
17888
17889   return SDValue();
17890 }
17891
17892 /// isTypeDesirableForOp - Return true if the target has native support for
17893 /// the specified value type and it is 'desirable' to use the type for the
17894 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17895 /// instruction encodings are longer and some i16 instructions are slow.
17896 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17897   if (!isTypeLegal(VT))
17898     return false;
17899   if (VT != MVT::i16)
17900     return true;
17901
17902   switch (Opc) {
17903   default:
17904     return true;
17905   case ISD::LOAD:
17906   case ISD::SIGN_EXTEND:
17907   case ISD::ZERO_EXTEND:
17908   case ISD::ANY_EXTEND:
17909   case ISD::SHL:
17910   case ISD::SRL:
17911   case ISD::SUB:
17912   case ISD::ADD:
17913   case ISD::MUL:
17914   case ISD::AND:
17915   case ISD::OR:
17916   case ISD::XOR:
17917     return false;
17918   }
17919 }
17920
17921 /// IsDesirableToPromoteOp - This method query the target whether it is
17922 /// beneficial for dag combiner to promote the specified node. If true, it
17923 /// should return the desired promotion type by reference.
17924 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17925   EVT VT = Op.getValueType();
17926   if (VT != MVT::i16)
17927     return false;
17928
17929   bool Promote = false;
17930   bool Commute = false;
17931   switch (Op.getOpcode()) {
17932   default: break;
17933   case ISD::LOAD: {
17934     LoadSDNode *LD = cast<LoadSDNode>(Op);
17935     // If the non-extending load has a single use and it's not live out, then it
17936     // might be folded.
17937     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17938                                                      Op.hasOneUse()*/) {
17939       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17940              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17941         // The only case where we'd want to promote LOAD (rather then it being
17942         // promoted as an operand is when it's only use is liveout.
17943         if (UI->getOpcode() != ISD::CopyToReg)
17944           return false;
17945       }
17946     }
17947     Promote = true;
17948     break;
17949   }
17950   case ISD::SIGN_EXTEND:
17951   case ISD::ZERO_EXTEND:
17952   case ISD::ANY_EXTEND:
17953     Promote = true;
17954     break;
17955   case ISD::SHL:
17956   case ISD::SRL: {
17957     SDValue N0 = Op.getOperand(0);
17958     // Look out for (store (shl (load), x)).
17959     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17960       return false;
17961     Promote = true;
17962     break;
17963   }
17964   case ISD::ADD:
17965   case ISD::MUL:
17966   case ISD::AND:
17967   case ISD::OR:
17968   case ISD::XOR:
17969     Commute = true;
17970     // fallthrough
17971   case ISD::SUB: {
17972     SDValue N0 = Op.getOperand(0);
17973     SDValue N1 = Op.getOperand(1);
17974     if (!Commute && MayFoldLoad(N1))
17975       return false;
17976     // Avoid disabling potential load folding opportunities.
17977     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
17978       return false;
17979     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
17980       return false;
17981     Promote = true;
17982   }
17983   }
17984
17985   PVT = MVT::i32;
17986   return Promote;
17987 }
17988
17989 //===----------------------------------------------------------------------===//
17990 //                           X86 Inline Assembly Support
17991 //===----------------------------------------------------------------------===//
17992
17993 namespace {
17994   // Helper to match a string separated by whitespace.
17995   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
17996     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
17997
17998     for (unsigned i = 0, e = args.size(); i != e; ++i) {
17999       StringRef piece(*args[i]);
18000       if (!s.startswith(piece)) // Check if the piece matches.
18001         return false;
18002
18003       s = s.substr(piece.size());
18004       StringRef::size_type pos = s.find_first_not_of(" \t");
18005       if (pos == 0) // We matched a prefix.
18006         return false;
18007
18008       s = s.substr(pos);
18009     }
18010
18011     return s.empty();
18012   }
18013   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18014 }
18015
18016 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18017   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18018
18019   std::string AsmStr = IA->getAsmString();
18020
18021   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18022   if (!Ty || Ty->getBitWidth() % 16 != 0)
18023     return false;
18024
18025   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18026   SmallVector<StringRef, 4> AsmPieces;
18027   SplitString(AsmStr, AsmPieces, ";\n");
18028
18029   switch (AsmPieces.size()) {
18030   default: return false;
18031   case 1:
18032     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18033     // we will turn this bswap into something that will be lowered to logical
18034     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18035     // lower so don't worry about this.
18036     // bswap $0
18037     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18038         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18039         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18040         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18041         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18042         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18043       // No need to check constraints, nothing other than the equivalent of
18044       // "=r,0" would be valid here.
18045       return IntrinsicLowering::LowerToByteSwap(CI);
18046     }
18047
18048     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18049     if (CI->getType()->isIntegerTy(16) &&
18050         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18051         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18052          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18053       AsmPieces.clear();
18054       const std::string &ConstraintsStr = IA->getConstraintString();
18055       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18056       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18057       if (AsmPieces.size() == 4 &&
18058           AsmPieces[0] == "~{cc}" &&
18059           AsmPieces[1] == "~{dirflag}" &&
18060           AsmPieces[2] == "~{flags}" &&
18061           AsmPieces[3] == "~{fpsr}")
18062       return IntrinsicLowering::LowerToByteSwap(CI);
18063     }
18064     break;
18065   case 3:
18066     if (CI->getType()->isIntegerTy(32) &&
18067         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18068         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18069         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18070         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18071       AsmPieces.clear();
18072       const std::string &ConstraintsStr = IA->getConstraintString();
18073       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18074       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18075       if (AsmPieces.size() == 4 &&
18076           AsmPieces[0] == "~{cc}" &&
18077           AsmPieces[1] == "~{dirflag}" &&
18078           AsmPieces[2] == "~{flags}" &&
18079           AsmPieces[3] == "~{fpsr}")
18080         return IntrinsicLowering::LowerToByteSwap(CI);
18081     }
18082
18083     if (CI->getType()->isIntegerTy(64)) {
18084       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18085       if (Constraints.size() >= 2 &&
18086           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18087           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18088         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18089         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18090             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18091             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18092           return IntrinsicLowering::LowerToByteSwap(CI);
18093       }
18094     }
18095     break;
18096   }
18097   return false;
18098 }
18099
18100 /// getConstraintType - Given a constraint letter, return the type of
18101 /// constraint it is for this target.
18102 X86TargetLowering::ConstraintType
18103 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18104   if (Constraint.size() == 1) {
18105     switch (Constraint[0]) {
18106     case 'R':
18107     case 'q':
18108     case 'Q':
18109     case 'f':
18110     case 't':
18111     case 'u':
18112     case 'y':
18113     case 'x':
18114     case 'Y':
18115     case 'l':
18116       return C_RegisterClass;
18117     case 'a':
18118     case 'b':
18119     case 'c':
18120     case 'd':
18121     case 'S':
18122     case 'D':
18123     case 'A':
18124       return C_Register;
18125     case 'I':
18126     case 'J':
18127     case 'K':
18128     case 'L':
18129     case 'M':
18130     case 'N':
18131     case 'G':
18132     case 'C':
18133     case 'e':
18134     case 'Z':
18135       return C_Other;
18136     default:
18137       break;
18138     }
18139   }
18140   return TargetLowering::getConstraintType(Constraint);
18141 }
18142
18143 /// Examine constraint type and operand type and determine a weight value.
18144 /// This object must already have been set up with the operand type
18145 /// and the current alternative constraint selected.
18146 TargetLowering::ConstraintWeight
18147   X86TargetLowering::getSingleConstraintMatchWeight(
18148     AsmOperandInfo &info, const char *constraint) const {
18149   ConstraintWeight weight = CW_Invalid;
18150   Value *CallOperandVal = info.CallOperandVal;
18151     // If we don't have a value, we can't do a match,
18152     // but allow it at the lowest weight.
18153   if (CallOperandVal == NULL)
18154     return CW_Default;
18155   Type *type = CallOperandVal->getType();
18156   // Look at the constraint type.
18157   switch (*constraint) {
18158   default:
18159     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18160   case 'R':
18161   case 'q':
18162   case 'Q':
18163   case 'a':
18164   case 'b':
18165   case 'c':
18166   case 'd':
18167   case 'S':
18168   case 'D':
18169   case 'A':
18170     if (CallOperandVal->getType()->isIntegerTy())
18171       weight = CW_SpecificReg;
18172     break;
18173   case 'f':
18174   case 't':
18175   case 'u':
18176     if (type->isFloatingPointTy())
18177       weight = CW_SpecificReg;
18178     break;
18179   case 'y':
18180     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18181       weight = CW_SpecificReg;
18182     break;
18183   case 'x':
18184   case 'Y':
18185     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18186         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18187       weight = CW_Register;
18188     break;
18189   case 'I':
18190     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18191       if (C->getZExtValue() <= 31)
18192         weight = CW_Constant;
18193     }
18194     break;
18195   case 'J':
18196     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18197       if (C->getZExtValue() <= 63)
18198         weight = CW_Constant;
18199     }
18200     break;
18201   case 'K':
18202     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18203       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18204         weight = CW_Constant;
18205     }
18206     break;
18207   case 'L':
18208     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18209       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18210         weight = CW_Constant;
18211     }
18212     break;
18213   case 'M':
18214     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18215       if (C->getZExtValue() <= 3)
18216         weight = CW_Constant;
18217     }
18218     break;
18219   case 'N':
18220     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18221       if (C->getZExtValue() <= 0xff)
18222         weight = CW_Constant;
18223     }
18224     break;
18225   case 'G':
18226   case 'C':
18227     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18228       weight = CW_Constant;
18229     }
18230     break;
18231   case 'e':
18232     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18233       if ((C->getSExtValue() >= -0x80000000LL) &&
18234           (C->getSExtValue() <= 0x7fffffffLL))
18235         weight = CW_Constant;
18236     }
18237     break;
18238   case 'Z':
18239     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18240       if (C->getZExtValue() <= 0xffffffff)
18241         weight = CW_Constant;
18242     }
18243     break;
18244   }
18245   return weight;
18246 }
18247
18248 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18249 /// with another that has more specific requirements based on the type of the
18250 /// corresponding operand.
18251 const char *X86TargetLowering::
18252 LowerXConstraint(EVT ConstraintVT) const {
18253   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18254   // 'f' like normal targets.
18255   if (ConstraintVT.isFloatingPoint()) {
18256     if (Subtarget->hasSSE2())
18257       return "Y";
18258     if (Subtarget->hasSSE1())
18259       return "x";
18260   }
18261
18262   return TargetLowering::LowerXConstraint(ConstraintVT);
18263 }
18264
18265 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18266 /// vector.  If it is invalid, don't add anything to Ops.
18267 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18268                                                      std::string &Constraint,
18269                                                      std::vector<SDValue>&Ops,
18270                                                      SelectionDAG &DAG) const {
18271   SDValue Result(0, 0);
18272
18273   // Only support length 1 constraints for now.
18274   if (Constraint.length() > 1) return;
18275
18276   char ConstraintLetter = Constraint[0];
18277   switch (ConstraintLetter) {
18278   default: break;
18279   case 'I':
18280     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18281       if (C->getZExtValue() <= 31) {
18282         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18283         break;
18284       }
18285     }
18286     return;
18287   case 'J':
18288     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18289       if (C->getZExtValue() <= 63) {
18290         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18291         break;
18292       }
18293     }
18294     return;
18295   case 'K':
18296     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18297       if (isInt<8>(C->getSExtValue())) {
18298         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18299         break;
18300       }
18301     }
18302     return;
18303   case 'N':
18304     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18305       if (C->getZExtValue() <= 255) {
18306         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18307         break;
18308       }
18309     }
18310     return;
18311   case 'e': {
18312     // 32-bit signed value
18313     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18314       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18315                                            C->getSExtValue())) {
18316         // Widen to 64 bits here to get it sign extended.
18317         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18318         break;
18319       }
18320     // FIXME gcc accepts some relocatable values here too, but only in certain
18321     // memory models; it's complicated.
18322     }
18323     return;
18324   }
18325   case 'Z': {
18326     // 32-bit unsigned value
18327     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18328       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18329                                            C->getZExtValue())) {
18330         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18331         break;
18332       }
18333     }
18334     // FIXME gcc accepts some relocatable values here too, but only in certain
18335     // memory models; it's complicated.
18336     return;
18337   }
18338   case 'i': {
18339     // Literal immediates are always ok.
18340     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18341       // Widen to 64 bits here to get it sign extended.
18342       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18343       break;
18344     }
18345
18346     // In any sort of PIC mode addresses need to be computed at runtime by
18347     // adding in a register or some sort of table lookup.  These can't
18348     // be used as immediates.
18349     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18350       return;
18351
18352     // If we are in non-pic codegen mode, we allow the address of a global (with
18353     // an optional displacement) to be used with 'i'.
18354     GlobalAddressSDNode *GA = 0;
18355     int64_t Offset = 0;
18356
18357     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18358     while (1) {
18359       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18360         Offset += GA->getOffset();
18361         break;
18362       } else if (Op.getOpcode() == ISD::ADD) {
18363         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18364           Offset += C->getZExtValue();
18365           Op = Op.getOperand(0);
18366           continue;
18367         }
18368       } else if (Op.getOpcode() == ISD::SUB) {
18369         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18370           Offset += -C->getZExtValue();
18371           Op = Op.getOperand(0);
18372           continue;
18373         }
18374       }
18375
18376       // Otherwise, this isn't something we can handle, reject it.
18377       return;
18378     }
18379
18380     const GlobalValue *GV = GA->getGlobal();
18381     // If we require an extra load to get this address, as in PIC mode, we
18382     // can't accept it.
18383     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18384                                                         getTargetMachine())))
18385       return;
18386
18387     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18388                                         GA->getValueType(0), Offset);
18389     break;
18390   }
18391   }
18392
18393   if (Result.getNode()) {
18394     Ops.push_back(Result);
18395     return;
18396   }
18397   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18398 }
18399
18400 std::pair<unsigned, const TargetRegisterClass*>
18401 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18402                                                 EVT VT) const {
18403   // First, see if this is a constraint that directly corresponds to an LLVM
18404   // register class.
18405   if (Constraint.size() == 1) {
18406     // GCC Constraint Letters
18407     switch (Constraint[0]) {
18408     default: break;
18409       // TODO: Slight differences here in allocation order and leaving
18410       // RIP in the class. Do they matter any more here than they do
18411       // in the normal allocation?
18412     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18413       if (Subtarget->is64Bit()) {
18414         if (VT == MVT::i32 || VT == MVT::f32)
18415           return std::make_pair(0U, &X86::GR32RegClass);
18416         if (VT == MVT::i16)
18417           return std::make_pair(0U, &X86::GR16RegClass);
18418         if (VT == MVT::i8 || VT == MVT::i1)
18419           return std::make_pair(0U, &X86::GR8RegClass);
18420         if (VT == MVT::i64 || VT == MVT::f64)
18421           return std::make_pair(0U, &X86::GR64RegClass);
18422         break;
18423       }
18424       // 32-bit fallthrough
18425     case 'Q':   // Q_REGS
18426       if (VT == MVT::i32 || VT == MVT::f32)
18427         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18428       if (VT == MVT::i16)
18429         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18430       if (VT == MVT::i8 || VT == MVT::i1)
18431         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18432       if (VT == MVT::i64)
18433         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18434       break;
18435     case 'r':   // GENERAL_REGS
18436     case 'l':   // INDEX_REGS
18437       if (VT == MVT::i8 || VT == MVT::i1)
18438         return std::make_pair(0U, &X86::GR8RegClass);
18439       if (VT == MVT::i16)
18440         return std::make_pair(0U, &X86::GR16RegClass);
18441       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18442         return std::make_pair(0U, &X86::GR32RegClass);
18443       return std::make_pair(0U, &X86::GR64RegClass);
18444     case 'R':   // LEGACY_REGS
18445       if (VT == MVT::i8 || VT == MVT::i1)
18446         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18447       if (VT == MVT::i16)
18448         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18449       if (VT == MVT::i32 || !Subtarget->is64Bit())
18450         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18451       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18452     case 'f':  // FP Stack registers.
18453       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18454       // value to the correct fpstack register class.
18455       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18456         return std::make_pair(0U, &X86::RFP32RegClass);
18457       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18458         return std::make_pair(0U, &X86::RFP64RegClass);
18459       return std::make_pair(0U, &X86::RFP80RegClass);
18460     case 'y':   // MMX_REGS if MMX allowed.
18461       if (!Subtarget->hasMMX()) break;
18462       return std::make_pair(0U, &X86::VR64RegClass);
18463     case 'Y':   // SSE_REGS if SSE2 allowed
18464       if (!Subtarget->hasSSE2()) break;
18465       // FALL THROUGH.
18466     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18467       if (!Subtarget->hasSSE1()) break;
18468
18469       switch (VT.getSimpleVT().SimpleTy) {
18470       default: break;
18471       // Scalar SSE types.
18472       case MVT::f32:
18473       case MVT::i32:
18474         return std::make_pair(0U, &X86::FR32RegClass);
18475       case MVT::f64:
18476       case MVT::i64:
18477         return std::make_pair(0U, &X86::FR64RegClass);
18478       // Vector types.
18479       case MVT::v16i8:
18480       case MVT::v8i16:
18481       case MVT::v4i32:
18482       case MVT::v2i64:
18483       case MVT::v4f32:
18484       case MVT::v2f64:
18485         return std::make_pair(0U, &X86::VR128RegClass);
18486       // AVX types.
18487       case MVT::v32i8:
18488       case MVT::v16i16:
18489       case MVT::v8i32:
18490       case MVT::v4i64:
18491       case MVT::v8f32:
18492       case MVT::v4f64:
18493         return std::make_pair(0U, &X86::VR256RegClass);
18494       }
18495       break;
18496     }
18497   }
18498
18499   // Use the default implementation in TargetLowering to convert the register
18500   // constraint into a member of a register class.
18501   std::pair<unsigned, const TargetRegisterClass*> Res;
18502   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18503
18504   // Not found as a standard register?
18505   if (Res.second == 0) {
18506     // Map st(0) -> st(7) -> ST0
18507     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18508         tolower(Constraint[1]) == 's' &&
18509         tolower(Constraint[2]) == 't' &&
18510         Constraint[3] == '(' &&
18511         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18512         Constraint[5] == ')' &&
18513         Constraint[6] == '}') {
18514
18515       Res.first = X86::ST0+Constraint[4]-'0';
18516       Res.second = &X86::RFP80RegClass;
18517       return Res;
18518     }
18519
18520     // GCC allows "st(0)" to be called just plain "st".
18521     if (StringRef("{st}").equals_lower(Constraint)) {
18522       Res.first = X86::ST0;
18523       Res.second = &X86::RFP80RegClass;
18524       return Res;
18525     }
18526
18527     // flags -> EFLAGS
18528     if (StringRef("{flags}").equals_lower(Constraint)) {
18529       Res.first = X86::EFLAGS;
18530       Res.second = &X86::CCRRegClass;
18531       return Res;
18532     }
18533
18534     // 'A' means EAX + EDX.
18535     if (Constraint == "A") {
18536       Res.first = X86::EAX;
18537       Res.second = &X86::GR32_ADRegClass;
18538       return Res;
18539     }
18540     return Res;
18541   }
18542
18543   // Otherwise, check to see if this is a register class of the wrong value
18544   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18545   // turn into {ax},{dx}.
18546   if (Res.second->hasType(VT))
18547     return Res;   // Correct type already, nothing to do.
18548
18549   // All of the single-register GCC register classes map their values onto
18550   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18551   // really want an 8-bit or 32-bit register, map to the appropriate register
18552   // class and return the appropriate register.
18553   if (Res.second == &X86::GR16RegClass) {
18554     if (VT == MVT::i8 || VT == MVT::i1) {
18555       unsigned DestReg = 0;
18556       switch (Res.first) {
18557       default: break;
18558       case X86::AX: DestReg = X86::AL; break;
18559       case X86::DX: DestReg = X86::DL; break;
18560       case X86::CX: DestReg = X86::CL; break;
18561       case X86::BX: DestReg = X86::BL; break;
18562       }
18563       if (DestReg) {
18564         Res.first = DestReg;
18565         Res.second = &X86::GR8RegClass;
18566       }
18567     } else if (VT == MVT::i32 || VT == MVT::f32) {
18568       unsigned DestReg = 0;
18569       switch (Res.first) {
18570       default: break;
18571       case X86::AX: DestReg = X86::EAX; break;
18572       case X86::DX: DestReg = X86::EDX; break;
18573       case X86::CX: DestReg = X86::ECX; break;
18574       case X86::BX: DestReg = X86::EBX; break;
18575       case X86::SI: DestReg = X86::ESI; break;
18576       case X86::DI: DestReg = X86::EDI; break;
18577       case X86::BP: DestReg = X86::EBP; break;
18578       case X86::SP: DestReg = X86::ESP; break;
18579       }
18580       if (DestReg) {
18581         Res.first = DestReg;
18582         Res.second = &X86::GR32RegClass;
18583       }
18584     } else if (VT == MVT::i64 || VT == MVT::f64) {
18585       unsigned DestReg = 0;
18586       switch (Res.first) {
18587       default: break;
18588       case X86::AX: DestReg = X86::RAX; break;
18589       case X86::DX: DestReg = X86::RDX; break;
18590       case X86::CX: DestReg = X86::RCX; break;
18591       case X86::BX: DestReg = X86::RBX; break;
18592       case X86::SI: DestReg = X86::RSI; break;
18593       case X86::DI: DestReg = X86::RDI; break;
18594       case X86::BP: DestReg = X86::RBP; break;
18595       case X86::SP: DestReg = X86::RSP; break;
18596       }
18597       if (DestReg) {
18598         Res.first = DestReg;
18599         Res.second = &X86::GR64RegClass;
18600       }
18601     }
18602   } else if (Res.second == &X86::FR32RegClass ||
18603              Res.second == &X86::FR64RegClass ||
18604              Res.second == &X86::VR128RegClass) {
18605     // Handle references to XMM physical registers that got mapped into the
18606     // wrong class.  This can happen with constraints like {xmm0} where the
18607     // target independent register mapper will just pick the first match it can
18608     // find, ignoring the required type.
18609
18610     if (VT == MVT::f32 || VT == MVT::i32)
18611       Res.second = &X86::FR32RegClass;
18612     else if (VT == MVT::f64 || VT == MVT::i64)
18613       Res.second = &X86::FR64RegClass;
18614     else if (X86::VR128RegClass.hasType(VT))
18615       Res.second = &X86::VR128RegClass;
18616     else if (X86::VR256RegClass.hasType(VT))
18617       Res.second = &X86::VR256RegClass;
18618   }
18619
18620   return Res;
18621 }