X86: Add an SSE2 lowering for 64 bit compares when pcmpgtq (SSE4.2) isn't available.
[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::MEMBARRIER    , MVT::Other, Custom);
530   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
531
532   // On X86 and X86-64, atomic operations are lowered to locked instructions.
533   // Locked instructions, in turn, have implicit fence semantics (all memory
534   // operations are flushed before issuing the locked instruction, and they
535   // are not buffered), so we can fold away the common pattern of
536   // fence-atomic-fence.
537   setShouldFoldAtomicFences(true);
538
539   // Expand certain atomics
540   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
541     MVT VT = IntVTs[i];
542     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
543     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
544     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
545   }
546
547   if (!Subtarget->is64Bit()) {
548     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
549     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
550     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
551     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
552     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
553     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
554     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
555     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
556     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
557     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
558     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
559     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
560   }
561
562   if (Subtarget->hasCmpxchg16b()) {
563     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
564   }
565
566   // FIXME - use subtarget debug flags
567   if (!Subtarget->isTargetDarwin() &&
568       !Subtarget->isTargetELF() &&
569       !Subtarget->isTargetCygMing()) {
570     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
571   }
572
573   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
574   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
575   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
576   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
577   if (Subtarget->is64Bit()) {
578     setExceptionPointerRegister(X86::RAX);
579     setExceptionSelectorRegister(X86::RDX);
580   } else {
581     setExceptionPointerRegister(X86::EAX);
582     setExceptionSelectorRegister(X86::EDX);
583   }
584   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
585   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
586
587   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
588   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
589
590   setOperationAction(ISD::TRAP, MVT::Other, Legal);
591   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
592
593   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
594   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
595   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
596   if (Subtarget->is64Bit()) {
597     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
598     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
599   } else {
600     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
601     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
602   }
603
604   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
605   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
606
607   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
608     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
609                        MVT::i64 : MVT::i32, Custom);
610   else if (TM.Options.EnableSegmentedStacks)
611     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
612                        MVT::i64 : MVT::i32, Custom);
613   else
614     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
615                        MVT::i64 : MVT::i32, Expand);
616
617   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
618     // f32 and f64 use SSE.
619     // Set up the FP register classes.
620     addRegisterClass(MVT::f32, &X86::FR32RegClass);
621     addRegisterClass(MVT::f64, &X86::FR64RegClass);
622
623     // Use ANDPD to simulate FABS.
624     setOperationAction(ISD::FABS , MVT::f64, Custom);
625     setOperationAction(ISD::FABS , MVT::f32, Custom);
626
627     // Use XORP to simulate FNEG.
628     setOperationAction(ISD::FNEG , MVT::f64, Custom);
629     setOperationAction(ISD::FNEG , MVT::f32, Custom);
630
631     // Use ANDPD and ORPD to simulate FCOPYSIGN.
632     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
633     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
634
635     // Lower this to FGETSIGNx86 plus an AND.
636     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
637     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
638
639     // We don't support sin/cos/fmod
640     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
641     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
642     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
643     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
644     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
645     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
646
647     // Expand FP immediates into loads from the stack, except for the special
648     // cases we handle.
649     addLegalFPImmediate(APFloat(+0.0)); // xorpd
650     addLegalFPImmediate(APFloat(+0.0f)); // xorps
651   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
652     // Use SSE for f32, x87 for f64.
653     // Set up the FP register classes.
654     addRegisterClass(MVT::f32, &X86::FR32RegClass);
655     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
656
657     // Use ANDPS to simulate FABS.
658     setOperationAction(ISD::FABS , MVT::f32, Custom);
659
660     // Use XORP to simulate FNEG.
661     setOperationAction(ISD::FNEG , MVT::f32, Custom);
662
663     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
664
665     // Use ANDPS and ORPS to simulate FCOPYSIGN.
666     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
667     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
668
669     // We don't support sin/cos/fmod
670     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
671     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
672     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
673
674     // Special cases we handle for FP constants.
675     addLegalFPImmediate(APFloat(+0.0f)); // xorps
676     addLegalFPImmediate(APFloat(+0.0)); // FLD0
677     addLegalFPImmediate(APFloat(+1.0)); // FLD1
678     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
679     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
680
681     if (!TM.Options.UnsafeFPMath) {
682       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
683       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
684       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
685     }
686   } else if (!TM.Options.UseSoftFloat) {
687     // f32 and f64 in x87.
688     // Set up the FP register classes.
689     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
690     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
691
692     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
693     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
694     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
695     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
696
697     if (!TM.Options.UnsafeFPMath) {
698       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
699       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
700       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
701       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
702       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
703       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
704     }
705     addLegalFPImmediate(APFloat(+0.0)); // FLD0
706     addLegalFPImmediate(APFloat(+1.0)); // FLD1
707     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
708     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
709     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
710     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
711     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
712     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
713   }
714
715   // We don't support FMA.
716   setOperationAction(ISD::FMA, MVT::f64, Expand);
717   setOperationAction(ISD::FMA, MVT::f32, Expand);
718
719   // Long double always uses X87.
720   if (!TM.Options.UseSoftFloat) {
721     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
722     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
723     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
724     {
725       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
726       addLegalFPImmediate(TmpFlt);  // FLD0
727       TmpFlt.changeSign();
728       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
729
730       bool ignored;
731       APFloat TmpFlt2(+1.0);
732       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
733                       &ignored);
734       addLegalFPImmediate(TmpFlt2);  // FLD1
735       TmpFlt2.changeSign();
736       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
737     }
738
739     if (!TM.Options.UnsafeFPMath) {
740       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
741       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
742       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
743     }
744
745     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
746     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
747     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
748     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
749     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
750     setOperationAction(ISD::FMA, MVT::f80, Expand);
751   }
752
753   // Always use a library call for pow.
754   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
755   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
756   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
757
758   setOperationAction(ISD::FLOG, MVT::f80, Expand);
759   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
760   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
761   setOperationAction(ISD::FEXP, MVT::f80, Expand);
762   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
763
764   // First set operation action for all vector types to either promote
765   // (for widening) or expand (for scalarization). Then we will selectively
766   // turn on ones that can be effectively codegen'd.
767   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
768            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
769     MVT VT = (MVT::SimpleValueType)i;
770     setOperationAction(ISD::ADD , VT, Expand);
771     setOperationAction(ISD::SUB , VT, Expand);
772     setOperationAction(ISD::FADD, VT, Expand);
773     setOperationAction(ISD::FNEG, VT, Expand);
774     setOperationAction(ISD::FSUB, VT, Expand);
775     setOperationAction(ISD::MUL , VT, Expand);
776     setOperationAction(ISD::FMUL, VT, Expand);
777     setOperationAction(ISD::SDIV, VT, Expand);
778     setOperationAction(ISD::UDIV, VT, Expand);
779     setOperationAction(ISD::FDIV, VT, Expand);
780     setOperationAction(ISD::SREM, VT, Expand);
781     setOperationAction(ISD::UREM, VT, Expand);
782     setOperationAction(ISD::LOAD, VT, Expand);
783     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
784     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
785     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
786     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
787     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
788     setOperationAction(ISD::FABS, VT, Expand);
789     setOperationAction(ISD::FSIN, VT, Expand);
790     setOperationAction(ISD::FSINCOS, VT, Expand);
791     setOperationAction(ISD::FCOS, VT, Expand);
792     setOperationAction(ISD::FSINCOS, VT, Expand);
793     setOperationAction(ISD::FREM, VT, Expand);
794     setOperationAction(ISD::FMA,  VT, Expand);
795     setOperationAction(ISD::FPOWI, VT, Expand);
796     setOperationAction(ISD::FSQRT, VT, Expand);
797     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
798     setOperationAction(ISD::FFLOOR, VT, Expand);
799     setOperationAction(ISD::FCEIL, VT, Expand);
800     setOperationAction(ISD::FTRUNC, VT, Expand);
801     setOperationAction(ISD::FRINT, VT, Expand);
802     setOperationAction(ISD::FNEARBYINT, VT, Expand);
803     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
804     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
805     setOperationAction(ISD::SDIVREM, VT, Expand);
806     setOperationAction(ISD::UDIVREM, VT, Expand);
807     setOperationAction(ISD::FPOW, VT, Expand);
808     setOperationAction(ISD::CTPOP, VT, Expand);
809     setOperationAction(ISD::CTTZ, VT, Expand);
810     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
811     setOperationAction(ISD::CTLZ, VT, Expand);
812     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
813     setOperationAction(ISD::SHL, VT, Expand);
814     setOperationAction(ISD::SRA, VT, Expand);
815     setOperationAction(ISD::SRL, VT, Expand);
816     setOperationAction(ISD::ROTL, VT, Expand);
817     setOperationAction(ISD::ROTR, VT, Expand);
818     setOperationAction(ISD::BSWAP, VT, Expand);
819     setOperationAction(ISD::SETCC, VT, Expand);
820     setOperationAction(ISD::FLOG, VT, Expand);
821     setOperationAction(ISD::FLOG2, VT, Expand);
822     setOperationAction(ISD::FLOG10, VT, Expand);
823     setOperationAction(ISD::FEXP, VT, Expand);
824     setOperationAction(ISD::FEXP2, VT, Expand);
825     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
826     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
827     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
828     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
829     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
830     setOperationAction(ISD::TRUNCATE, VT, Expand);
831     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
832     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
833     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
834     setOperationAction(ISD::VSELECT, VT, Expand);
835     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
836              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
837       setTruncStoreAction(VT,
838                           (MVT::SimpleValueType)InnerVT, Expand);
839     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
840     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
841     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
842   }
843
844   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
845   // with -msoft-float, disable use of MMX as well.
846   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
847     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
848     // No operations on x86mmx supported, everything uses intrinsics.
849   }
850
851   // MMX-sized vectors (other than x86mmx) are expected to be expanded
852   // into smaller operations.
853   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
854   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
855   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
856   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
857   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
858   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
859   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
860   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
861   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
862   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
863   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
864   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
865   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
866   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
867   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
868   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
869   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
870   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
871   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
872   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
873   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
874   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
875   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
876   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
877   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
878   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
879   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
880   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
881   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
882
883   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
884     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
885
886     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
887     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
888     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
889     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
890     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
891     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
892     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
893     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
894     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
895     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
896     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
897     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
898   }
899
900   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
901     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
902
903     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
904     // registers cannot be used even for integer operations.
905     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
906     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
907     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
908     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
909
910     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
911     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
912     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
913     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
914     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
915     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
916     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
917     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
918     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
919     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
920     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
921     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
922     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
923     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
924     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
925     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
926     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
927     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
928
929     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
930     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
931     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
932     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
933
934     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
935     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
939
940     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
941     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
942       MVT VT = (MVT::SimpleValueType)i;
943       // Do not attempt to custom lower non-power-of-2 vectors
944       if (!isPowerOf2_32(VT.getVectorNumElements()))
945         continue;
946       // Do not attempt to custom lower non-128-bit vectors
947       if (!VT.is128BitVector())
948         continue;
949       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
950       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
951       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
952     }
953
954     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
955     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
956     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
957     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
958     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
959     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
960
961     if (Subtarget->is64Bit()) {
962       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
963       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
964     }
965
966     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
967     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
968       MVT VT = (MVT::SimpleValueType)i;
969
970       // Do not attempt to promote non-128-bit vectors
971       if (!VT.is128BitVector())
972         continue;
973
974       setOperationAction(ISD::AND,    VT, Promote);
975       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
976       setOperationAction(ISD::OR,     VT, Promote);
977       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
978       setOperationAction(ISD::XOR,    VT, Promote);
979       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
980       setOperationAction(ISD::LOAD,   VT, Promote);
981       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
982       setOperationAction(ISD::SELECT, VT, Promote);
983       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
984     }
985
986     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
987
988     // Custom lower v2i64 and v2f64 selects.
989     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
990     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
991     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
992     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
993
994     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
995     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
996
997     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
998     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
999     // As there is no 64-bit GPR available, we need build a special custom
1000     // sequence to convert from v2i32 to v2f32.
1001     if (!Subtarget->is64Bit())
1002       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1003
1004     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1005     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1006
1007     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1008   }
1009
1010   if (Subtarget->hasSSE41()) {
1011     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1012     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1013     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1014     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1015     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1016     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1017     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1018     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1019     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1020     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1021
1022     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1023     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1024     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1025     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1026     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1027     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1028     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1029     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1030     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1031     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1032
1033     // FIXME: Do we need to handle scalar-to-vector here?
1034     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1035
1036     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1037     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1038     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1039     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1040     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1041
1042     // i8 and i16 vectors are custom , because the source register and source
1043     // source memory operand types are not the same width.  f32 vectors are
1044     // custom since the immediate controlling the insert encodes additional
1045     // information.
1046     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1047     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1048     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1049     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1050
1051     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1052     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1053     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1054     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1055
1056     // FIXME: these should be Legal but thats only for the case where
1057     // the index is constant.  For now custom expand to deal with that.
1058     if (Subtarget->is64Bit()) {
1059       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1060       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1061     }
1062   }
1063
1064   if (Subtarget->hasSSE2()) {
1065     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1066     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1067
1068     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1069     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1070
1071     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1072     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1073
1074     // In the customized shift lowering, the legal cases in AVX2 will be
1075     // recognized.
1076     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1077     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1078
1079     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1080     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1081
1082     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1083
1084     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1085     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1086   }
1087
1088   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1089     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1090     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1091     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1092     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1093     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1094     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1095
1096     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1097     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1098     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1099
1100     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1101     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1102     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1103     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1104     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1105     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1106     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1107     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1108     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1109     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1110     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1111     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1112
1113     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1114     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1115     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1116     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1117     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1118     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1119     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1120     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1121     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1122     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1123     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1124     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1125
1126     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1127     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1128
1129     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1130
1131     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1132     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1133     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1134     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1135
1136     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1137     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1138     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1139
1140     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1141
1142     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1143     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1144
1145     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1146     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1147
1148     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1149     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1150
1151     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1152
1153     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1154     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1155     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1156     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1157
1158     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1159     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1160     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1161
1162     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1163     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1164     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1165     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1166
1167     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1168     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1169     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1170     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1171     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1172     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1173
1174     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1175       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1176       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1177       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1178       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1179       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1180       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1181     }
1182
1183     if (Subtarget->hasInt256()) {
1184       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1185       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1186       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1187       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1188
1189       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1190       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1191       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1192       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1193
1194       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1195       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1196       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1197       // Don't lower v32i8 because there is no 128-bit byte mul
1198
1199       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1200
1201       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1202     } else {
1203       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1204       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1205       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1206       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1207
1208       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1209       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1210       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1211       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1212
1213       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1214       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1215       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1216       // Don't lower v32i8 because there is no 128-bit byte mul
1217     }
1218
1219     // In the customized shift lowering, the legal cases in AVX2 will be
1220     // recognized.
1221     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1222     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1223
1224     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1225     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1226
1227     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1228
1229     // Custom lower several nodes for 256-bit types.
1230     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1231              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1232       MVT VT = (MVT::SimpleValueType)i;
1233
1234       // Extract subvector is special because the value type
1235       // (result) is 128-bit but the source is 256-bit wide.
1236       if (VT.is128BitVector())
1237         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1238
1239       // Do not attempt to custom lower other non-256-bit vectors
1240       if (!VT.is256BitVector())
1241         continue;
1242
1243       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1244       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1245       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1246       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1247       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1248       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1249       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1250     }
1251
1252     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1253     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1254       MVT VT = (MVT::SimpleValueType)i;
1255
1256       // Do not attempt to promote non-256-bit vectors
1257       if (!VT.is256BitVector())
1258         continue;
1259
1260       setOperationAction(ISD::AND,    VT, Promote);
1261       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1262       setOperationAction(ISD::OR,     VT, Promote);
1263       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1264       setOperationAction(ISD::XOR,    VT, Promote);
1265       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1266       setOperationAction(ISD::LOAD,   VT, Promote);
1267       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1268       setOperationAction(ISD::SELECT, VT, Promote);
1269       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1270     }
1271   }
1272
1273   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1274   // of this type with custom code.
1275   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1276            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1277     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1278                        Custom);
1279   }
1280
1281   // We want to custom lower some of our intrinsics.
1282   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1283   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1284
1285   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1286   // handle type legalization for these operations here.
1287   //
1288   // FIXME: We really should do custom legalization for addition and
1289   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1290   // than generic legalization for 64-bit multiplication-with-overflow, though.
1291   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1292     // Add/Sub/Mul with overflow operations are custom lowered.
1293     MVT VT = IntVTs[i];
1294     setOperationAction(ISD::SADDO, VT, Custom);
1295     setOperationAction(ISD::UADDO, VT, Custom);
1296     setOperationAction(ISD::SSUBO, VT, Custom);
1297     setOperationAction(ISD::USUBO, VT, Custom);
1298     setOperationAction(ISD::SMULO, VT, Custom);
1299     setOperationAction(ISD::UMULO, VT, Custom);
1300   }
1301
1302   // There are no 8-bit 3-address imul/mul instructions
1303   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1304   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1305
1306   if (!Subtarget->is64Bit()) {
1307     // These libcalls are not available in 32-bit.
1308     setLibcallName(RTLIB::SHL_I128, 0);
1309     setLibcallName(RTLIB::SRL_I128, 0);
1310     setLibcallName(RTLIB::SRA_I128, 0);
1311   }
1312
1313   // Combine sin / cos into one node or libcall if possible.
1314   if (Subtarget->hasSinCos()) {
1315     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1316     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1317     if (Subtarget->isTargetDarwin()) {
1318       // For MacOSX, we don't want to the normal expansion of a libcall to
1319       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1320       // traffic.
1321       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1322       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1323     }
1324   }
1325
1326   // We have target-specific dag combine patterns for the following nodes:
1327   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1328   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1329   setTargetDAGCombine(ISD::VSELECT);
1330   setTargetDAGCombine(ISD::SELECT);
1331   setTargetDAGCombine(ISD::SHL);
1332   setTargetDAGCombine(ISD::SRA);
1333   setTargetDAGCombine(ISD::SRL);
1334   setTargetDAGCombine(ISD::OR);
1335   setTargetDAGCombine(ISD::AND);
1336   setTargetDAGCombine(ISD::ADD);
1337   setTargetDAGCombine(ISD::FADD);
1338   setTargetDAGCombine(ISD::FSUB);
1339   setTargetDAGCombine(ISD::FMA);
1340   setTargetDAGCombine(ISD::SUB);
1341   setTargetDAGCombine(ISD::LOAD);
1342   setTargetDAGCombine(ISD::STORE);
1343   setTargetDAGCombine(ISD::ZERO_EXTEND);
1344   setTargetDAGCombine(ISD::ANY_EXTEND);
1345   setTargetDAGCombine(ISD::SIGN_EXTEND);
1346   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1347   setTargetDAGCombine(ISD::TRUNCATE);
1348   setTargetDAGCombine(ISD::SINT_TO_FP);
1349   setTargetDAGCombine(ISD::SETCC);
1350   if (Subtarget->is64Bit())
1351     setTargetDAGCombine(ISD::MUL);
1352   setTargetDAGCombine(ISD::XOR);
1353
1354   computeRegisterProperties();
1355
1356   // On Darwin, -Os means optimize for size without hurting performance,
1357   // do not reduce the limit.
1358   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1359   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1360   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1361   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1362   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1363   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1364   setPrefLoopAlignment(4); // 2^4 bytes.
1365
1366   // Predictable cmov don't hurt on atom because it's in-order.
1367   PredictableSelectIsExpensive = !Subtarget->isAtom();
1368
1369   setPrefFunctionAlignment(4); // 2^4 bytes.
1370 }
1371
1372 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1373   if (!VT.isVector()) return MVT::i8;
1374   return VT.changeVectorElementTypeToInteger();
1375 }
1376
1377 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1378 /// the desired ByVal argument alignment.
1379 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1380   if (MaxAlign == 16)
1381     return;
1382   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1383     if (VTy->getBitWidth() == 128)
1384       MaxAlign = 16;
1385   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1386     unsigned EltAlign = 0;
1387     getMaxByValAlign(ATy->getElementType(), EltAlign);
1388     if (EltAlign > MaxAlign)
1389       MaxAlign = EltAlign;
1390   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1391     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1392       unsigned EltAlign = 0;
1393       getMaxByValAlign(STy->getElementType(i), EltAlign);
1394       if (EltAlign > MaxAlign)
1395         MaxAlign = EltAlign;
1396       if (MaxAlign == 16)
1397         break;
1398     }
1399   }
1400 }
1401
1402 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1403 /// function arguments in the caller parameter area. For X86, aggregates
1404 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1405 /// are at 4-byte boundaries.
1406 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1407   if (Subtarget->is64Bit()) {
1408     // Max of 8 and alignment of type.
1409     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1410     if (TyAlign > 8)
1411       return TyAlign;
1412     return 8;
1413   }
1414
1415   unsigned Align = 4;
1416   if (Subtarget->hasSSE1())
1417     getMaxByValAlign(Ty, Align);
1418   return Align;
1419 }
1420
1421 /// getOptimalMemOpType - Returns the target specific optimal type for load
1422 /// and store operations as a result of memset, memcpy, and memmove
1423 /// lowering. If DstAlign is zero that means it's safe to destination
1424 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1425 /// means there isn't a need to check it against alignment requirement,
1426 /// probably because the source does not need to be loaded. If 'IsMemset' is
1427 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1428 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1429 /// source is constant so it does not need to be loaded.
1430 /// It returns EVT::Other if the type should be determined using generic
1431 /// target-independent logic.
1432 EVT
1433 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1434                                        unsigned DstAlign, unsigned SrcAlign,
1435                                        bool IsMemset, bool ZeroMemset,
1436                                        bool MemcpyStrSrc,
1437                                        MachineFunction &MF) const {
1438   const Function *F = MF.getFunction();
1439   if ((!IsMemset || ZeroMemset) &&
1440       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1441                                        Attribute::NoImplicitFloat)) {
1442     if (Size >= 16 &&
1443         (Subtarget->isUnalignedMemAccessFast() ||
1444          ((DstAlign == 0 || DstAlign >= 16) &&
1445           (SrcAlign == 0 || SrcAlign >= 16)))) {
1446       if (Size >= 32) {
1447         if (Subtarget->hasInt256())
1448           return MVT::v8i32;
1449         if (Subtarget->hasFp256())
1450           return MVT::v8f32;
1451       }
1452       if (Subtarget->hasSSE2())
1453         return MVT::v4i32;
1454       if (Subtarget->hasSSE1())
1455         return MVT::v4f32;
1456     } else if (!MemcpyStrSrc && Size >= 8 &&
1457                !Subtarget->is64Bit() &&
1458                Subtarget->hasSSE2()) {
1459       // Do not use f64 to lower memcpy if source is string constant. It's
1460       // better to use i32 to avoid the loads.
1461       return MVT::f64;
1462     }
1463   }
1464   if (Subtarget->is64Bit() && Size >= 8)
1465     return MVT::i64;
1466   return MVT::i32;
1467 }
1468
1469 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1470   if (VT == MVT::f32)
1471     return X86ScalarSSEf32;
1472   else if (VT == MVT::f64)
1473     return X86ScalarSSEf64;
1474   return true;
1475 }
1476
1477 bool
1478 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1479   if (Fast)
1480     *Fast = Subtarget->isUnalignedMemAccessFast();
1481   return true;
1482 }
1483
1484 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1485 /// current function.  The returned value is a member of the
1486 /// MachineJumpTableInfo::JTEntryKind enum.
1487 unsigned X86TargetLowering::getJumpTableEncoding() const {
1488   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1489   // symbol.
1490   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1491       Subtarget->isPICStyleGOT())
1492     return MachineJumpTableInfo::EK_Custom32;
1493
1494   // Otherwise, use the normal jump table encoding heuristics.
1495   return TargetLowering::getJumpTableEncoding();
1496 }
1497
1498 const MCExpr *
1499 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1500                                              const MachineBasicBlock *MBB,
1501                                              unsigned uid,MCContext &Ctx) const{
1502   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1503          Subtarget->isPICStyleGOT());
1504   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1505   // entries.
1506   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1507                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1508 }
1509
1510 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1511 /// jumptable.
1512 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1513                                                     SelectionDAG &DAG) const {
1514   if (!Subtarget->is64Bit())
1515     // This doesn't have DebugLoc associated with it, but is not really the
1516     // same as a Register.
1517     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1518   return Table;
1519 }
1520
1521 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1522 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1523 /// MCExpr.
1524 const MCExpr *X86TargetLowering::
1525 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1526                              MCContext &Ctx) const {
1527   // X86-64 uses RIP relative addressing based on the jump table label.
1528   if (Subtarget->isPICStyleRIPRel())
1529     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1530
1531   // Otherwise, the reference is relative to the PIC base.
1532   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1533 }
1534
1535 // FIXME: Why this routine is here? Move to RegInfo!
1536 std::pair<const TargetRegisterClass*, uint8_t>
1537 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1538   const TargetRegisterClass *RRC = 0;
1539   uint8_t Cost = 1;
1540   switch (VT.SimpleTy) {
1541   default:
1542     return TargetLowering::findRepresentativeClass(VT);
1543   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1544     RRC = Subtarget->is64Bit() ?
1545       (const TargetRegisterClass*)&X86::GR64RegClass :
1546       (const TargetRegisterClass*)&X86::GR32RegClass;
1547     break;
1548   case MVT::x86mmx:
1549     RRC = &X86::VR64RegClass;
1550     break;
1551   case MVT::f32: case MVT::f64:
1552   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1553   case MVT::v4f32: case MVT::v2f64:
1554   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1555   case MVT::v4f64:
1556     RRC = &X86::VR128RegClass;
1557     break;
1558   }
1559   return std::make_pair(RRC, Cost);
1560 }
1561
1562 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1563                                                unsigned &Offset) const {
1564   if (!Subtarget->isTargetLinux())
1565     return false;
1566
1567   if (Subtarget->is64Bit()) {
1568     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1569     Offset = 0x28;
1570     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1571       AddressSpace = 256;
1572     else
1573       AddressSpace = 257;
1574   } else {
1575     // %gs:0x14 on i386
1576     Offset = 0x14;
1577     AddressSpace = 256;
1578   }
1579   return true;
1580 }
1581
1582 //===----------------------------------------------------------------------===//
1583 //               Return Value Calling Convention Implementation
1584 //===----------------------------------------------------------------------===//
1585
1586 #include "X86GenCallingConv.inc"
1587
1588 bool
1589 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1590                                   MachineFunction &MF, bool isVarArg,
1591                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1592                         LLVMContext &Context) const {
1593   SmallVector<CCValAssign, 16> RVLocs;
1594   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1595                  RVLocs, Context);
1596   return CCInfo.CheckReturn(Outs, RetCC_X86);
1597 }
1598
1599 SDValue
1600 X86TargetLowering::LowerReturn(SDValue Chain,
1601                                CallingConv::ID CallConv, bool isVarArg,
1602                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1603                                const SmallVectorImpl<SDValue> &OutVals,
1604                                DebugLoc dl, SelectionDAG &DAG) const {
1605   MachineFunction &MF = DAG.getMachineFunction();
1606   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1607
1608   SmallVector<CCValAssign, 16> RVLocs;
1609   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1610                  RVLocs, *DAG.getContext());
1611   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1612
1613   SDValue Flag;
1614   SmallVector<SDValue, 6> RetOps;
1615   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1616   // Operand #1 = Bytes To Pop
1617   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1618                    MVT::i16));
1619
1620   // Copy the result values into the output registers.
1621   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1622     CCValAssign &VA = RVLocs[i];
1623     assert(VA.isRegLoc() && "Can only return in registers!");
1624     SDValue ValToCopy = OutVals[i];
1625     EVT ValVT = ValToCopy.getValueType();
1626
1627     // Promote values to the appropriate types
1628     if (VA.getLocInfo() == CCValAssign::SExt)
1629       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1630     else if (VA.getLocInfo() == CCValAssign::ZExt)
1631       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1632     else if (VA.getLocInfo() == CCValAssign::AExt)
1633       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1634     else if (VA.getLocInfo() == CCValAssign::BCvt)
1635       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1636
1637     // If this is x86-64, and we disabled SSE, we can't return FP values,
1638     // or SSE or MMX vectors.
1639     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1640          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1641           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1642       report_fatal_error("SSE register return with SSE disabled");
1643     }
1644     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1645     // llvm-gcc has never done it right and no one has noticed, so this
1646     // should be OK for now.
1647     if (ValVT == MVT::f64 &&
1648         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1649       report_fatal_error("SSE2 register return with SSE2 disabled");
1650
1651     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1652     // the RET instruction and handled by the FP Stackifier.
1653     if (VA.getLocReg() == X86::ST0 ||
1654         VA.getLocReg() == X86::ST1) {
1655       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1656       // change the value to the FP stack register class.
1657       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1658         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1659       RetOps.push_back(ValToCopy);
1660       // Don't emit a copytoreg.
1661       continue;
1662     }
1663
1664     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1665     // which is returned in RAX / RDX.
1666     if (Subtarget->is64Bit()) {
1667       if (ValVT == MVT::x86mmx) {
1668         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1669           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1670           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1671                                   ValToCopy);
1672           // If we don't have SSE2 available, convert to v4f32 so the generated
1673           // register is legal.
1674           if (!Subtarget->hasSSE2())
1675             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1676         }
1677       }
1678     }
1679
1680     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1681     Flag = Chain.getValue(1);
1682     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1683   }
1684
1685   // The x86-64 ABIs require that for returning structs by value we copy
1686   // the sret argument into %rax/%eax (depending on ABI) for the return.
1687   // Win32 requires us to put the sret argument to %eax as well.
1688   // We saved the argument into a virtual register in the entry block,
1689   // so now we copy the value out and into %rax/%eax.
1690   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1691       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1692     MachineFunction &MF = DAG.getMachineFunction();
1693     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1694     unsigned Reg = FuncInfo->getSRetReturnReg();
1695     assert(Reg &&
1696            "SRetReturnReg should have been set in LowerFormalArguments().");
1697     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1698
1699     unsigned RetValReg
1700         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1701           X86::RAX : X86::EAX;
1702     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1703     Flag = Chain.getValue(1);
1704
1705     // RAX/EAX now acts like a return value.
1706     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1707   }
1708
1709   RetOps[0] = Chain;  // Update chain.
1710
1711   // Add the flag if we have it.
1712   if (Flag.getNode())
1713     RetOps.push_back(Flag);
1714
1715   return DAG.getNode(X86ISD::RET_FLAG, dl,
1716                      MVT::Other, &RetOps[0], RetOps.size());
1717 }
1718
1719 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1720   if (N->getNumValues() != 1)
1721     return false;
1722   if (!N->hasNUsesOfValue(1, 0))
1723     return false;
1724
1725   SDValue TCChain = Chain;
1726   SDNode *Copy = *N->use_begin();
1727   if (Copy->getOpcode() == ISD::CopyToReg) {
1728     // If the copy has a glue operand, we conservatively assume it isn't safe to
1729     // perform a tail call.
1730     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1731       return false;
1732     TCChain = Copy->getOperand(0);
1733   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1734     return false;
1735
1736   bool HasRet = false;
1737   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1738        UI != UE; ++UI) {
1739     if (UI->getOpcode() != X86ISD::RET_FLAG)
1740       return false;
1741     HasRet = true;
1742   }
1743
1744   if (!HasRet)
1745     return false;
1746
1747   Chain = TCChain;
1748   return true;
1749 }
1750
1751 MVT
1752 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1753                                             ISD::NodeType ExtendKind) const {
1754   MVT ReturnMVT;
1755   // TODO: Is this also valid on 32-bit?
1756   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1757     ReturnMVT = MVT::i8;
1758   else
1759     ReturnMVT = MVT::i32;
1760
1761   MVT MinVT = getRegisterType(ReturnMVT);
1762   return VT.bitsLT(MinVT) ? MinVT : VT;
1763 }
1764
1765 /// LowerCallResult - Lower the result values of a call into the
1766 /// appropriate copies out of appropriate physical registers.
1767 ///
1768 SDValue
1769 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1770                                    CallingConv::ID CallConv, bool isVarArg,
1771                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1772                                    DebugLoc dl, SelectionDAG &DAG,
1773                                    SmallVectorImpl<SDValue> &InVals) const {
1774
1775   // Assign locations to each value returned by this call.
1776   SmallVector<CCValAssign, 16> RVLocs;
1777   bool Is64Bit = Subtarget->is64Bit();
1778   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1779                  getTargetMachine(), RVLocs, *DAG.getContext());
1780   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1781
1782   // Copy all of the result registers out of their specified physreg.
1783   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1784     CCValAssign &VA = RVLocs[i];
1785     EVT CopyVT = VA.getValVT();
1786
1787     // If this is x86-64, and we disabled SSE, we can't return FP values
1788     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1789         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1790       report_fatal_error("SSE register return with SSE disabled");
1791     }
1792
1793     SDValue Val;
1794
1795     // If this is a call to a function that returns an fp value on the floating
1796     // point stack, we must guarantee the value is popped from the stack, so
1797     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1798     // if the return value is not used. We use the FpPOP_RETVAL instruction
1799     // instead.
1800     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1801       // If we prefer to use the value in xmm registers, copy it out as f80 and
1802       // use a truncate to move it from fp stack reg to xmm reg.
1803       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1804       SDValue Ops[] = { Chain, InFlag };
1805       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1806                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1807       Val = Chain.getValue(0);
1808
1809       // Round the f80 to the right size, which also moves it to the appropriate
1810       // xmm register.
1811       if (CopyVT != VA.getValVT())
1812         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1813                           // This truncation won't change the value.
1814                           DAG.getIntPtrConstant(1));
1815     } else {
1816       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1817                                  CopyVT, InFlag).getValue(1);
1818       Val = Chain.getValue(0);
1819     }
1820     InFlag = Chain.getValue(2);
1821     InVals.push_back(Val);
1822   }
1823
1824   return Chain;
1825 }
1826
1827 //===----------------------------------------------------------------------===//
1828 //                C & StdCall & Fast Calling Convention implementation
1829 //===----------------------------------------------------------------------===//
1830 //  StdCall calling convention seems to be standard for many Windows' API
1831 //  routines and around. It differs from C calling convention just a little:
1832 //  callee should clean up the stack, not caller. Symbols should be also
1833 //  decorated in some fancy way :) It doesn't support any vector arguments.
1834 //  For info on fast calling convention see Fast Calling Convention (tail call)
1835 //  implementation LowerX86_32FastCCCallTo.
1836
1837 /// CallIsStructReturn - Determines whether a call uses struct return
1838 /// semantics.
1839 enum StructReturnType {
1840   NotStructReturn,
1841   RegStructReturn,
1842   StackStructReturn
1843 };
1844 static StructReturnType
1845 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1846   if (Outs.empty())
1847     return NotStructReturn;
1848
1849   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1850   if (!Flags.isSRet())
1851     return NotStructReturn;
1852   if (Flags.isInReg())
1853     return RegStructReturn;
1854   return StackStructReturn;
1855 }
1856
1857 /// ArgsAreStructReturn - Determines whether a function uses struct
1858 /// return semantics.
1859 static StructReturnType
1860 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1861   if (Ins.empty())
1862     return NotStructReturn;
1863
1864   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1865   if (!Flags.isSRet())
1866     return NotStructReturn;
1867   if (Flags.isInReg())
1868     return RegStructReturn;
1869   return StackStructReturn;
1870 }
1871
1872 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1873 /// by "Src" to address "Dst" with size and alignment information specified by
1874 /// the specific parameter attribute. The copy will be passed as a byval
1875 /// function parameter.
1876 static SDValue
1877 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1878                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1879                           DebugLoc dl) {
1880   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1881
1882   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1883                        /*isVolatile*/false, /*AlwaysInline=*/true,
1884                        MachinePointerInfo(), MachinePointerInfo());
1885 }
1886
1887 /// IsTailCallConvention - Return true if the calling convention is one that
1888 /// supports tail call optimization.
1889 static bool IsTailCallConvention(CallingConv::ID CC) {
1890   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1891           CC == CallingConv::HiPE);
1892 }
1893
1894 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1895   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1896     return false;
1897
1898   CallSite CS(CI);
1899   CallingConv::ID CalleeCC = CS.getCallingConv();
1900   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1901     return false;
1902
1903   return true;
1904 }
1905
1906 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1907 /// a tailcall target by changing its ABI.
1908 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1909                                    bool GuaranteedTailCallOpt) {
1910   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1911 }
1912
1913 SDValue
1914 X86TargetLowering::LowerMemArgument(SDValue Chain,
1915                                     CallingConv::ID CallConv,
1916                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1917                                     DebugLoc dl, SelectionDAG &DAG,
1918                                     const CCValAssign &VA,
1919                                     MachineFrameInfo *MFI,
1920                                     unsigned i) const {
1921   // Create the nodes corresponding to a load from this parameter slot.
1922   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1923   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1924                               getTargetMachine().Options.GuaranteedTailCallOpt);
1925   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1926   EVT ValVT;
1927
1928   // If value is passed by pointer we have address passed instead of the value
1929   // itself.
1930   if (VA.getLocInfo() == CCValAssign::Indirect)
1931     ValVT = VA.getLocVT();
1932   else
1933     ValVT = VA.getValVT();
1934
1935   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1936   // changed with more analysis.
1937   // In case of tail call optimization mark all arguments mutable. Since they
1938   // could be overwritten by lowering of arguments in case of a tail call.
1939   if (Flags.isByVal()) {
1940     unsigned Bytes = Flags.getByValSize();
1941     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1942     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1943     return DAG.getFrameIndex(FI, getPointerTy());
1944   } else {
1945     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1946                                     VA.getLocMemOffset(), isImmutable);
1947     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1948     return DAG.getLoad(ValVT, dl, Chain, FIN,
1949                        MachinePointerInfo::getFixedStack(FI),
1950                        false, false, false, 0);
1951   }
1952 }
1953
1954 SDValue
1955 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1956                                         CallingConv::ID CallConv,
1957                                         bool isVarArg,
1958                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1959                                         DebugLoc dl,
1960                                         SelectionDAG &DAG,
1961                                         SmallVectorImpl<SDValue> &InVals)
1962                                           const {
1963   MachineFunction &MF = DAG.getMachineFunction();
1964   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1965
1966   const Function* Fn = MF.getFunction();
1967   if (Fn->hasExternalLinkage() &&
1968       Subtarget->isTargetCygMing() &&
1969       Fn->getName() == "main")
1970     FuncInfo->setForceFramePointer(true);
1971
1972   MachineFrameInfo *MFI = MF.getFrameInfo();
1973   bool Is64Bit = Subtarget->is64Bit();
1974   bool IsWindows = Subtarget->isTargetWindows();
1975   bool IsWin64 = Subtarget->isTargetWin64();
1976
1977   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1978          "Var args not supported with calling convention fastcc, ghc or hipe");
1979
1980   // Assign locations to all of the incoming arguments.
1981   SmallVector<CCValAssign, 16> ArgLocs;
1982   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1983                  ArgLocs, *DAG.getContext());
1984
1985   // Allocate shadow area for Win64
1986   if (IsWin64) {
1987     CCInfo.AllocateStack(32, 8);
1988   }
1989
1990   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1991
1992   unsigned LastVal = ~0U;
1993   SDValue ArgValue;
1994   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1995     CCValAssign &VA = ArgLocs[i];
1996     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1997     // places.
1998     assert(VA.getValNo() != LastVal &&
1999            "Don't support value assigned to multiple locs yet");
2000     (void)LastVal;
2001     LastVal = VA.getValNo();
2002
2003     if (VA.isRegLoc()) {
2004       EVT RegVT = VA.getLocVT();
2005       const TargetRegisterClass *RC;
2006       if (RegVT == MVT::i32)
2007         RC = &X86::GR32RegClass;
2008       else if (Is64Bit && RegVT == MVT::i64)
2009         RC = &X86::GR64RegClass;
2010       else if (RegVT == MVT::f32)
2011         RC = &X86::FR32RegClass;
2012       else if (RegVT == MVT::f64)
2013         RC = &X86::FR64RegClass;
2014       else if (RegVT.is256BitVector())
2015         RC = &X86::VR256RegClass;
2016       else if (RegVT.is128BitVector())
2017         RC = &X86::VR128RegClass;
2018       else if (RegVT == MVT::x86mmx)
2019         RC = &X86::VR64RegClass;
2020       else
2021         llvm_unreachable("Unknown argument type!");
2022
2023       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2024       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2025
2026       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2027       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2028       // right size.
2029       if (VA.getLocInfo() == CCValAssign::SExt)
2030         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2031                                DAG.getValueType(VA.getValVT()));
2032       else if (VA.getLocInfo() == CCValAssign::ZExt)
2033         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2034                                DAG.getValueType(VA.getValVT()));
2035       else if (VA.getLocInfo() == CCValAssign::BCvt)
2036         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2037
2038       if (VA.isExtInLoc()) {
2039         // Handle MMX values passed in XMM regs.
2040         if (RegVT.isVector())
2041           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2042         else
2043           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2044       }
2045     } else {
2046       assert(VA.isMemLoc());
2047       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2048     }
2049
2050     // If value is passed via pointer - do a load.
2051     if (VA.getLocInfo() == CCValAssign::Indirect)
2052       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2053                              MachinePointerInfo(), false, false, false, 0);
2054
2055     InVals.push_back(ArgValue);
2056   }
2057
2058   // The x86-64 ABIs require that for returning structs by value we copy
2059   // the sret argument into %rax/%eax (depending on ABI) for the return.
2060   // Win32 requires us to put the sret argument to %eax as well.
2061   // Save the argument into a virtual register so that we can access it
2062   // from the return points.
2063   if (MF.getFunction()->hasStructRetAttr() &&
2064       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2065     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2066     unsigned Reg = FuncInfo->getSRetReturnReg();
2067     if (!Reg) {
2068       MVT PtrTy = getPointerTy();
2069       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2070       FuncInfo->setSRetReturnReg(Reg);
2071     }
2072     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2073     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2074   }
2075
2076   unsigned StackSize = CCInfo.getNextStackOffset();
2077   // Align stack specially for tail calls.
2078   if (FuncIsMadeTailCallSafe(CallConv,
2079                              MF.getTarget().Options.GuaranteedTailCallOpt))
2080     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2081
2082   // If the function takes variable number of arguments, make a frame index for
2083   // the start of the first vararg value... for expansion of llvm.va_start.
2084   if (isVarArg) {
2085     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2086                     CallConv != CallingConv::X86_ThisCall)) {
2087       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2088     }
2089     if (Is64Bit) {
2090       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2091
2092       // FIXME: We should really autogenerate these arrays
2093       static const uint16_t GPR64ArgRegsWin64[] = {
2094         X86::RCX, X86::RDX, X86::R8,  X86::R9
2095       };
2096       static const uint16_t GPR64ArgRegs64Bit[] = {
2097         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2098       };
2099       static const uint16_t XMMArgRegs64Bit[] = {
2100         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2101         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2102       };
2103       const uint16_t *GPR64ArgRegs;
2104       unsigned NumXMMRegs = 0;
2105
2106       if (IsWin64) {
2107         // The XMM registers which might contain var arg parameters are shadowed
2108         // in their paired GPR.  So we only need to save the GPR to their home
2109         // slots.
2110         TotalNumIntRegs = 4;
2111         GPR64ArgRegs = GPR64ArgRegsWin64;
2112       } else {
2113         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2114         GPR64ArgRegs = GPR64ArgRegs64Bit;
2115
2116         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2117                                                 TotalNumXMMRegs);
2118       }
2119       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2120                                                        TotalNumIntRegs);
2121
2122       bool NoImplicitFloatOps = Fn->getAttributes().
2123         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2124       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2125              "SSE register cannot be used when SSE is disabled!");
2126       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2127                NoImplicitFloatOps) &&
2128              "SSE register cannot be used when SSE is disabled!");
2129       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2130           !Subtarget->hasSSE1())
2131         // Kernel mode asks for SSE to be disabled, so don't push them
2132         // on the stack.
2133         TotalNumXMMRegs = 0;
2134
2135       if (IsWin64) {
2136         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2137         // Get to the caller-allocated home save location.  Add 8 to account
2138         // for the return address.
2139         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2140         FuncInfo->setRegSaveFrameIndex(
2141           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2142         // Fixup to set vararg frame on shadow area (4 x i64).
2143         if (NumIntRegs < 4)
2144           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2145       } else {
2146         // For X86-64, if there are vararg parameters that are passed via
2147         // registers, then we must store them to their spots on the stack so
2148         // they may be loaded by deferencing the result of va_next.
2149         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2150         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2151         FuncInfo->setRegSaveFrameIndex(
2152           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2153                                false));
2154       }
2155
2156       // Store the integer parameter registers.
2157       SmallVector<SDValue, 8> MemOps;
2158       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2159                                         getPointerTy());
2160       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2161       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2162         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2163                                   DAG.getIntPtrConstant(Offset));
2164         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2165                                      &X86::GR64RegClass);
2166         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2167         SDValue Store =
2168           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2169                        MachinePointerInfo::getFixedStack(
2170                          FuncInfo->getRegSaveFrameIndex(), Offset),
2171                        false, false, 0);
2172         MemOps.push_back(Store);
2173         Offset += 8;
2174       }
2175
2176       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2177         // Now store the XMM (fp + vector) parameter registers.
2178         SmallVector<SDValue, 11> SaveXMMOps;
2179         SaveXMMOps.push_back(Chain);
2180
2181         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2182         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2183         SaveXMMOps.push_back(ALVal);
2184
2185         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2186                                FuncInfo->getRegSaveFrameIndex()));
2187         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2188                                FuncInfo->getVarArgsFPOffset()));
2189
2190         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2191           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2192                                        &X86::VR128RegClass);
2193           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2194           SaveXMMOps.push_back(Val);
2195         }
2196         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2197                                      MVT::Other,
2198                                      &SaveXMMOps[0], SaveXMMOps.size()));
2199       }
2200
2201       if (!MemOps.empty())
2202         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2203                             &MemOps[0], MemOps.size());
2204     }
2205   }
2206
2207   // Some CCs need callee pop.
2208   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2209                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2210     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2211   } else {
2212     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2213     // If this is an sret function, the return should pop the hidden pointer.
2214     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2215         argsAreStructReturn(Ins) == StackStructReturn)
2216       FuncInfo->setBytesToPopOnReturn(4);
2217   }
2218
2219   if (!Is64Bit) {
2220     // RegSaveFrameIndex is X86-64 only.
2221     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2222     if (CallConv == CallingConv::X86_FastCall ||
2223         CallConv == CallingConv::X86_ThisCall)
2224       // fastcc functions can't have varargs.
2225       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2226   }
2227
2228   FuncInfo->setArgumentStackSize(StackSize);
2229
2230   return Chain;
2231 }
2232
2233 SDValue
2234 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2235                                     SDValue StackPtr, SDValue Arg,
2236                                     DebugLoc dl, SelectionDAG &DAG,
2237                                     const CCValAssign &VA,
2238                                     ISD::ArgFlagsTy Flags) const {
2239   unsigned LocMemOffset = VA.getLocMemOffset();
2240   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2241   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2242   if (Flags.isByVal())
2243     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2244
2245   return DAG.getStore(Chain, dl, Arg, PtrOff,
2246                       MachinePointerInfo::getStack(LocMemOffset),
2247                       false, false, 0);
2248 }
2249
2250 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2251 /// optimization is performed and it is required.
2252 SDValue
2253 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2254                                            SDValue &OutRetAddr, SDValue Chain,
2255                                            bool IsTailCall, bool Is64Bit,
2256                                            int FPDiff, DebugLoc dl) const {
2257   // Adjust the Return address stack slot.
2258   EVT VT = getPointerTy();
2259   OutRetAddr = getReturnAddressFrameIndex(DAG);
2260
2261   // Load the "old" Return address.
2262   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2263                            false, false, false, 0);
2264   return SDValue(OutRetAddr.getNode(), 1);
2265 }
2266
2267 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2268 /// optimization is performed and it is required (FPDiff!=0).
2269 static SDValue
2270 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2271                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2272                          unsigned SlotSize, int FPDiff, DebugLoc dl) {
2273   // Store the return address to the appropriate stack slot.
2274   if (!FPDiff) return Chain;
2275   // Calculate the new stack slot for the return address.
2276   int NewReturnAddrFI =
2277     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2278   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2279   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2280                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2281                        false, false, 0);
2282   return Chain;
2283 }
2284
2285 SDValue
2286 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2287                              SmallVectorImpl<SDValue> &InVals) const {
2288   SelectionDAG &DAG                     = CLI.DAG;
2289   DebugLoc &dl                          = CLI.DL;
2290   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2291   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2292   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2293   SDValue Chain                         = CLI.Chain;
2294   SDValue Callee                        = CLI.Callee;
2295   CallingConv::ID CallConv              = CLI.CallConv;
2296   bool &isTailCall                      = CLI.IsTailCall;
2297   bool isVarArg                         = CLI.IsVarArg;
2298
2299   MachineFunction &MF = DAG.getMachineFunction();
2300   bool Is64Bit        = Subtarget->is64Bit();
2301   bool IsWin64        = Subtarget->isTargetWin64();
2302   bool IsWindows      = Subtarget->isTargetWindows();
2303   StructReturnType SR = callIsStructReturn(Outs);
2304   bool IsSibcall      = false;
2305
2306   if (MF.getTarget().Options.DisableTailCalls)
2307     isTailCall = false;
2308
2309   if (isTailCall) {
2310     // Check if it's really possible to do a tail call.
2311     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2312                     isVarArg, SR != NotStructReturn,
2313                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2314                     Outs, OutVals, Ins, DAG);
2315
2316     // Sibcalls are automatically detected tailcalls which do not require
2317     // ABI changes.
2318     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2319       IsSibcall = true;
2320
2321     if (isTailCall)
2322       ++NumTailCalls;
2323   }
2324
2325   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2326          "Var args not supported with calling convention fastcc, ghc or hipe");
2327
2328   // Analyze operands of the call, assigning locations to each operand.
2329   SmallVector<CCValAssign, 16> ArgLocs;
2330   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2331                  ArgLocs, *DAG.getContext());
2332
2333   // Allocate shadow area for Win64
2334   if (IsWin64) {
2335     CCInfo.AllocateStack(32, 8);
2336   }
2337
2338   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2339
2340   // Get a count of how many bytes are to be pushed on the stack.
2341   unsigned NumBytes = CCInfo.getNextStackOffset();
2342   if (IsSibcall)
2343     // This is a sibcall. The memory operands are available in caller's
2344     // own caller's stack.
2345     NumBytes = 0;
2346   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2347            IsTailCallConvention(CallConv))
2348     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2349
2350   int FPDiff = 0;
2351   if (isTailCall && !IsSibcall) {
2352     // Lower arguments at fp - stackoffset + fpdiff.
2353     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2354     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2355
2356     FPDiff = NumBytesCallerPushed - NumBytes;
2357
2358     // Set the delta of movement of the returnaddr stackslot.
2359     // But only set if delta is greater than previous delta.
2360     if (FPDiff < X86Info->getTCReturnAddrDelta())
2361       X86Info->setTCReturnAddrDelta(FPDiff);
2362   }
2363
2364   if (!IsSibcall)
2365     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2366
2367   SDValue RetAddrFrIdx;
2368   // Load return address for tail calls.
2369   if (isTailCall && FPDiff)
2370     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2371                                     Is64Bit, FPDiff, dl);
2372
2373   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2374   SmallVector<SDValue, 8> MemOpChains;
2375   SDValue StackPtr;
2376
2377   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2378   // of tail call optimization arguments are handle later.
2379   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2380     CCValAssign &VA = ArgLocs[i];
2381     EVT RegVT = VA.getLocVT();
2382     SDValue Arg = OutVals[i];
2383     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2384     bool isByVal = Flags.isByVal();
2385
2386     // Promote the value if needed.
2387     switch (VA.getLocInfo()) {
2388     default: llvm_unreachable("Unknown loc info!");
2389     case CCValAssign::Full: break;
2390     case CCValAssign::SExt:
2391       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2392       break;
2393     case CCValAssign::ZExt:
2394       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2395       break;
2396     case CCValAssign::AExt:
2397       if (RegVT.is128BitVector()) {
2398         // Special case: passing MMX values in XMM registers.
2399         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2400         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2401         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2402       } else
2403         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2404       break;
2405     case CCValAssign::BCvt:
2406       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2407       break;
2408     case CCValAssign::Indirect: {
2409       // Store the argument.
2410       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2411       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2412       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2413                            MachinePointerInfo::getFixedStack(FI),
2414                            false, false, 0);
2415       Arg = SpillSlot;
2416       break;
2417     }
2418     }
2419
2420     if (VA.isRegLoc()) {
2421       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2422       if (isVarArg && IsWin64) {
2423         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2424         // shadow reg if callee is a varargs function.
2425         unsigned ShadowReg = 0;
2426         switch (VA.getLocReg()) {
2427         case X86::XMM0: ShadowReg = X86::RCX; break;
2428         case X86::XMM1: ShadowReg = X86::RDX; break;
2429         case X86::XMM2: ShadowReg = X86::R8; break;
2430         case X86::XMM3: ShadowReg = X86::R9; break;
2431         }
2432         if (ShadowReg)
2433           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2434       }
2435     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2436       assert(VA.isMemLoc());
2437       if (StackPtr.getNode() == 0)
2438         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2439                                       getPointerTy());
2440       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2441                                              dl, DAG, VA, Flags));
2442     }
2443   }
2444
2445   if (!MemOpChains.empty())
2446     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2447                         &MemOpChains[0], MemOpChains.size());
2448
2449   if (Subtarget->isPICStyleGOT()) {
2450     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2451     // GOT pointer.
2452     if (!isTailCall) {
2453       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2454                DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy())));
2455     } else {
2456       // If we are tail calling and generating PIC/GOT style code load the
2457       // address of the callee into ECX. The value in ecx is used as target of
2458       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2459       // for tail calls on PIC/GOT architectures. Normally we would just put the
2460       // address of GOT into ebx and then call target@PLT. But for tail calls
2461       // ebx would be restored (since ebx is callee saved) before jumping to the
2462       // target@PLT.
2463
2464       // Note: The actual moving to ECX is done further down.
2465       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2466       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2467           !G->getGlobal()->hasProtectedVisibility())
2468         Callee = LowerGlobalAddress(Callee, DAG);
2469       else if (isa<ExternalSymbolSDNode>(Callee))
2470         Callee = LowerExternalSymbol(Callee, DAG);
2471     }
2472   }
2473
2474   if (Is64Bit && isVarArg && !IsWin64) {
2475     // From AMD64 ABI document:
2476     // For calls that may call functions that use varargs or stdargs
2477     // (prototype-less calls or calls to functions containing ellipsis (...) in
2478     // the declaration) %al is used as hidden argument to specify the number
2479     // of SSE registers used. The contents of %al do not need to match exactly
2480     // the number of registers, but must be an ubound on the number of SSE
2481     // registers used and is in the range 0 - 8 inclusive.
2482
2483     // Count the number of XMM registers allocated.
2484     static const uint16_t XMMArgRegs[] = {
2485       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2486       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2487     };
2488     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2489     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2490            && "SSE registers cannot be used when SSE is disabled");
2491
2492     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2493                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2494   }
2495
2496   // For tail calls lower the arguments to the 'real' stack slot.
2497   if (isTailCall) {
2498     // Force all the incoming stack arguments to be loaded from the stack
2499     // before any new outgoing arguments are stored to the stack, because the
2500     // outgoing stack slots may alias the incoming argument stack slots, and
2501     // the alias isn't otherwise explicit. This is slightly more conservative
2502     // than necessary, because it means that each store effectively depends
2503     // on every argument instead of just those arguments it would clobber.
2504     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2505
2506     SmallVector<SDValue, 8> MemOpChains2;
2507     SDValue FIN;
2508     int FI = 0;
2509     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2510       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2511         CCValAssign &VA = ArgLocs[i];
2512         if (VA.isRegLoc())
2513           continue;
2514         assert(VA.isMemLoc());
2515         SDValue Arg = OutVals[i];
2516         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2517         // Create frame index.
2518         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2519         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2520         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2521         FIN = DAG.getFrameIndex(FI, getPointerTy());
2522
2523         if (Flags.isByVal()) {
2524           // Copy relative to framepointer.
2525           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2526           if (StackPtr.getNode() == 0)
2527             StackPtr = DAG.getCopyFromReg(Chain, dl,
2528                                           RegInfo->getStackRegister(),
2529                                           getPointerTy());
2530           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2531
2532           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2533                                                            ArgChain,
2534                                                            Flags, DAG, dl));
2535         } else {
2536           // Store relative to framepointer.
2537           MemOpChains2.push_back(
2538             DAG.getStore(ArgChain, dl, Arg, FIN,
2539                          MachinePointerInfo::getFixedStack(FI),
2540                          false, false, 0));
2541         }
2542       }
2543     }
2544
2545     if (!MemOpChains2.empty())
2546       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2547                           &MemOpChains2[0], MemOpChains2.size());
2548
2549     // Store the return address to the appropriate stack slot.
2550     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2551                                      getPointerTy(), RegInfo->getSlotSize(),
2552                                      FPDiff, dl);
2553   }
2554
2555   // Build a sequence of copy-to-reg nodes chained together with token chain
2556   // and flag operands which copy the outgoing args into registers.
2557   SDValue InFlag;
2558   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2559     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2560                              RegsToPass[i].second, InFlag);
2561     InFlag = Chain.getValue(1);
2562   }
2563
2564   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2565     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2566     // In the 64-bit large code model, we have to make all calls
2567     // through a register, since the call instruction's 32-bit
2568     // pc-relative offset may not be large enough to hold the whole
2569     // address.
2570   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2571     // If the callee is a GlobalAddress node (quite common, every direct call
2572     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2573     // it.
2574
2575     // We should use extra load for direct calls to dllimported functions in
2576     // non-JIT mode.
2577     const GlobalValue *GV = G->getGlobal();
2578     if (!GV->hasDLLImportLinkage()) {
2579       unsigned char OpFlags = 0;
2580       bool ExtraLoad = false;
2581       unsigned WrapperKind = ISD::DELETED_NODE;
2582
2583       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2584       // external symbols most go through the PLT in PIC mode.  If the symbol
2585       // has hidden or protected visibility, or if it is static or local, then
2586       // we don't need to use the PLT - we can directly call it.
2587       if (Subtarget->isTargetELF() &&
2588           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2589           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2590         OpFlags = X86II::MO_PLT;
2591       } else if (Subtarget->isPICStyleStubAny() &&
2592                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2593                  (!Subtarget->getTargetTriple().isMacOSX() ||
2594                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2595         // PC-relative references to external symbols should go through $stub,
2596         // unless we're building with the leopard linker or later, which
2597         // automatically synthesizes these stubs.
2598         OpFlags = X86II::MO_DARWIN_STUB;
2599       } else if (Subtarget->isPICStyleRIPRel() &&
2600                  isa<Function>(GV) &&
2601                  cast<Function>(GV)->getAttributes().
2602                    hasAttribute(AttributeSet::FunctionIndex,
2603                                 Attribute::NonLazyBind)) {
2604         // If the function is marked as non-lazy, generate an indirect call
2605         // which loads from the GOT directly. This avoids runtime overhead
2606         // at the cost of eager binding (and one extra byte of encoding).
2607         OpFlags = X86II::MO_GOTPCREL;
2608         WrapperKind = X86ISD::WrapperRIP;
2609         ExtraLoad = true;
2610       }
2611
2612       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2613                                           G->getOffset(), OpFlags);
2614
2615       // Add a wrapper if needed.
2616       if (WrapperKind != ISD::DELETED_NODE)
2617         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2618       // Add extra indirection if needed.
2619       if (ExtraLoad)
2620         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2621                              MachinePointerInfo::getGOT(),
2622                              false, false, false, 0);
2623     }
2624   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2625     unsigned char OpFlags = 0;
2626
2627     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2628     // external symbols should go through the PLT.
2629     if (Subtarget->isTargetELF() &&
2630         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2631       OpFlags = X86II::MO_PLT;
2632     } else if (Subtarget->isPICStyleStubAny() &&
2633                (!Subtarget->getTargetTriple().isMacOSX() ||
2634                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2635       // PC-relative references to external symbols should go through $stub,
2636       // unless we're building with the leopard linker or later, which
2637       // automatically synthesizes these stubs.
2638       OpFlags = X86II::MO_DARWIN_STUB;
2639     }
2640
2641     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2642                                          OpFlags);
2643   }
2644
2645   // Returns a chain & a flag for retval copy to use.
2646   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2647   SmallVector<SDValue, 8> Ops;
2648
2649   if (!IsSibcall && isTailCall) {
2650     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2651                            DAG.getIntPtrConstant(0, true), InFlag);
2652     InFlag = Chain.getValue(1);
2653   }
2654
2655   Ops.push_back(Chain);
2656   Ops.push_back(Callee);
2657
2658   if (isTailCall)
2659     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2660
2661   // Add argument registers to the end of the list so that they are known live
2662   // into the call.
2663   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2664     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2665                                   RegsToPass[i].second.getValueType()));
2666
2667   // Add a register mask operand representing the call-preserved registers.
2668   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2669   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2670   assert(Mask && "Missing call preserved mask for calling convention");
2671   Ops.push_back(DAG.getRegisterMask(Mask));
2672
2673   if (InFlag.getNode())
2674     Ops.push_back(InFlag);
2675
2676   if (isTailCall) {
2677     // We used to do:
2678     //// If this is the first return lowered for this function, add the regs
2679     //// to the liveout set for the function.
2680     // This isn't right, although it's probably harmless on x86; liveouts
2681     // should be computed from returns not tail calls.  Consider a void
2682     // function making a tail call to a function returning int.
2683     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2684   }
2685
2686   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2687   InFlag = Chain.getValue(1);
2688
2689   // Create the CALLSEQ_END node.
2690   unsigned NumBytesForCalleeToPush;
2691   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2692                        getTargetMachine().Options.GuaranteedTailCallOpt))
2693     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2694   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2695            SR == StackStructReturn)
2696     // If this is a call to a struct-return function, the callee
2697     // pops the hidden struct pointer, so we have to push it back.
2698     // This is common for Darwin/X86, Linux & Mingw32 targets.
2699     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2700     NumBytesForCalleeToPush = 4;
2701   else
2702     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2703
2704   // Returns a flag for retval copy to use.
2705   if (!IsSibcall) {
2706     Chain = DAG.getCALLSEQ_END(Chain,
2707                                DAG.getIntPtrConstant(NumBytes, true),
2708                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2709                                                      true),
2710                                InFlag);
2711     InFlag = Chain.getValue(1);
2712   }
2713
2714   // Handle result values, copying them out of physregs into vregs that we
2715   // return.
2716   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2717                          Ins, dl, DAG, InVals);
2718 }
2719
2720 //===----------------------------------------------------------------------===//
2721 //                Fast Calling Convention (tail call) implementation
2722 //===----------------------------------------------------------------------===//
2723
2724 //  Like std call, callee cleans arguments, convention except that ECX is
2725 //  reserved for storing the tail called function address. Only 2 registers are
2726 //  free for argument passing (inreg). Tail call optimization is performed
2727 //  provided:
2728 //                * tailcallopt is enabled
2729 //                * caller/callee are fastcc
2730 //  On X86_64 architecture with GOT-style position independent code only local
2731 //  (within module) calls are supported at the moment.
2732 //  To keep the stack aligned according to platform abi the function
2733 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2734 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2735 //  If a tail called function callee has more arguments than the caller the
2736 //  caller needs to make sure that there is room to move the RETADDR to. This is
2737 //  achieved by reserving an area the size of the argument delta right after the
2738 //  original REtADDR, but before the saved framepointer or the spilled registers
2739 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2740 //  stack layout:
2741 //    arg1
2742 //    arg2
2743 //    RETADDR
2744 //    [ new RETADDR
2745 //      move area ]
2746 //    (possible EBP)
2747 //    ESI
2748 //    EDI
2749 //    local1 ..
2750
2751 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2752 /// for a 16 byte align requirement.
2753 unsigned
2754 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2755                                                SelectionDAG& DAG) const {
2756   MachineFunction &MF = DAG.getMachineFunction();
2757   const TargetMachine &TM = MF.getTarget();
2758   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2759   unsigned StackAlignment = TFI.getStackAlignment();
2760   uint64_t AlignMask = StackAlignment - 1;
2761   int64_t Offset = StackSize;
2762   unsigned SlotSize = RegInfo->getSlotSize();
2763   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2764     // Number smaller than 12 so just add the difference.
2765     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2766   } else {
2767     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2768     Offset = ((~AlignMask) & Offset) + StackAlignment +
2769       (StackAlignment-SlotSize);
2770   }
2771   return Offset;
2772 }
2773
2774 /// MatchingStackOffset - Return true if the given stack call argument is
2775 /// already available in the same position (relatively) of the caller's
2776 /// incoming argument stack.
2777 static
2778 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2779                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2780                          const X86InstrInfo *TII) {
2781   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2782   int FI = INT_MAX;
2783   if (Arg.getOpcode() == ISD::CopyFromReg) {
2784     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2785     if (!TargetRegisterInfo::isVirtualRegister(VR))
2786       return false;
2787     MachineInstr *Def = MRI->getVRegDef(VR);
2788     if (!Def)
2789       return false;
2790     if (!Flags.isByVal()) {
2791       if (!TII->isLoadFromStackSlot(Def, FI))
2792         return false;
2793     } else {
2794       unsigned Opcode = Def->getOpcode();
2795       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2796           Def->getOperand(1).isFI()) {
2797         FI = Def->getOperand(1).getIndex();
2798         Bytes = Flags.getByValSize();
2799       } else
2800         return false;
2801     }
2802   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2803     if (Flags.isByVal())
2804       // ByVal argument is passed in as a pointer but it's now being
2805       // dereferenced. e.g.
2806       // define @foo(%struct.X* %A) {
2807       //   tail call @bar(%struct.X* byval %A)
2808       // }
2809       return false;
2810     SDValue Ptr = Ld->getBasePtr();
2811     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2812     if (!FINode)
2813       return false;
2814     FI = FINode->getIndex();
2815   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2816     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2817     FI = FINode->getIndex();
2818     Bytes = Flags.getByValSize();
2819   } else
2820     return false;
2821
2822   assert(FI != INT_MAX);
2823   if (!MFI->isFixedObjectIndex(FI))
2824     return false;
2825   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2826 }
2827
2828 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2829 /// for tail call optimization. Targets which want to do tail call
2830 /// optimization should implement this function.
2831 bool
2832 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2833                                                      CallingConv::ID CalleeCC,
2834                                                      bool isVarArg,
2835                                                      bool isCalleeStructRet,
2836                                                      bool isCallerStructRet,
2837                                                      Type *RetTy,
2838                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2839                                     const SmallVectorImpl<SDValue> &OutVals,
2840                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2841                                                      SelectionDAG &DAG) const {
2842   if (!IsTailCallConvention(CalleeCC) &&
2843       CalleeCC != CallingConv::C)
2844     return false;
2845
2846   // If -tailcallopt is specified, make fastcc functions tail-callable.
2847   const MachineFunction &MF = DAG.getMachineFunction();
2848   const Function *CallerF = DAG.getMachineFunction().getFunction();
2849
2850   // If the function return type is x86_fp80 and the callee return type is not,
2851   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2852   // perform a tailcall optimization here.
2853   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2854     return false;
2855
2856   CallingConv::ID CallerCC = CallerF->getCallingConv();
2857   bool CCMatch = CallerCC == CalleeCC;
2858
2859   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2860     if (IsTailCallConvention(CalleeCC) && CCMatch)
2861       return true;
2862     return false;
2863   }
2864
2865   // Look for obvious safe cases to perform tail call optimization that do not
2866   // require ABI changes. This is what gcc calls sibcall.
2867
2868   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2869   // emit a special epilogue.
2870   if (RegInfo->needsStackRealignment(MF))
2871     return false;
2872
2873   // Also avoid sibcall optimization if either caller or callee uses struct
2874   // return semantics.
2875   if (isCalleeStructRet || isCallerStructRet)
2876     return false;
2877
2878   // An stdcall caller is expected to clean up its arguments; the callee
2879   // isn't going to do that.
2880   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2881     return false;
2882
2883   // Do not sibcall optimize vararg calls unless all arguments are passed via
2884   // registers.
2885   if (isVarArg && !Outs.empty()) {
2886
2887     // Optimizing for varargs on Win64 is unlikely to be safe without
2888     // additional testing.
2889     if (Subtarget->isTargetWin64())
2890       return false;
2891
2892     SmallVector<CCValAssign, 16> ArgLocs;
2893     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2894                    getTargetMachine(), ArgLocs, *DAG.getContext());
2895
2896     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2897     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2898       if (!ArgLocs[i].isRegLoc())
2899         return false;
2900   }
2901
2902   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2903   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2904   // this into a sibcall.
2905   bool Unused = false;
2906   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2907     if (!Ins[i].Used) {
2908       Unused = true;
2909       break;
2910     }
2911   }
2912   if (Unused) {
2913     SmallVector<CCValAssign, 16> RVLocs;
2914     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2915                    getTargetMachine(), RVLocs, *DAG.getContext());
2916     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2917     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2918       CCValAssign &VA = RVLocs[i];
2919       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2920         return false;
2921     }
2922   }
2923
2924   // If the calling conventions do not match, then we'd better make sure the
2925   // results are returned in the same way as what the caller expects.
2926   if (!CCMatch) {
2927     SmallVector<CCValAssign, 16> RVLocs1;
2928     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2929                     getTargetMachine(), RVLocs1, *DAG.getContext());
2930     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2931
2932     SmallVector<CCValAssign, 16> RVLocs2;
2933     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2934                     getTargetMachine(), RVLocs2, *DAG.getContext());
2935     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2936
2937     if (RVLocs1.size() != RVLocs2.size())
2938       return false;
2939     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2940       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2941         return false;
2942       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2943         return false;
2944       if (RVLocs1[i].isRegLoc()) {
2945         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2946           return false;
2947       } else {
2948         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2949           return false;
2950       }
2951     }
2952   }
2953
2954   // If the callee takes no arguments then go on to check the results of the
2955   // call.
2956   if (!Outs.empty()) {
2957     // Check if stack adjustment is needed. For now, do not do this if any
2958     // argument is passed on the stack.
2959     SmallVector<CCValAssign, 16> ArgLocs;
2960     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2961                    getTargetMachine(), ArgLocs, *DAG.getContext());
2962
2963     // Allocate shadow area for Win64
2964     if (Subtarget->isTargetWin64()) {
2965       CCInfo.AllocateStack(32, 8);
2966     }
2967
2968     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2969     if (CCInfo.getNextStackOffset()) {
2970       MachineFunction &MF = DAG.getMachineFunction();
2971       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2972         return false;
2973
2974       // Check if the arguments are already laid out in the right way as
2975       // the caller's fixed stack objects.
2976       MachineFrameInfo *MFI = MF.getFrameInfo();
2977       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2978       const X86InstrInfo *TII =
2979         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2980       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2981         CCValAssign &VA = ArgLocs[i];
2982         SDValue Arg = OutVals[i];
2983         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2984         if (VA.getLocInfo() == CCValAssign::Indirect)
2985           return false;
2986         if (!VA.isRegLoc()) {
2987           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2988                                    MFI, MRI, TII))
2989             return false;
2990         }
2991       }
2992     }
2993
2994     // If the tailcall address may be in a register, then make sure it's
2995     // possible to register allocate for it. In 32-bit, the call address can
2996     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2997     // callee-saved registers are restored. These happen to be the same
2998     // registers used to pass 'inreg' arguments so watch out for those.
2999     if (!Subtarget->is64Bit() &&
3000         ((!isa<GlobalAddressSDNode>(Callee) &&
3001           !isa<ExternalSymbolSDNode>(Callee)) ||
3002          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3003       unsigned NumInRegs = 0;
3004       // In PIC we need an extra register to formulate the address computation
3005       // for the callee.
3006       unsigned MaxInRegs =
3007           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3008
3009       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3010         CCValAssign &VA = ArgLocs[i];
3011         if (!VA.isRegLoc())
3012           continue;
3013         unsigned Reg = VA.getLocReg();
3014         switch (Reg) {
3015         default: break;
3016         case X86::EAX: case X86::EDX: case X86::ECX:
3017           if (++NumInRegs == MaxInRegs)
3018             return false;
3019           break;
3020         }
3021       }
3022     }
3023   }
3024
3025   return true;
3026 }
3027
3028 FastISel *
3029 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3030                                   const TargetLibraryInfo *libInfo) const {
3031   return X86::createFastISel(funcInfo, libInfo);
3032 }
3033
3034 //===----------------------------------------------------------------------===//
3035 //                           Other Lowering Hooks
3036 //===----------------------------------------------------------------------===//
3037
3038 static bool MayFoldLoad(SDValue Op) {
3039   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3040 }
3041
3042 static bool MayFoldIntoStore(SDValue Op) {
3043   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3044 }
3045
3046 static bool isTargetShuffle(unsigned Opcode) {
3047   switch(Opcode) {
3048   default: return false;
3049   case X86ISD::PSHUFD:
3050   case X86ISD::PSHUFHW:
3051   case X86ISD::PSHUFLW:
3052   case X86ISD::SHUFP:
3053   case X86ISD::PALIGNR:
3054   case X86ISD::MOVLHPS:
3055   case X86ISD::MOVLHPD:
3056   case X86ISD::MOVHLPS:
3057   case X86ISD::MOVLPS:
3058   case X86ISD::MOVLPD:
3059   case X86ISD::MOVSHDUP:
3060   case X86ISD::MOVSLDUP:
3061   case X86ISD::MOVDDUP:
3062   case X86ISD::MOVSS:
3063   case X86ISD::MOVSD:
3064   case X86ISD::UNPCKL:
3065   case X86ISD::UNPCKH:
3066   case X86ISD::VPERMILP:
3067   case X86ISD::VPERM2X128:
3068   case X86ISD::VPERMI:
3069     return true;
3070   }
3071 }
3072
3073 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3074                                     SDValue V1, SelectionDAG &DAG) {
3075   switch(Opc) {
3076   default: llvm_unreachable("Unknown x86 shuffle node");
3077   case X86ISD::MOVSHDUP:
3078   case X86ISD::MOVSLDUP:
3079   case X86ISD::MOVDDUP:
3080     return DAG.getNode(Opc, dl, VT, V1);
3081   }
3082 }
3083
3084 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3085                                     SDValue V1, unsigned TargetMask,
3086                                     SelectionDAG &DAG) {
3087   switch(Opc) {
3088   default: llvm_unreachable("Unknown x86 shuffle node");
3089   case X86ISD::PSHUFD:
3090   case X86ISD::PSHUFHW:
3091   case X86ISD::PSHUFLW:
3092   case X86ISD::VPERMILP:
3093   case X86ISD::VPERMI:
3094     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3095   }
3096 }
3097
3098 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3099                                     SDValue V1, SDValue V2, unsigned TargetMask,
3100                                     SelectionDAG &DAG) {
3101   switch(Opc) {
3102   default: llvm_unreachable("Unknown x86 shuffle node");
3103   case X86ISD::PALIGNR:
3104   case X86ISD::SHUFP:
3105   case X86ISD::VPERM2X128:
3106     return DAG.getNode(Opc, dl, VT, V1, V2,
3107                        DAG.getConstant(TargetMask, MVT::i8));
3108   }
3109 }
3110
3111 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
3112                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3113   switch(Opc) {
3114   default: llvm_unreachable("Unknown x86 shuffle node");
3115   case X86ISD::MOVLHPS:
3116   case X86ISD::MOVLHPD:
3117   case X86ISD::MOVHLPS:
3118   case X86ISD::MOVLPS:
3119   case X86ISD::MOVLPD:
3120   case X86ISD::MOVSS:
3121   case X86ISD::MOVSD:
3122   case X86ISD::UNPCKL:
3123   case X86ISD::UNPCKH:
3124     return DAG.getNode(Opc, dl, VT, V1, V2);
3125   }
3126 }
3127
3128 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3129   MachineFunction &MF = DAG.getMachineFunction();
3130   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3131   int ReturnAddrIndex = FuncInfo->getRAIndex();
3132
3133   if (ReturnAddrIndex == 0) {
3134     // Set up a frame object for the return address.
3135     unsigned SlotSize = RegInfo->getSlotSize();
3136     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
3137                                                            false);
3138     FuncInfo->setRAIndex(ReturnAddrIndex);
3139   }
3140
3141   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3142 }
3143
3144 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3145                                        bool hasSymbolicDisplacement) {
3146   // Offset should fit into 32 bit immediate field.
3147   if (!isInt<32>(Offset))
3148     return false;
3149
3150   // If we don't have a symbolic displacement - we don't have any extra
3151   // restrictions.
3152   if (!hasSymbolicDisplacement)
3153     return true;
3154
3155   // FIXME: Some tweaks might be needed for medium code model.
3156   if (M != CodeModel::Small && M != CodeModel::Kernel)
3157     return false;
3158
3159   // For small code model we assume that latest object is 16MB before end of 31
3160   // bits boundary. We may also accept pretty large negative constants knowing
3161   // that all objects are in the positive half of address space.
3162   if (M == CodeModel::Small && Offset < 16*1024*1024)
3163     return true;
3164
3165   // For kernel code model we know that all object resist in the negative half
3166   // of 32bits address space. We may not accept negative offsets, since they may
3167   // be just off and we may accept pretty large positive ones.
3168   if (M == CodeModel::Kernel && Offset > 0)
3169     return true;
3170
3171   return false;
3172 }
3173
3174 /// isCalleePop - Determines whether the callee is required to pop its
3175 /// own arguments. Callee pop is necessary to support tail calls.
3176 bool X86::isCalleePop(CallingConv::ID CallingConv,
3177                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3178   if (IsVarArg)
3179     return false;
3180
3181   switch (CallingConv) {
3182   default:
3183     return false;
3184   case CallingConv::X86_StdCall:
3185     return !is64Bit;
3186   case CallingConv::X86_FastCall:
3187     return !is64Bit;
3188   case CallingConv::X86_ThisCall:
3189     return !is64Bit;
3190   case CallingConv::Fast:
3191     return TailCallOpt;
3192   case CallingConv::GHC:
3193     return TailCallOpt;
3194   case CallingConv::HiPE:
3195     return TailCallOpt;
3196   }
3197 }
3198
3199 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3200 /// specific condition code, returning the condition code and the LHS/RHS of the
3201 /// comparison to make.
3202 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3203                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3204   if (!isFP) {
3205     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3206       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3207         // X > -1   -> X == 0, jump !sign.
3208         RHS = DAG.getConstant(0, RHS.getValueType());
3209         return X86::COND_NS;
3210       }
3211       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3212         // X < 0   -> X == 0, jump on sign.
3213         return X86::COND_S;
3214       }
3215       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3216         // X < 1   -> X <= 0
3217         RHS = DAG.getConstant(0, RHS.getValueType());
3218         return X86::COND_LE;
3219       }
3220     }
3221
3222     switch (SetCCOpcode) {
3223     default: llvm_unreachable("Invalid integer condition!");
3224     case ISD::SETEQ:  return X86::COND_E;
3225     case ISD::SETGT:  return X86::COND_G;
3226     case ISD::SETGE:  return X86::COND_GE;
3227     case ISD::SETLT:  return X86::COND_L;
3228     case ISD::SETLE:  return X86::COND_LE;
3229     case ISD::SETNE:  return X86::COND_NE;
3230     case ISD::SETULT: return X86::COND_B;
3231     case ISD::SETUGT: return X86::COND_A;
3232     case ISD::SETULE: return X86::COND_BE;
3233     case ISD::SETUGE: return X86::COND_AE;
3234     }
3235   }
3236
3237   // First determine if it is required or is profitable to flip the operands.
3238
3239   // If LHS is a foldable load, but RHS is not, flip the condition.
3240   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3241       !ISD::isNON_EXTLoad(RHS.getNode())) {
3242     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3243     std::swap(LHS, RHS);
3244   }
3245
3246   switch (SetCCOpcode) {
3247   default: break;
3248   case ISD::SETOLT:
3249   case ISD::SETOLE:
3250   case ISD::SETUGT:
3251   case ISD::SETUGE:
3252     std::swap(LHS, RHS);
3253     break;
3254   }
3255
3256   // On a floating point condition, the flags are set as follows:
3257   // ZF  PF  CF   op
3258   //  0 | 0 | 0 | X > Y
3259   //  0 | 0 | 1 | X < Y
3260   //  1 | 0 | 0 | X == Y
3261   //  1 | 1 | 1 | unordered
3262   switch (SetCCOpcode) {
3263   default: llvm_unreachable("Condcode should be pre-legalized away");
3264   case ISD::SETUEQ:
3265   case ISD::SETEQ:   return X86::COND_E;
3266   case ISD::SETOLT:              // flipped
3267   case ISD::SETOGT:
3268   case ISD::SETGT:   return X86::COND_A;
3269   case ISD::SETOLE:              // flipped
3270   case ISD::SETOGE:
3271   case ISD::SETGE:   return X86::COND_AE;
3272   case ISD::SETUGT:              // flipped
3273   case ISD::SETULT:
3274   case ISD::SETLT:   return X86::COND_B;
3275   case ISD::SETUGE:              // flipped
3276   case ISD::SETULE:
3277   case ISD::SETLE:   return X86::COND_BE;
3278   case ISD::SETONE:
3279   case ISD::SETNE:   return X86::COND_NE;
3280   case ISD::SETUO:   return X86::COND_P;
3281   case ISD::SETO:    return X86::COND_NP;
3282   case ISD::SETOEQ:
3283   case ISD::SETUNE:  return X86::COND_INVALID;
3284   }
3285 }
3286
3287 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3288 /// code. Current x86 isa includes the following FP cmov instructions:
3289 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3290 static bool hasFPCMov(unsigned X86CC) {
3291   switch (X86CC) {
3292   default:
3293     return false;
3294   case X86::COND_B:
3295   case X86::COND_BE:
3296   case X86::COND_E:
3297   case X86::COND_P:
3298   case X86::COND_A:
3299   case X86::COND_AE:
3300   case X86::COND_NE:
3301   case X86::COND_NP:
3302     return true;
3303   }
3304 }
3305
3306 /// isFPImmLegal - Returns true if the target can instruction select the
3307 /// specified FP immediate natively. If false, the legalizer will
3308 /// materialize the FP immediate as a load from a constant pool.
3309 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3310   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3311     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3312       return true;
3313   }
3314   return false;
3315 }
3316
3317 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3318 /// the specified range (L, H].
3319 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3320   return (Val < 0) || (Val >= Low && Val < Hi);
3321 }
3322
3323 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3324 /// specified value.
3325 static bool isUndefOrEqual(int Val, int CmpVal) {
3326   return (Val < 0 || Val == CmpVal);
3327 }
3328
3329 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3330 /// from position Pos and ending in Pos+Size, falls within the specified
3331 /// sequential range (L, L+Pos]. or is undef.
3332 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3333                                        unsigned Pos, unsigned Size, int Low) {
3334   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3335     if (!isUndefOrEqual(Mask[i], Low))
3336       return false;
3337   return true;
3338 }
3339
3340 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3341 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3342 /// the second operand.
3343 static bool isPSHUFDMask(ArrayRef<int> Mask, EVT VT) {
3344   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3345     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3346   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3347     return (Mask[0] < 2 && Mask[1] < 2);
3348   return false;
3349 }
3350
3351 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3352 /// is suitable for input to PSHUFHW.
3353 static bool isPSHUFHWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3354   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3355     return false;
3356
3357   // Lower quadword copied in order or undef.
3358   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3359     return false;
3360
3361   // Upper quadword shuffled.
3362   for (unsigned i = 4; i != 8; ++i)
3363     if (!isUndefOrInRange(Mask[i], 4, 8))
3364       return false;
3365
3366   if (VT == MVT::v16i16) {
3367     // Lower quadword copied in order or undef.
3368     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3369       return false;
3370
3371     // Upper quadword shuffled.
3372     for (unsigned i = 12; i != 16; ++i)
3373       if (!isUndefOrInRange(Mask[i], 12, 16))
3374         return false;
3375   }
3376
3377   return true;
3378 }
3379
3380 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3381 /// is suitable for input to PSHUFLW.
3382 static bool isPSHUFLWMask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3383   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3384     return false;
3385
3386   // Upper quadword copied in order.
3387   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3388     return false;
3389
3390   // Lower quadword shuffled.
3391   for (unsigned i = 0; i != 4; ++i)
3392     if (!isUndefOrInRange(Mask[i], 0, 4))
3393       return false;
3394
3395   if (VT == MVT::v16i16) {
3396     // Upper quadword copied in order.
3397     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3398       return false;
3399
3400     // Lower quadword shuffled.
3401     for (unsigned i = 8; i != 12; ++i)
3402       if (!isUndefOrInRange(Mask[i], 8, 12))
3403         return false;
3404   }
3405
3406   return true;
3407 }
3408
3409 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3410 /// is suitable for input to PALIGNR.
3411 static bool isPALIGNRMask(ArrayRef<int> Mask, EVT VT,
3412                           const X86Subtarget *Subtarget) {
3413   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3414       (VT.is256BitVector() && !Subtarget->hasInt256()))
3415     return false;
3416
3417   unsigned NumElts = VT.getVectorNumElements();
3418   unsigned NumLanes = VT.getSizeInBits()/128;
3419   unsigned NumLaneElts = NumElts/NumLanes;
3420
3421   // Do not handle 64-bit element shuffles with palignr.
3422   if (NumLaneElts == 2)
3423     return false;
3424
3425   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3426     unsigned i;
3427     for (i = 0; i != NumLaneElts; ++i) {
3428       if (Mask[i+l] >= 0)
3429         break;
3430     }
3431
3432     // Lane is all undef, go to next lane
3433     if (i == NumLaneElts)
3434       continue;
3435
3436     int Start = Mask[i+l];
3437
3438     // Make sure its in this lane in one of the sources
3439     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3440         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3441       return false;
3442
3443     // If not lane 0, then we must match lane 0
3444     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3445       return false;
3446
3447     // Correct second source to be contiguous with first source
3448     if (Start >= (int)NumElts)
3449       Start -= NumElts - NumLaneElts;
3450
3451     // Make sure we're shifting in the right direction.
3452     if (Start <= (int)(i+l))
3453       return false;
3454
3455     Start -= i;
3456
3457     // Check the rest of the elements to see if they are consecutive.
3458     for (++i; i != NumLaneElts; ++i) {
3459       int Idx = Mask[i+l];
3460
3461       // Make sure its in this lane
3462       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3463           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3464         return false;
3465
3466       // If not lane 0, then we must match lane 0
3467       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3468         return false;
3469
3470       if (Idx >= (int)NumElts)
3471         Idx -= NumElts - NumLaneElts;
3472
3473       if (!isUndefOrEqual(Idx, Start+i))
3474         return false;
3475
3476     }
3477   }
3478
3479   return true;
3480 }
3481
3482 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3483 /// the two vector operands have swapped position.
3484 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3485                                      unsigned NumElems) {
3486   for (unsigned i = 0; i != NumElems; ++i) {
3487     int idx = Mask[i];
3488     if (idx < 0)
3489       continue;
3490     else if (idx < (int)NumElems)
3491       Mask[i] = idx + NumElems;
3492     else
3493       Mask[i] = idx - NumElems;
3494   }
3495 }
3496
3497 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3498 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3499 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3500 /// reverse of what x86 shuffles want.
3501 static bool isSHUFPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256,
3502                         bool Commuted = false) {
3503   if (!HasFp256 && VT.is256BitVector())
3504     return false;
3505
3506   unsigned NumElems = VT.getVectorNumElements();
3507   unsigned NumLanes = VT.getSizeInBits()/128;
3508   unsigned NumLaneElems = NumElems/NumLanes;
3509
3510   if (NumLaneElems != 2 && NumLaneElems != 4)
3511     return false;
3512
3513   // VSHUFPSY divides the resulting vector into 4 chunks.
3514   // The sources are also splitted into 4 chunks, and each destination
3515   // chunk must come from a different source chunk.
3516   //
3517   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3518   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3519   //
3520   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3521   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3522   //
3523   // VSHUFPDY divides the resulting vector into 4 chunks.
3524   // The sources are also splitted into 4 chunks, and each destination
3525   // chunk must come from a different source chunk.
3526   //
3527   //  SRC1 =>      X3       X2       X1       X0
3528   //  SRC2 =>      Y3       Y2       Y1       Y0
3529   //
3530   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3531   //
3532   unsigned HalfLaneElems = NumLaneElems/2;
3533   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3534     for (unsigned i = 0; i != NumLaneElems; ++i) {
3535       int Idx = Mask[i+l];
3536       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3537       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3538         return false;
3539       // For VSHUFPSY, the mask of the second half must be the same as the
3540       // first but with the appropriate offsets. This works in the same way as
3541       // VPERMILPS works with masks.
3542       if (NumElems != 8 || l == 0 || Mask[i] < 0)
3543         continue;
3544       if (!isUndefOrEqual(Idx, Mask[i]+l))
3545         return false;
3546     }
3547   }
3548
3549   return true;
3550 }
3551
3552 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3553 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3554 static bool isMOVHLPSMask(ArrayRef<int> Mask, EVT VT) {
3555   if (!VT.is128BitVector())
3556     return false;
3557
3558   unsigned NumElems = VT.getVectorNumElements();
3559
3560   if (NumElems != 4)
3561     return false;
3562
3563   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3564   return isUndefOrEqual(Mask[0], 6) &&
3565          isUndefOrEqual(Mask[1], 7) &&
3566          isUndefOrEqual(Mask[2], 2) &&
3567          isUndefOrEqual(Mask[3], 3);
3568 }
3569
3570 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3571 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3572 /// <2, 3, 2, 3>
3573 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, EVT VT) {
3574   if (!VT.is128BitVector())
3575     return false;
3576
3577   unsigned NumElems = VT.getVectorNumElements();
3578
3579   if (NumElems != 4)
3580     return false;
3581
3582   return isUndefOrEqual(Mask[0], 2) &&
3583          isUndefOrEqual(Mask[1], 3) &&
3584          isUndefOrEqual(Mask[2], 2) &&
3585          isUndefOrEqual(Mask[3], 3);
3586 }
3587
3588 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3589 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3590 static bool isMOVLPMask(ArrayRef<int> Mask, EVT VT) {
3591   if (!VT.is128BitVector())
3592     return false;
3593
3594   unsigned NumElems = VT.getVectorNumElements();
3595
3596   if (NumElems != 2 && NumElems != 4)
3597     return false;
3598
3599   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3600     if (!isUndefOrEqual(Mask[i], i + NumElems))
3601       return false;
3602
3603   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3604     if (!isUndefOrEqual(Mask[i], i))
3605       return false;
3606
3607   return true;
3608 }
3609
3610 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3611 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3612 static bool isMOVLHPSMask(ArrayRef<int> Mask, EVT VT) {
3613   if (!VT.is128BitVector())
3614     return false;
3615
3616   unsigned NumElems = VT.getVectorNumElements();
3617
3618   if (NumElems != 2 && NumElems != 4)
3619     return false;
3620
3621   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3622     if (!isUndefOrEqual(Mask[i], i))
3623       return false;
3624
3625   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3626     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3627       return false;
3628
3629   return true;
3630 }
3631
3632 //
3633 // Some special combinations that can be optimized.
3634 //
3635 static
3636 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3637                                SelectionDAG &DAG) {
3638   MVT VT = SVOp->getValueType(0).getSimpleVT();
3639   DebugLoc dl = SVOp->getDebugLoc();
3640
3641   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3642     return SDValue();
3643
3644   ArrayRef<int> Mask = SVOp->getMask();
3645
3646   // These are the special masks that may be optimized.
3647   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3648   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3649   bool MatchEvenMask = true;
3650   bool MatchOddMask  = true;
3651   for (int i=0; i<8; ++i) {
3652     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
3653       MatchEvenMask = false;
3654     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
3655       MatchOddMask = false;
3656   }
3657
3658   if (!MatchEvenMask && !MatchOddMask)
3659     return SDValue();
3660
3661   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
3662
3663   SDValue Op0 = SVOp->getOperand(0);
3664   SDValue Op1 = SVOp->getOperand(1);
3665
3666   if (MatchEvenMask) {
3667     // Shift the second operand right to 32 bits.
3668     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
3669     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
3670   } else {
3671     // Shift the first operand left to 32 bits.
3672     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
3673     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
3674   }
3675   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
3676   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
3677 }
3678
3679 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3680 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3681 static bool isUNPCKLMask(ArrayRef<int> Mask, EVT VT,
3682                          bool HasInt256, bool V2IsSplat = false) {
3683   unsigned NumElts = VT.getVectorNumElements();
3684
3685   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3686          "Unsupported vector type for unpckh");
3687
3688   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3689       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3690     return false;
3691
3692   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3693   // independently on 128-bit lanes.
3694   unsigned NumLanes = VT.getSizeInBits()/128;
3695   unsigned NumLaneElts = NumElts/NumLanes;
3696
3697   for (unsigned l = 0; l != NumLanes; ++l) {
3698     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3699          i != (l+1)*NumLaneElts;
3700          i += 2, ++j) {
3701       int BitI  = Mask[i];
3702       int BitI1 = Mask[i+1];
3703       if (!isUndefOrEqual(BitI, j))
3704         return false;
3705       if (V2IsSplat) {
3706         if (!isUndefOrEqual(BitI1, NumElts))
3707           return false;
3708       } else {
3709         if (!isUndefOrEqual(BitI1, j + NumElts))
3710           return false;
3711       }
3712     }
3713   }
3714
3715   return true;
3716 }
3717
3718 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3719 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3720 static bool isUNPCKHMask(ArrayRef<int> Mask, EVT VT,
3721                          bool HasInt256, bool V2IsSplat = false) {
3722   unsigned NumElts = VT.getVectorNumElements();
3723
3724   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3725          "Unsupported vector type for unpckh");
3726
3727   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3728       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3729     return false;
3730
3731   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3732   // independently on 128-bit lanes.
3733   unsigned NumLanes = VT.getSizeInBits()/128;
3734   unsigned NumLaneElts = NumElts/NumLanes;
3735
3736   for (unsigned l = 0; l != NumLanes; ++l) {
3737     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3738          i != (l+1)*NumLaneElts; i += 2, ++j) {
3739       int BitI  = Mask[i];
3740       int BitI1 = Mask[i+1];
3741       if (!isUndefOrEqual(BitI, j))
3742         return false;
3743       if (V2IsSplat) {
3744         if (isUndefOrEqual(BitI1, NumElts))
3745           return false;
3746       } else {
3747         if (!isUndefOrEqual(BitI1, j+NumElts))
3748           return false;
3749       }
3750     }
3751   }
3752   return true;
3753 }
3754
3755 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3756 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3757 /// <0, 0, 1, 1>
3758 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3759   unsigned NumElts = VT.getVectorNumElements();
3760   bool Is256BitVec = VT.is256BitVector();
3761
3762   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3763          "Unsupported vector type for unpckh");
3764
3765   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
3766       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3767     return false;
3768
3769   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3770   // FIXME: Need a better way to get rid of this, there's no latency difference
3771   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3772   // the former later. We should also remove the "_undef" special mask.
3773   if (NumElts == 4 && Is256BitVec)
3774     return false;
3775
3776   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3777   // independently on 128-bit lanes.
3778   unsigned NumLanes = VT.getSizeInBits()/128;
3779   unsigned NumLaneElts = NumElts/NumLanes;
3780
3781   for (unsigned l = 0; l != NumLanes; ++l) {
3782     for (unsigned i = l*NumLaneElts, j = l*NumLaneElts;
3783          i != (l+1)*NumLaneElts;
3784          i += 2, ++j) {
3785       int BitI  = Mask[i];
3786       int BitI1 = Mask[i+1];
3787
3788       if (!isUndefOrEqual(BitI, j))
3789         return false;
3790       if (!isUndefOrEqual(BitI1, j))
3791         return false;
3792     }
3793   }
3794
3795   return true;
3796 }
3797
3798 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3799 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3800 /// <2, 2, 3, 3>
3801 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, EVT VT, bool HasInt256) {
3802   unsigned NumElts = VT.getVectorNumElements();
3803
3804   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3805          "Unsupported vector type for unpckh");
3806
3807   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
3808       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
3809     return false;
3810
3811   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3812   // independently on 128-bit lanes.
3813   unsigned NumLanes = VT.getSizeInBits()/128;
3814   unsigned NumLaneElts = NumElts/NumLanes;
3815
3816   for (unsigned l = 0; l != NumLanes; ++l) {
3817     for (unsigned i = l*NumLaneElts, j = (l*NumLaneElts)+NumLaneElts/2;
3818          i != (l+1)*NumLaneElts; i += 2, ++j) {
3819       int BitI  = Mask[i];
3820       int BitI1 = Mask[i+1];
3821       if (!isUndefOrEqual(BitI, j))
3822         return false;
3823       if (!isUndefOrEqual(BitI1, j))
3824         return false;
3825     }
3826   }
3827   return true;
3828 }
3829
3830 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3831 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3832 /// MOVSD, and MOVD, i.e. setting the lowest element.
3833 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
3834   if (VT.getVectorElementType().getSizeInBits() < 32)
3835     return false;
3836   if (!VT.is128BitVector())
3837     return false;
3838
3839   unsigned NumElts = VT.getVectorNumElements();
3840
3841   if (!isUndefOrEqual(Mask[0], NumElts))
3842     return false;
3843
3844   for (unsigned i = 1; i != NumElts; ++i)
3845     if (!isUndefOrEqual(Mask[i], i))
3846       return false;
3847
3848   return true;
3849 }
3850
3851 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
3852 /// as permutations between 128-bit chunks or halves. As an example: this
3853 /// shuffle bellow:
3854 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3855 /// The first half comes from the second half of V1 and the second half from the
3856 /// the second half of V2.
3857 static bool isVPERM2X128Mask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3858   if (!HasFp256 || !VT.is256BitVector())
3859     return false;
3860
3861   // The shuffle result is divided into half A and half B. In total the two
3862   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3863   // B must come from C, D, E or F.
3864   unsigned HalfSize = VT.getVectorNumElements()/2;
3865   bool MatchA = false, MatchB = false;
3866
3867   // Check if A comes from one of C, D, E, F.
3868   for (unsigned Half = 0; Half != 4; ++Half) {
3869     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3870       MatchA = true;
3871       break;
3872     }
3873   }
3874
3875   // Check if B comes from one of C, D, E, F.
3876   for (unsigned Half = 0; Half != 4; ++Half) {
3877     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3878       MatchB = true;
3879       break;
3880     }
3881   }
3882
3883   return MatchA && MatchB;
3884 }
3885
3886 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
3887 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
3888 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
3889   MVT VT = SVOp->getValueType(0).getSimpleVT();
3890
3891   unsigned HalfSize = VT.getVectorNumElements()/2;
3892
3893   unsigned FstHalf = 0, SndHalf = 0;
3894   for (unsigned i = 0; i < HalfSize; ++i) {
3895     if (SVOp->getMaskElt(i) > 0) {
3896       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3897       break;
3898     }
3899   }
3900   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
3901     if (SVOp->getMaskElt(i) > 0) {
3902       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3903       break;
3904     }
3905   }
3906
3907   return (FstHalf | (SndHalf << 4));
3908 }
3909
3910 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
3911 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3912 /// Note that VPERMIL mask matching is different depending whether theunderlying
3913 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3914 /// to the same elements of the low, but to the higher half of the source.
3915 /// In VPERMILPD the two lanes could be shuffled independently of each other
3916 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
3917 static bool isVPERMILPMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
3918   if (!HasFp256)
3919     return false;
3920
3921   unsigned NumElts = VT.getVectorNumElements();
3922   // Only match 256-bit with 32/64-bit types
3923   if (!VT.is256BitVector() || (NumElts != 4 && NumElts != 8))
3924     return false;
3925
3926   unsigned NumLanes = VT.getSizeInBits()/128;
3927   unsigned LaneSize = NumElts/NumLanes;
3928   for (unsigned l = 0; l != NumElts; l += LaneSize) {
3929     for (unsigned i = 0; i != LaneSize; ++i) {
3930       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
3931         return false;
3932       if (NumElts != 8 || l == 0)
3933         continue;
3934       // VPERMILPS handling
3935       if (Mask[i] < 0)
3936         continue;
3937       if (!isUndefOrEqual(Mask[i+l], Mask[i]+l))
3938         return false;
3939     }
3940   }
3941
3942   return true;
3943 }
3944
3945 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
3946 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3947 /// element of vector 2 and the other elements to come from vector 1 in order.
3948 static bool isCommutedMOVLMask(ArrayRef<int> Mask, EVT VT,
3949                                bool V2IsSplat = false, bool V2IsUndef = false) {
3950   if (!VT.is128BitVector())
3951     return false;
3952
3953   unsigned NumOps = VT.getVectorNumElements();
3954   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3955     return false;
3956
3957   if (!isUndefOrEqual(Mask[0], 0))
3958     return false;
3959
3960   for (unsigned i = 1; i != NumOps; ++i)
3961     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3962           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3963           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3964       return false;
3965
3966   return true;
3967 }
3968
3969 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3970 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3971 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3972 static bool isMOVSHDUPMask(ArrayRef<int> Mask, EVT VT,
3973                            const X86Subtarget *Subtarget) {
3974   if (!Subtarget->hasSSE3())
3975     return false;
3976
3977   unsigned NumElems = VT.getVectorNumElements();
3978
3979   if ((VT.is128BitVector() && NumElems != 4) ||
3980       (VT.is256BitVector() && NumElems != 8))
3981     return false;
3982
3983   // "i+1" is the value the indexed mask element must have
3984   for (unsigned i = 0; i != NumElems; i += 2)
3985     if (!isUndefOrEqual(Mask[i], i+1) ||
3986         !isUndefOrEqual(Mask[i+1], i+1))
3987       return false;
3988
3989   return true;
3990 }
3991
3992 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3993 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3994 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3995 static bool isMOVSLDUPMask(ArrayRef<int> Mask, EVT VT,
3996                            const X86Subtarget *Subtarget) {
3997   if (!Subtarget->hasSSE3())
3998     return false;
3999
4000   unsigned NumElems = VT.getVectorNumElements();
4001
4002   if ((VT.is128BitVector() && NumElems != 4) ||
4003       (VT.is256BitVector() && NumElems != 8))
4004     return false;
4005
4006   // "i" is the value the indexed mask element must have
4007   for (unsigned i = 0; i != NumElems; i += 2)
4008     if (!isUndefOrEqual(Mask[i], i) ||
4009         !isUndefOrEqual(Mask[i+1], i))
4010       return false;
4011
4012   return true;
4013 }
4014
4015 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4016 /// specifies a shuffle of elements that is suitable for input to 256-bit
4017 /// version of MOVDDUP.
4018 static bool isMOVDDUPYMask(ArrayRef<int> Mask, EVT VT, bool HasFp256) {
4019   if (!HasFp256 || !VT.is256BitVector())
4020     return false;
4021
4022   unsigned NumElts = VT.getVectorNumElements();
4023   if (NumElts != 4)
4024     return false;
4025
4026   for (unsigned i = 0; i != NumElts/2; ++i)
4027     if (!isUndefOrEqual(Mask[i], 0))
4028       return false;
4029   for (unsigned i = NumElts/2; i != NumElts; ++i)
4030     if (!isUndefOrEqual(Mask[i], NumElts/2))
4031       return false;
4032   return true;
4033 }
4034
4035 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to 128-bit
4037 /// version of MOVDDUP.
4038 static bool isMOVDDUPMask(ArrayRef<int> Mask, EVT VT) {
4039   if (!VT.is128BitVector())
4040     return false;
4041
4042   unsigned e = VT.getVectorNumElements() / 2;
4043   for (unsigned i = 0; i != e; ++i)
4044     if (!isUndefOrEqual(Mask[i], i))
4045       return false;
4046   for (unsigned i = 0; i != e; ++i)
4047     if (!isUndefOrEqual(Mask[e+i], i))
4048       return false;
4049   return true;
4050 }
4051
4052 /// isVEXTRACTF128Index - Return true if the specified
4053 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4054 /// suitable for input to VEXTRACTF128.
4055 bool X86::isVEXTRACTF128Index(SDNode *N) {
4056   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4057     return false;
4058
4059   // The index should be aligned on a 128-bit boundary.
4060   uint64_t Index =
4061     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4062
4063   MVT VT = N->getValueType(0).getSimpleVT();
4064   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4065   bool Result = (Index * ElSize) % 128 == 0;
4066
4067   return Result;
4068 }
4069
4070 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4071 /// operand specifies a subvector insert that is suitable for input to
4072 /// VINSERTF128.
4073 bool X86::isVINSERTF128Index(SDNode *N) {
4074   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4075     return false;
4076
4077   // The index should be aligned on a 128-bit boundary.
4078   uint64_t Index =
4079     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4080
4081   MVT VT = N->getValueType(0).getSimpleVT();
4082   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4083   bool Result = (Index * ElSize) % 128 == 0;
4084
4085   return Result;
4086 }
4087
4088 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4089 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4090 /// Handles 128-bit and 256-bit.
4091 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4092   MVT VT = N->getValueType(0).getSimpleVT();
4093
4094   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4095          "Unsupported vector type for PSHUF/SHUFP");
4096
4097   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4098   // independently on 128-bit lanes.
4099   unsigned NumElts = VT.getVectorNumElements();
4100   unsigned NumLanes = VT.getSizeInBits()/128;
4101   unsigned NumLaneElts = NumElts/NumLanes;
4102
4103   assert((NumLaneElts == 2 || NumLaneElts == 4) &&
4104          "Only supports 2 or 4 elements per lane");
4105
4106   unsigned Shift = (NumLaneElts == 4) ? 1 : 0;
4107   unsigned Mask = 0;
4108   for (unsigned i = 0; i != NumElts; ++i) {
4109     int Elt = N->getMaskElt(i);
4110     if (Elt < 0) continue;
4111     Elt &= NumLaneElts - 1;
4112     unsigned ShAmt = (i << Shift) % 8;
4113     Mask |= Elt << ShAmt;
4114   }
4115
4116   return Mask;
4117 }
4118
4119 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4120 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4121 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4122   MVT VT = N->getValueType(0).getSimpleVT();
4123
4124   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4125          "Unsupported vector type for PSHUFHW");
4126
4127   unsigned NumElts = VT.getVectorNumElements();
4128
4129   unsigned Mask = 0;
4130   for (unsigned l = 0; l != NumElts; l += 8) {
4131     // 8 nodes per lane, but we only care about the last 4.
4132     for (unsigned i = 0; i < 4; ++i) {
4133       int Elt = N->getMaskElt(l+i+4);
4134       if (Elt < 0) continue;
4135       Elt &= 0x3; // only 2-bits.
4136       Mask |= Elt << (i * 2);
4137     }
4138   }
4139
4140   return Mask;
4141 }
4142
4143 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4144 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4145 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4146   MVT VT = N->getValueType(0).getSimpleVT();
4147
4148   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4149          "Unsupported vector type for PSHUFHW");
4150
4151   unsigned NumElts = VT.getVectorNumElements();
4152
4153   unsigned Mask = 0;
4154   for (unsigned l = 0; l != NumElts; l += 8) {
4155     // 8 nodes per lane, but we only care about the first 4.
4156     for (unsigned i = 0; i < 4; ++i) {
4157       int Elt = N->getMaskElt(l+i);
4158       if (Elt < 0) continue;
4159       Elt &= 0x3; // only 2-bits
4160       Mask |= Elt << (i * 2);
4161     }
4162   }
4163
4164   return Mask;
4165 }
4166
4167 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4168 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4169 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4170   MVT VT = SVOp->getValueType(0).getSimpleVT();
4171   unsigned EltSize = VT.getVectorElementType().getSizeInBits() >> 3;
4172
4173   unsigned NumElts = VT.getVectorNumElements();
4174   unsigned NumLanes = VT.getSizeInBits()/128;
4175   unsigned NumLaneElts = NumElts/NumLanes;
4176
4177   int Val = 0;
4178   unsigned i;
4179   for (i = 0; i != NumElts; ++i) {
4180     Val = SVOp->getMaskElt(i);
4181     if (Val >= 0)
4182       break;
4183   }
4184   if (Val >= (int)NumElts)
4185     Val -= NumElts - NumLaneElts;
4186
4187   assert(Val - i > 0 && "PALIGNR imm should be positive");
4188   return (Val - i) * EltSize;
4189 }
4190
4191 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4192 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4193 /// instructions.
4194 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4195   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4196     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4197
4198   uint64_t Index =
4199     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4200
4201   MVT VecVT = N->getOperand(0).getValueType().getSimpleVT();
4202   MVT ElVT = VecVT.getVectorElementType();
4203
4204   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4205   return Index / NumElemsPerChunk;
4206 }
4207
4208 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4209 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4210 /// instructions.
4211 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4212   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4213     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4214
4215   uint64_t Index =
4216     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4217
4218   MVT VecVT = N->getValueType(0).getSimpleVT();
4219   MVT ElVT = VecVT.getVectorElementType();
4220
4221   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4222   return Index / NumElemsPerChunk;
4223 }
4224
4225 /// getShuffleCLImmediate - Return the appropriate immediate to shuffle
4226 /// the specified VECTOR_SHUFFLE mask with VPERMQ and VPERMPD instructions.
4227 /// Handles 256-bit.
4228 static unsigned getShuffleCLImmediate(ShuffleVectorSDNode *N) {
4229   MVT VT = N->getValueType(0).getSimpleVT();
4230
4231   unsigned NumElts = VT.getVectorNumElements();
4232
4233   assert((VT.is256BitVector() && NumElts == 4) &&
4234          "Unsupported vector type for VPERMQ/VPERMPD");
4235
4236   unsigned Mask = 0;
4237   for (unsigned i = 0; i != NumElts; ++i) {
4238     int Elt = N->getMaskElt(i);
4239     if (Elt < 0)
4240       continue;
4241     Mask |= Elt << (i*2);
4242   }
4243
4244   return Mask;
4245 }
4246 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4247 /// constant +0.0.
4248 bool X86::isZeroNode(SDValue Elt) {
4249   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Elt))
4250     return CN->isNullValue();
4251   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4252     return CFP->getValueAPF().isPosZero();
4253   return false;
4254 }
4255
4256 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4257 /// their permute mask.
4258 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4259                                     SelectionDAG &DAG) {
4260   MVT VT = SVOp->getValueType(0).getSimpleVT();
4261   unsigned NumElems = VT.getVectorNumElements();
4262   SmallVector<int, 8> MaskVec;
4263
4264   for (unsigned i = 0; i != NumElems; ++i) {
4265     int Idx = SVOp->getMaskElt(i);
4266     if (Idx >= 0) {
4267       if (Idx < (int)NumElems)
4268         Idx += NumElems;
4269       else
4270         Idx -= NumElems;
4271     }
4272     MaskVec.push_back(Idx);
4273   }
4274   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4275                               SVOp->getOperand(0), &MaskVec[0]);
4276 }
4277
4278 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4279 /// match movhlps. The lower half elements should come from upper half of
4280 /// V1 (and in order), and the upper half elements should come from the upper
4281 /// half of V2 (and in order).
4282 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, EVT VT) {
4283   if (!VT.is128BitVector())
4284     return false;
4285   if (VT.getVectorNumElements() != 4)
4286     return false;
4287   for (unsigned i = 0, e = 2; i != e; ++i)
4288     if (!isUndefOrEqual(Mask[i], i+2))
4289       return false;
4290   for (unsigned i = 2; i != 4; ++i)
4291     if (!isUndefOrEqual(Mask[i], i+4))
4292       return false;
4293   return true;
4294 }
4295
4296 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4297 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4298 /// required.
4299 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4300   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4301     return false;
4302   N = N->getOperand(0).getNode();
4303   if (!ISD::isNON_EXTLoad(N))
4304     return false;
4305   if (LD)
4306     *LD = cast<LoadSDNode>(N);
4307   return true;
4308 }
4309
4310 // Test whether the given value is a vector value which will be legalized
4311 // into a load.
4312 static bool WillBeConstantPoolLoad(SDNode *N) {
4313   if (N->getOpcode() != ISD::BUILD_VECTOR)
4314     return false;
4315
4316   // Check for any non-constant elements.
4317   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4318     switch (N->getOperand(i).getNode()->getOpcode()) {
4319     case ISD::UNDEF:
4320     case ISD::ConstantFP:
4321     case ISD::Constant:
4322       break;
4323     default:
4324       return false;
4325     }
4326
4327   // Vectors of all-zeros and all-ones are materialized with special
4328   // instructions rather than being loaded.
4329   return !ISD::isBuildVectorAllZeros(N) &&
4330          !ISD::isBuildVectorAllOnes(N);
4331 }
4332
4333 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4334 /// match movlp{s|d}. The lower half elements should come from lower half of
4335 /// V1 (and in order), and the upper half elements should come from the upper
4336 /// half of V2 (and in order). And since V1 will become the source of the
4337 /// MOVLP, it must be either a vector load or a scalar load to vector.
4338 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4339                                ArrayRef<int> Mask, EVT VT) {
4340   if (!VT.is128BitVector())
4341     return false;
4342
4343   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4344     return false;
4345   // Is V2 is a vector load, don't do this transformation. We will try to use
4346   // load folding shufps op.
4347   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4348     return false;
4349
4350   unsigned NumElems = VT.getVectorNumElements();
4351
4352   if (NumElems != 2 && NumElems != 4)
4353     return false;
4354   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4355     if (!isUndefOrEqual(Mask[i], i))
4356       return false;
4357   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4358     if (!isUndefOrEqual(Mask[i], i+NumElems))
4359       return false;
4360   return true;
4361 }
4362
4363 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4364 /// all the same.
4365 static bool isSplatVector(SDNode *N) {
4366   if (N->getOpcode() != ISD::BUILD_VECTOR)
4367     return false;
4368
4369   SDValue SplatValue = N->getOperand(0);
4370   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4371     if (N->getOperand(i) != SplatValue)
4372       return false;
4373   return true;
4374 }
4375
4376 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4377 /// to an zero vector.
4378 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4379 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4380   SDValue V1 = N->getOperand(0);
4381   SDValue V2 = N->getOperand(1);
4382   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4383   for (unsigned i = 0; i != NumElems; ++i) {
4384     int Idx = N->getMaskElt(i);
4385     if (Idx >= (int)NumElems) {
4386       unsigned Opc = V2.getOpcode();
4387       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4388         continue;
4389       if (Opc != ISD::BUILD_VECTOR ||
4390           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4391         return false;
4392     } else if (Idx >= 0) {
4393       unsigned Opc = V1.getOpcode();
4394       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4395         continue;
4396       if (Opc != ISD::BUILD_VECTOR ||
4397           !X86::isZeroNode(V1.getOperand(Idx)))
4398         return false;
4399     }
4400   }
4401   return true;
4402 }
4403
4404 /// getZeroVector - Returns a vector of specified type with all zero elements.
4405 ///
4406 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4407                              SelectionDAG &DAG, DebugLoc dl) {
4408   assert(VT.isVector() && "Expected a vector type");
4409
4410   // Always build SSE zero vectors as <4 x i32> bitcasted
4411   // to their dest type. This ensures they get CSE'd.
4412   SDValue Vec;
4413   if (VT.is128BitVector()) {  // SSE
4414     if (Subtarget->hasSSE2()) {  // SSE2
4415       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4416       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4417     } else { // SSE1
4418       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4419       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4420     }
4421   } else if (VT.is256BitVector()) { // AVX
4422     if (Subtarget->hasInt256()) { // AVX2
4423       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4424       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4425       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4426     } else {
4427       // 256-bit logic and arithmetic instructions in AVX are all
4428       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4429       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4430       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4431       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4432     }
4433   } else
4434     llvm_unreachable("Unexpected vector type");
4435
4436   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4437 }
4438
4439 /// getOnesVector - Returns a vector of specified type with all bits set.
4440 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4441 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4442 /// Then bitcast to their original type, ensuring they get CSE'd.
4443 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4444                              DebugLoc dl) {
4445   assert(VT.isVector() && "Expected a vector type");
4446
4447   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4448   SDValue Vec;
4449   if (VT.is256BitVector()) {
4450     if (HasInt256) { // AVX2
4451       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4452       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4453     } else { // AVX
4454       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4455       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4456     }
4457   } else if (VT.is128BitVector()) {
4458     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4459   } else
4460     llvm_unreachable("Unexpected vector type");
4461
4462   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4463 }
4464
4465 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4466 /// that point to V2 points to its first element.
4467 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4468   for (unsigned i = 0; i != NumElems; ++i) {
4469     if (Mask[i] > (int)NumElems) {
4470       Mask[i] = NumElems;
4471     }
4472   }
4473 }
4474
4475 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4476 /// operation of specified width.
4477 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4478                        SDValue V2) {
4479   unsigned NumElems = VT.getVectorNumElements();
4480   SmallVector<int, 8> Mask;
4481   Mask.push_back(NumElems);
4482   for (unsigned i = 1; i != NumElems; ++i)
4483     Mask.push_back(i);
4484   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4485 }
4486
4487 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4488 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4489                           SDValue V2) {
4490   unsigned NumElems = VT.getVectorNumElements();
4491   SmallVector<int, 8> Mask;
4492   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4493     Mask.push_back(i);
4494     Mask.push_back(i + NumElems);
4495   }
4496   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4497 }
4498
4499 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4500 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4501                           SDValue V2) {
4502   unsigned NumElems = VT.getVectorNumElements();
4503   SmallVector<int, 8> Mask;
4504   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4505     Mask.push_back(i + Half);
4506     Mask.push_back(i + NumElems + Half);
4507   }
4508   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4509 }
4510
4511 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4512 // a generic shuffle instruction because the target has no such instructions.
4513 // Generate shuffles which repeat i16 and i8 several times until they can be
4514 // represented by v4f32 and then be manipulated by target suported shuffles.
4515 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4516   EVT VT = V.getValueType();
4517   int NumElems = VT.getVectorNumElements();
4518   DebugLoc dl = V.getDebugLoc();
4519
4520   while (NumElems > 4) {
4521     if (EltNo < NumElems/2) {
4522       V = getUnpackl(DAG, dl, VT, V, V);
4523     } else {
4524       V = getUnpackh(DAG, dl, VT, V, V);
4525       EltNo -= NumElems/2;
4526     }
4527     NumElems >>= 1;
4528   }
4529   return V;
4530 }
4531
4532 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4533 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4534   EVT VT = V.getValueType();
4535   DebugLoc dl = V.getDebugLoc();
4536
4537   if (VT.is128BitVector()) {
4538     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4539     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4540     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4541                              &SplatMask[0]);
4542   } else if (VT.is256BitVector()) {
4543     // To use VPERMILPS to splat scalars, the second half of indicies must
4544     // refer to the higher part, which is a duplication of the lower one,
4545     // because VPERMILPS can only handle in-lane permutations.
4546     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4547                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4548
4549     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4550     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4551                              &SplatMask[0]);
4552   } else
4553     llvm_unreachable("Vector size not supported");
4554
4555   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4556 }
4557
4558 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4559 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4560   EVT SrcVT = SV->getValueType(0);
4561   SDValue V1 = SV->getOperand(0);
4562   DebugLoc dl = SV->getDebugLoc();
4563
4564   int EltNo = SV->getSplatIndex();
4565   int NumElems = SrcVT.getVectorNumElements();
4566   bool Is256BitVec = SrcVT.is256BitVector();
4567
4568   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4569          "Unknown how to promote splat for type");
4570
4571   // Extract the 128-bit part containing the splat element and update
4572   // the splat element index when it refers to the higher register.
4573   if (Is256BitVec) {
4574     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4575     if (EltNo >= NumElems/2)
4576       EltNo -= NumElems/2;
4577   }
4578
4579   // All i16 and i8 vector types can't be used directly by a generic shuffle
4580   // instruction because the target has no such instruction. Generate shuffles
4581   // which repeat i16 and i8 several times until they fit in i32, and then can
4582   // be manipulated by target suported shuffles.
4583   EVT EltVT = SrcVT.getVectorElementType();
4584   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4585     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4586
4587   // Recreate the 256-bit vector and place the same 128-bit vector
4588   // into the low and high part. This is necessary because we want
4589   // to use VPERM* to shuffle the vectors
4590   if (Is256BitVec) {
4591     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4592   }
4593
4594   return getLegalSplat(DAG, V1, EltNo);
4595 }
4596
4597 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4598 /// vector of zero or undef vector.  This produces a shuffle where the low
4599 /// element of V2 is swizzled into the zero/undef vector, landing at element
4600 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4601 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4602                                            bool IsZero,
4603                                            const X86Subtarget *Subtarget,
4604                                            SelectionDAG &DAG) {
4605   EVT VT = V2.getValueType();
4606   SDValue V1 = IsZero
4607     ? getZeroVector(VT, Subtarget, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4608   unsigned NumElems = VT.getVectorNumElements();
4609   SmallVector<int, 16> MaskVec;
4610   for (unsigned i = 0; i != NumElems; ++i)
4611     // If this is the insertion idx, put the low elt of V2 here.
4612     MaskVec.push_back(i == Idx ? NumElems : i);
4613   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4614 }
4615
4616 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4617 /// target specific opcode. Returns true if the Mask could be calculated.
4618 /// Sets IsUnary to true if only uses one source.
4619 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4620                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4621   unsigned NumElems = VT.getVectorNumElements();
4622   SDValue ImmN;
4623
4624   IsUnary = false;
4625   switch(N->getOpcode()) {
4626   case X86ISD::SHUFP:
4627     ImmN = N->getOperand(N->getNumOperands()-1);
4628     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4629     break;
4630   case X86ISD::UNPCKH:
4631     DecodeUNPCKHMask(VT, Mask);
4632     break;
4633   case X86ISD::UNPCKL:
4634     DecodeUNPCKLMask(VT, Mask);
4635     break;
4636   case X86ISD::MOVHLPS:
4637     DecodeMOVHLPSMask(NumElems, Mask);
4638     break;
4639   case X86ISD::MOVLHPS:
4640     DecodeMOVLHPSMask(NumElems, Mask);
4641     break;
4642   case X86ISD::PALIGNR:
4643     ImmN = N->getOperand(N->getNumOperands()-1);
4644     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4645     break;
4646   case X86ISD::PSHUFD:
4647   case X86ISD::VPERMILP:
4648     ImmN = N->getOperand(N->getNumOperands()-1);
4649     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4650     IsUnary = true;
4651     break;
4652   case X86ISD::PSHUFHW:
4653     ImmN = N->getOperand(N->getNumOperands()-1);
4654     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4655     IsUnary = true;
4656     break;
4657   case X86ISD::PSHUFLW:
4658     ImmN = N->getOperand(N->getNumOperands()-1);
4659     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4660     IsUnary = true;
4661     break;
4662   case X86ISD::VPERMI:
4663     ImmN = N->getOperand(N->getNumOperands()-1);
4664     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4665     IsUnary = true;
4666     break;
4667   case X86ISD::MOVSS:
4668   case X86ISD::MOVSD: {
4669     // The index 0 always comes from the first element of the second source,
4670     // this is why MOVSS and MOVSD are used in the first place. The other
4671     // elements come from the other positions of the first source vector
4672     Mask.push_back(NumElems);
4673     for (unsigned i = 1; i != NumElems; ++i) {
4674       Mask.push_back(i);
4675     }
4676     break;
4677   }
4678   case X86ISD::VPERM2X128:
4679     ImmN = N->getOperand(N->getNumOperands()-1);
4680     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4681     if (Mask.empty()) return false;
4682     break;
4683   case X86ISD::MOVDDUP:
4684   case X86ISD::MOVLHPD:
4685   case X86ISD::MOVLPD:
4686   case X86ISD::MOVLPS:
4687   case X86ISD::MOVSHDUP:
4688   case X86ISD::MOVSLDUP:
4689     // Not yet implemented
4690     return false;
4691   default: llvm_unreachable("unknown target shuffle node");
4692   }
4693
4694   return true;
4695 }
4696
4697 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4698 /// element of the result of the vector shuffle.
4699 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4700                                    unsigned Depth) {
4701   if (Depth == 6)
4702     return SDValue();  // Limit search depth.
4703
4704   SDValue V = SDValue(N, 0);
4705   EVT VT = V.getValueType();
4706   unsigned Opcode = V.getOpcode();
4707
4708   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4709   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4710     int Elt = SV->getMaskElt(Index);
4711
4712     if (Elt < 0)
4713       return DAG.getUNDEF(VT.getVectorElementType());
4714
4715     unsigned NumElems = VT.getVectorNumElements();
4716     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4717                                          : SV->getOperand(1);
4718     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4719   }
4720
4721   // Recurse into target specific vector shuffles to find scalars.
4722   if (isTargetShuffle(Opcode)) {
4723     MVT ShufVT = V.getValueType().getSimpleVT();
4724     unsigned NumElems = ShufVT.getVectorNumElements();
4725     SmallVector<int, 16> ShuffleMask;
4726     bool IsUnary;
4727
4728     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4729       return SDValue();
4730
4731     int Elt = ShuffleMask[Index];
4732     if (Elt < 0)
4733       return DAG.getUNDEF(ShufVT.getVectorElementType());
4734
4735     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4736                                          : N->getOperand(1);
4737     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4738                                Depth+1);
4739   }
4740
4741   // Actual nodes that may contain scalar elements
4742   if (Opcode == ISD::BITCAST) {
4743     V = V.getOperand(0);
4744     EVT SrcVT = V.getValueType();
4745     unsigned NumElems = VT.getVectorNumElements();
4746
4747     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4748       return SDValue();
4749   }
4750
4751   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4752     return (Index == 0) ? V.getOperand(0)
4753                         : DAG.getUNDEF(VT.getVectorElementType());
4754
4755   if (V.getOpcode() == ISD::BUILD_VECTOR)
4756     return V.getOperand(Index);
4757
4758   return SDValue();
4759 }
4760
4761 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4762 /// shuffle operation which come from a consecutively from a zero. The
4763 /// search can start in two different directions, from left or right.
4764 static
4765 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, unsigned NumElems,
4766                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4767   unsigned i;
4768   for (i = 0; i != NumElems; ++i) {
4769     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4770     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4771     if (!(Elt.getNode() &&
4772          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4773       break;
4774   }
4775
4776   return i;
4777 }
4778
4779 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4780 /// correspond consecutively to elements from one of the vector operands,
4781 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4782 static
4783 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4784                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4785                               unsigned NumElems, unsigned &OpNum) {
4786   bool SeenV1 = false;
4787   bool SeenV2 = false;
4788
4789   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4790     int Idx = SVOp->getMaskElt(i);
4791     // Ignore undef indicies
4792     if (Idx < 0)
4793       continue;
4794
4795     if (Idx < (int)NumElems)
4796       SeenV1 = true;
4797     else
4798       SeenV2 = true;
4799
4800     // Only accept consecutive elements from the same vector
4801     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4802       return false;
4803   }
4804
4805   OpNum = SeenV1 ? 0 : 1;
4806   return true;
4807 }
4808
4809 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4810 /// logical left shift of a vector.
4811 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4812                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4813   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4814   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4815               false /* check zeros from right */, DAG);
4816   unsigned OpSrc;
4817
4818   if (!NumZeros)
4819     return false;
4820
4821   // Considering the elements in the mask that are not consecutive zeros,
4822   // check if they consecutively come from only one of the source vectors.
4823   //
4824   //               V1 = {X, A, B, C}     0
4825   //                         \  \  \    /
4826   //   vector_shuffle V1, V2 <1, 2, 3, X>
4827   //
4828   if (!isShuffleMaskConsecutive(SVOp,
4829             0,                   // Mask Start Index
4830             NumElems-NumZeros,   // Mask End Index(exclusive)
4831             NumZeros,            // Where to start looking in the src vector
4832             NumElems,            // Number of elements in vector
4833             OpSrc))              // Which source operand ?
4834     return false;
4835
4836   isLeft = false;
4837   ShAmt = NumZeros;
4838   ShVal = SVOp->getOperand(OpSrc);
4839   return true;
4840 }
4841
4842 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4843 /// logical left shift of a vector.
4844 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4845                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4846   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4847   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4848               true /* check zeros from left */, DAG);
4849   unsigned OpSrc;
4850
4851   if (!NumZeros)
4852     return false;
4853
4854   // Considering the elements in the mask that are not consecutive zeros,
4855   // check if they consecutively come from only one of the source vectors.
4856   //
4857   //                           0    { A, B, X, X } = V2
4858   //                          / \    /  /
4859   //   vector_shuffle V1, V2 <X, X, 4, 5>
4860   //
4861   if (!isShuffleMaskConsecutive(SVOp,
4862             NumZeros,     // Mask Start Index
4863             NumElems,     // Mask End Index(exclusive)
4864             0,            // Where to start looking in the src vector
4865             NumElems,     // Number of elements in vector
4866             OpSrc))       // Which source operand ?
4867     return false;
4868
4869   isLeft = true;
4870   ShAmt = NumZeros;
4871   ShVal = SVOp->getOperand(OpSrc);
4872   return true;
4873 }
4874
4875 /// isVectorShift - Returns true if the shuffle can be implemented as a
4876 /// logical left or right shift of a vector.
4877 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4878                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4879   // Although the logic below support any bitwidth size, there are no
4880   // shift instructions which handle more than 128-bit vectors.
4881   if (!SVOp->getValueType(0).is128BitVector())
4882     return false;
4883
4884   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4885       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4886     return true;
4887
4888   return false;
4889 }
4890
4891 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4892 ///
4893 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4894                                        unsigned NumNonZero, unsigned NumZero,
4895                                        SelectionDAG &DAG,
4896                                        const X86Subtarget* Subtarget,
4897                                        const TargetLowering &TLI) {
4898   if (NumNonZero > 8)
4899     return SDValue();
4900
4901   DebugLoc dl = Op.getDebugLoc();
4902   SDValue V(0, 0);
4903   bool First = true;
4904   for (unsigned i = 0; i < 16; ++i) {
4905     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4906     if (ThisIsNonZero && First) {
4907       if (NumZero)
4908         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4909       else
4910         V = DAG.getUNDEF(MVT::v8i16);
4911       First = false;
4912     }
4913
4914     if ((i & 1) != 0) {
4915       SDValue ThisElt(0, 0), LastElt(0, 0);
4916       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4917       if (LastIsNonZero) {
4918         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4919                               MVT::i16, Op.getOperand(i-1));
4920       }
4921       if (ThisIsNonZero) {
4922         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4923         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4924                               ThisElt, DAG.getConstant(8, MVT::i8));
4925         if (LastIsNonZero)
4926           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4927       } else
4928         ThisElt = LastElt;
4929
4930       if (ThisElt.getNode())
4931         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4932                         DAG.getIntPtrConstant(i/2));
4933     }
4934   }
4935
4936   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4937 }
4938
4939 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4940 ///
4941 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4942                                      unsigned NumNonZero, unsigned NumZero,
4943                                      SelectionDAG &DAG,
4944                                      const X86Subtarget* Subtarget,
4945                                      const TargetLowering &TLI) {
4946   if (NumNonZero > 4)
4947     return SDValue();
4948
4949   DebugLoc dl = Op.getDebugLoc();
4950   SDValue V(0, 0);
4951   bool First = true;
4952   for (unsigned i = 0; i < 8; ++i) {
4953     bool isNonZero = (NonZeros & (1 << i)) != 0;
4954     if (isNonZero) {
4955       if (First) {
4956         if (NumZero)
4957           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4958         else
4959           V = DAG.getUNDEF(MVT::v8i16);
4960         First = false;
4961       }
4962       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4963                       MVT::v8i16, V, Op.getOperand(i),
4964                       DAG.getIntPtrConstant(i));
4965     }
4966   }
4967
4968   return V;
4969 }
4970
4971 /// getVShift - Return a vector logical shift node.
4972 ///
4973 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4974                          unsigned NumBits, SelectionDAG &DAG,
4975                          const TargetLowering &TLI, DebugLoc dl) {
4976   assert(VT.is128BitVector() && "Unknown type for VShift");
4977   EVT ShVT = MVT::v2i64;
4978   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4979   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4980   return DAG.getNode(ISD::BITCAST, dl, VT,
4981                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4982                              DAG.getConstant(NumBits,
4983                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4984 }
4985
4986 SDValue
4987 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4988                                           SelectionDAG &DAG) const {
4989
4990   // Check if the scalar load can be widened into a vector load. And if
4991   // the address is "base + cst" see if the cst can be "absorbed" into
4992   // the shuffle mask.
4993   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4994     SDValue Ptr = LD->getBasePtr();
4995     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4996       return SDValue();
4997     EVT PVT = LD->getValueType(0);
4998     if (PVT != MVT::i32 && PVT != MVT::f32)
4999       return SDValue();
5000
5001     int FI = -1;
5002     int64_t Offset = 0;
5003     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5004       FI = FINode->getIndex();
5005       Offset = 0;
5006     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5007                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5008       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5009       Offset = Ptr.getConstantOperandVal(1);
5010       Ptr = Ptr.getOperand(0);
5011     } else {
5012       return SDValue();
5013     }
5014
5015     // FIXME: 256-bit vector instructions don't require a strict alignment,
5016     // improve this code to support it better.
5017     unsigned RequiredAlign = VT.getSizeInBits()/8;
5018     SDValue Chain = LD->getChain();
5019     // Make sure the stack object alignment is at least 16 or 32.
5020     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5021     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5022       if (MFI->isFixedObjectIndex(FI)) {
5023         // Can't change the alignment. FIXME: It's possible to compute
5024         // the exact stack offset and reference FI + adjust offset instead.
5025         // If someone *really* cares about this. That's the way to implement it.
5026         return SDValue();
5027       } else {
5028         MFI->setObjectAlignment(FI, RequiredAlign);
5029       }
5030     }
5031
5032     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5033     // Ptr + (Offset & ~15).
5034     if (Offset < 0)
5035       return SDValue();
5036     if ((Offset % RequiredAlign) & 3)
5037       return SDValue();
5038     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5039     if (StartOffset)
5040       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5041                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5042
5043     int EltNo = (Offset - StartOffset) >> 2;
5044     unsigned NumElems = VT.getVectorNumElements();
5045
5046     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5047     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5048                              LD->getPointerInfo().getWithOffset(StartOffset),
5049                              false, false, false, 0);
5050
5051     SmallVector<int, 8> Mask;
5052     for (unsigned i = 0; i != NumElems; ++i)
5053       Mask.push_back(EltNo);
5054
5055     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5056   }
5057
5058   return SDValue();
5059 }
5060
5061 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5062 /// vector of type 'VT', see if the elements can be replaced by a single large
5063 /// load which has the same value as a build_vector whose operands are 'elts'.
5064 ///
5065 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5066 ///
5067 /// FIXME: we'd also like to handle the case where the last elements are zero
5068 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5069 /// There's even a handy isZeroNode for that purpose.
5070 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5071                                         DebugLoc &DL, SelectionDAG &DAG) {
5072   EVT EltVT = VT.getVectorElementType();
5073   unsigned NumElems = Elts.size();
5074
5075   LoadSDNode *LDBase = NULL;
5076   unsigned LastLoadedElt = -1U;
5077
5078   // For each element in the initializer, see if we've found a load or an undef.
5079   // If we don't find an initial load element, or later load elements are
5080   // non-consecutive, bail out.
5081   for (unsigned i = 0; i < NumElems; ++i) {
5082     SDValue Elt = Elts[i];
5083
5084     if (!Elt.getNode() ||
5085         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5086       return SDValue();
5087     if (!LDBase) {
5088       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5089         return SDValue();
5090       LDBase = cast<LoadSDNode>(Elt.getNode());
5091       LastLoadedElt = i;
5092       continue;
5093     }
5094     if (Elt.getOpcode() == ISD::UNDEF)
5095       continue;
5096
5097     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5098     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5099       return SDValue();
5100     LastLoadedElt = i;
5101   }
5102
5103   // If we have found an entire vector of loads and undefs, then return a large
5104   // load of the entire vector width starting at the base pointer.  If we found
5105   // consecutive loads for the low half, generate a vzext_load node.
5106   if (LastLoadedElt == NumElems - 1) {
5107     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5108       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5109                          LDBase->getPointerInfo(),
5110                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5111                          LDBase->isInvariant(), 0);
5112     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5113                        LDBase->getPointerInfo(),
5114                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5115                        LDBase->isInvariant(), LDBase->getAlignment());
5116   }
5117   if (NumElems == 4 && LastLoadedElt == 1 &&
5118       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5119     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5120     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5121     SDValue ResNode =
5122         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5123                                 LDBase->getPointerInfo(),
5124                                 LDBase->getAlignment(),
5125                                 false/*isVolatile*/, true/*ReadMem*/,
5126                                 false/*WriteMem*/);
5127
5128     // Make sure the newly-created LOAD is in the same position as LDBase in
5129     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5130     // update uses of LDBase's output chain to use the TokenFactor.
5131     if (LDBase->hasAnyUseOfValue(1)) {
5132       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5133                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5134       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5135       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5136                              SDValue(ResNode.getNode(), 1));
5137     }
5138
5139     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5140   }
5141   return SDValue();
5142 }
5143
5144 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5145 /// to generate a splat value for the following cases:
5146 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5147 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5148 /// a scalar load, or a constant.
5149 /// The VBROADCAST node is returned when a pattern is found,
5150 /// or SDValue() otherwise.
5151 SDValue
5152 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5153   if (!Subtarget->hasFp256())
5154     return SDValue();
5155
5156   MVT VT = Op.getValueType().getSimpleVT();
5157   DebugLoc dl = Op.getDebugLoc();
5158
5159   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5160          "Unsupported vector type for broadcast.");
5161
5162   SDValue Ld;
5163   bool ConstSplatVal;
5164
5165   switch (Op.getOpcode()) {
5166     default:
5167       // Unknown pattern found.
5168       return SDValue();
5169
5170     case ISD::BUILD_VECTOR: {
5171       // The BUILD_VECTOR node must be a splat.
5172       if (!isSplatVector(Op.getNode()))
5173         return SDValue();
5174
5175       Ld = Op.getOperand(0);
5176       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5177                      Ld.getOpcode() == ISD::ConstantFP);
5178
5179       // The suspected load node has several users. Make sure that all
5180       // of its users are from the BUILD_VECTOR node.
5181       // Constants may have multiple users.
5182       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5183         return SDValue();
5184       break;
5185     }
5186
5187     case ISD::VECTOR_SHUFFLE: {
5188       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5189
5190       // Shuffles must have a splat mask where the first element is
5191       // broadcasted.
5192       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5193         return SDValue();
5194
5195       SDValue Sc = Op.getOperand(0);
5196       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5197           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5198
5199         if (!Subtarget->hasInt256())
5200           return SDValue();
5201
5202         // Use the register form of the broadcast instruction available on AVX2.
5203         if (VT.is256BitVector())
5204           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5205         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5206       }
5207
5208       Ld = Sc.getOperand(0);
5209       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5210                        Ld.getOpcode() == ISD::ConstantFP);
5211
5212       // The scalar_to_vector node and the suspected
5213       // load node must have exactly one user.
5214       // Constants may have multiple users.
5215       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5216         return SDValue();
5217       break;
5218     }
5219   }
5220
5221   bool Is256 = VT.is256BitVector();
5222
5223   // Handle the broadcasting a single constant scalar from the constant pool
5224   // into a vector. On Sandybridge it is still better to load a constant vector
5225   // from the constant pool and not to broadcast it from a scalar.
5226   if (ConstSplatVal && Subtarget->hasInt256()) {
5227     EVT CVT = Ld.getValueType();
5228     assert(!CVT.isVector() && "Must not broadcast a vector type");
5229     unsigned ScalarSize = CVT.getSizeInBits();
5230
5231     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5232       const Constant *C = 0;
5233       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5234         C = CI->getConstantIntValue();
5235       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5236         C = CF->getConstantFPValue();
5237
5238       assert(C && "Invalid constant type");
5239
5240       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5241       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5242       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5243                        MachinePointerInfo::getConstantPool(),
5244                        false, false, false, Alignment);
5245
5246       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5247     }
5248   }
5249
5250   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5251   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5252
5253   // Handle AVX2 in-register broadcasts.
5254   if (!IsLoad && Subtarget->hasInt256() &&
5255       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5256     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5257
5258   // The scalar source must be a normal load.
5259   if (!IsLoad)
5260     return SDValue();
5261
5262   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5263     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5264
5265   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5266   // double since there is no vbroadcastsd xmm
5267   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5268     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5269       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5270   }
5271
5272   // Unsupported broadcast.
5273   return SDValue();
5274 }
5275
5276 SDValue
5277 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5278   EVT VT = Op.getValueType();
5279
5280   // Skip if insert_vec_elt is not supported.
5281   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5282     return SDValue();
5283
5284   DebugLoc DL = Op.getDebugLoc();
5285   unsigned NumElems = Op.getNumOperands();
5286
5287   SDValue VecIn1;
5288   SDValue VecIn2;
5289   SmallVector<unsigned, 4> InsertIndices;
5290   SmallVector<int, 8> Mask(NumElems, -1);
5291
5292   for (unsigned i = 0; i != NumElems; ++i) {
5293     unsigned Opc = Op.getOperand(i).getOpcode();
5294
5295     if (Opc == ISD::UNDEF)
5296       continue;
5297
5298     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5299       // Quit if more than 1 elements need inserting.
5300       if (InsertIndices.size() > 1)
5301         return SDValue();
5302
5303       InsertIndices.push_back(i);
5304       continue;
5305     }
5306
5307     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5308     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5309
5310     // Quit if extracted from vector of different type.
5311     if (ExtractedFromVec.getValueType() != VT)
5312       return SDValue();
5313
5314     // Quit if non-constant index.
5315     if (!isa<ConstantSDNode>(ExtIdx))
5316       return SDValue();
5317
5318     if (VecIn1.getNode() == 0)
5319       VecIn1 = ExtractedFromVec;
5320     else if (VecIn1 != ExtractedFromVec) {
5321       if (VecIn2.getNode() == 0)
5322         VecIn2 = ExtractedFromVec;
5323       else if (VecIn2 != ExtractedFromVec)
5324         // Quit if more than 2 vectors to shuffle
5325         return SDValue();
5326     }
5327
5328     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5329
5330     if (ExtractedFromVec == VecIn1)
5331       Mask[i] = Idx;
5332     else if (ExtractedFromVec == VecIn2)
5333       Mask[i] = Idx + NumElems;
5334   }
5335
5336   if (VecIn1.getNode() == 0)
5337     return SDValue();
5338
5339   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5340   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5341   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5342     unsigned Idx = InsertIndices[i];
5343     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5344                      DAG.getIntPtrConstant(Idx));
5345   }
5346
5347   return NV;
5348 }
5349
5350 SDValue
5351 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5352   DebugLoc dl = Op.getDebugLoc();
5353
5354   MVT VT = Op.getValueType().getSimpleVT();
5355   MVT ExtVT = VT.getVectorElementType();
5356   unsigned NumElems = Op.getNumOperands();
5357
5358   // Vectors containing all zeros can be matched by pxor and xorps later
5359   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5360     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5361     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5362     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5363       return Op;
5364
5365     return getZeroVector(VT, Subtarget, DAG, dl);
5366   }
5367
5368   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5369   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5370   // vpcmpeqd on 256-bit vectors.
5371   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5372     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5373       return Op;
5374
5375     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5376   }
5377
5378   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5379   if (Broadcast.getNode())
5380     return Broadcast;
5381
5382   unsigned EVTBits = ExtVT.getSizeInBits();
5383
5384   unsigned NumZero  = 0;
5385   unsigned NumNonZero = 0;
5386   unsigned NonZeros = 0;
5387   bool IsAllConstants = true;
5388   SmallSet<SDValue, 8> Values;
5389   for (unsigned i = 0; i < NumElems; ++i) {
5390     SDValue Elt = Op.getOperand(i);
5391     if (Elt.getOpcode() == ISD::UNDEF)
5392       continue;
5393     Values.insert(Elt);
5394     if (Elt.getOpcode() != ISD::Constant &&
5395         Elt.getOpcode() != ISD::ConstantFP)
5396       IsAllConstants = false;
5397     if (X86::isZeroNode(Elt))
5398       NumZero++;
5399     else {
5400       NonZeros |= (1 << i);
5401       NumNonZero++;
5402     }
5403   }
5404
5405   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5406   if (NumNonZero == 0)
5407     return DAG.getUNDEF(VT);
5408
5409   // Special case for single non-zero, non-undef, element.
5410   if (NumNonZero == 1) {
5411     unsigned Idx = CountTrailingZeros_32(NonZeros);
5412     SDValue Item = Op.getOperand(Idx);
5413
5414     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5415     // the value are obviously zero, truncate the value to i32 and do the
5416     // insertion that way.  Only do this if the value is non-constant or if the
5417     // value is a constant being inserted into element 0.  It is cheaper to do
5418     // a constant pool load than it is to do a movd + shuffle.
5419     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5420         (!IsAllConstants || Idx == 0)) {
5421       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5422         // Handle SSE only.
5423         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5424         EVT VecVT = MVT::v4i32;
5425         unsigned VecElts = 4;
5426
5427         // Truncate the value (which may itself be a constant) to i32, and
5428         // convert it to a vector with movd (S2V+shuffle to zero extend).
5429         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5430         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5431         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5432
5433         // Now we have our 32-bit value zero extended in the low element of
5434         // a vector.  If Idx != 0, swizzle it into place.
5435         if (Idx != 0) {
5436           SmallVector<int, 4> Mask;
5437           Mask.push_back(Idx);
5438           for (unsigned i = 1; i != VecElts; ++i)
5439             Mask.push_back(i);
5440           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5441                                       &Mask[0]);
5442         }
5443         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5444       }
5445     }
5446
5447     // If we have a constant or non-constant insertion into the low element of
5448     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5449     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5450     // depending on what the source datatype is.
5451     if (Idx == 0) {
5452       if (NumZero == 0)
5453         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5454
5455       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5456           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5457         if (VT.is256BitVector()) {
5458           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5459           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5460                              Item, DAG.getIntPtrConstant(0));
5461         }
5462         assert(VT.is128BitVector() && "Expected an SSE value type!");
5463         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5464         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5465         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5466       }
5467
5468       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5469         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5470         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5471         if (VT.is256BitVector()) {
5472           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5473           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5474         } else {
5475           assert(VT.is128BitVector() && "Expected an SSE value type!");
5476           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5477         }
5478         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5479       }
5480     }
5481
5482     // Is it a vector logical left shift?
5483     if (NumElems == 2 && Idx == 1 &&
5484         X86::isZeroNode(Op.getOperand(0)) &&
5485         !X86::isZeroNode(Op.getOperand(1))) {
5486       unsigned NumBits = VT.getSizeInBits();
5487       return getVShift(true, VT,
5488                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5489                                    VT, Op.getOperand(1)),
5490                        NumBits/2, DAG, *this, dl);
5491     }
5492
5493     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5494       return SDValue();
5495
5496     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5497     // is a non-constant being inserted into an element other than the low one,
5498     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5499     // movd/movss) to move this into the low element, then shuffle it into
5500     // place.
5501     if (EVTBits == 32) {
5502       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5503
5504       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5505       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5506       SmallVector<int, 8> MaskVec;
5507       for (unsigned i = 0; i != NumElems; ++i)
5508         MaskVec.push_back(i == Idx ? 0 : 1);
5509       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5510     }
5511   }
5512
5513   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5514   if (Values.size() == 1) {
5515     if (EVTBits == 32) {
5516       // Instead of a shuffle like this:
5517       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5518       // Check if it's possible to issue this instead.
5519       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5520       unsigned Idx = CountTrailingZeros_32(NonZeros);
5521       SDValue Item = Op.getOperand(Idx);
5522       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5523         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5524     }
5525     return SDValue();
5526   }
5527
5528   // A vector full of immediates; various special cases are already
5529   // handled, so this is best done with a single constant-pool load.
5530   if (IsAllConstants)
5531     return SDValue();
5532
5533   // For AVX-length vectors, build the individual 128-bit pieces and use
5534   // shuffles to put them in place.
5535   if (VT.is256BitVector()) {
5536     SmallVector<SDValue, 32> V;
5537     for (unsigned i = 0; i != NumElems; ++i)
5538       V.push_back(Op.getOperand(i));
5539
5540     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5541
5542     // Build both the lower and upper subvector.
5543     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5544     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5545                                 NumElems/2);
5546
5547     // Recreate the wider vector with the lower and upper part.
5548     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5549   }
5550
5551   // Let legalizer expand 2-wide build_vectors.
5552   if (EVTBits == 64) {
5553     if (NumNonZero == 1) {
5554       // One half is zero or undef.
5555       unsigned Idx = CountTrailingZeros_32(NonZeros);
5556       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5557                                  Op.getOperand(Idx));
5558       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5559     }
5560     return SDValue();
5561   }
5562
5563   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5564   if (EVTBits == 8 && NumElems == 16) {
5565     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5566                                         Subtarget, *this);
5567     if (V.getNode()) return V;
5568   }
5569
5570   if (EVTBits == 16 && NumElems == 8) {
5571     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5572                                       Subtarget, *this);
5573     if (V.getNode()) return V;
5574   }
5575
5576   // If element VT is == 32 bits, turn it into a number of shuffles.
5577   SmallVector<SDValue, 8> V(NumElems);
5578   if (NumElems == 4 && NumZero > 0) {
5579     for (unsigned i = 0; i < 4; ++i) {
5580       bool isZero = !(NonZeros & (1 << i));
5581       if (isZero)
5582         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5583       else
5584         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5585     }
5586
5587     for (unsigned i = 0; i < 2; ++i) {
5588       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5589         default: break;
5590         case 0:
5591           V[i] = V[i*2];  // Must be a zero vector.
5592           break;
5593         case 1:
5594           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5595           break;
5596         case 2:
5597           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5598           break;
5599         case 3:
5600           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5601           break;
5602       }
5603     }
5604
5605     bool Reverse1 = (NonZeros & 0x3) == 2;
5606     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5607     int MaskVec[] = {
5608       Reverse1 ? 1 : 0,
5609       Reverse1 ? 0 : 1,
5610       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5611       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5612     };
5613     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5614   }
5615
5616   if (Values.size() > 1 && VT.is128BitVector()) {
5617     // Check for a build vector of consecutive loads.
5618     for (unsigned i = 0; i < NumElems; ++i)
5619       V[i] = Op.getOperand(i);
5620
5621     // Check for elements which are consecutive loads.
5622     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5623     if (LD.getNode())
5624       return LD;
5625
5626     // Check for a build vector from mostly shuffle plus few inserting.
5627     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5628     if (Sh.getNode())
5629       return Sh;
5630
5631     // For SSE 4.1, use insertps to put the high elements into the low element.
5632     if (getSubtarget()->hasSSE41()) {
5633       SDValue Result;
5634       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5635         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5636       else
5637         Result = DAG.getUNDEF(VT);
5638
5639       for (unsigned i = 1; i < NumElems; ++i) {
5640         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5641         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5642                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5643       }
5644       return Result;
5645     }
5646
5647     // Otherwise, expand into a number of unpckl*, start by extending each of
5648     // our (non-undef) elements to the full vector width with the element in the
5649     // bottom slot of the vector (which generates no code for SSE).
5650     for (unsigned i = 0; i < NumElems; ++i) {
5651       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5652         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5653       else
5654         V[i] = DAG.getUNDEF(VT);
5655     }
5656
5657     // Next, we iteratively mix elements, e.g. for v4f32:
5658     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5659     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5660     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5661     unsigned EltStride = NumElems >> 1;
5662     while (EltStride != 0) {
5663       for (unsigned i = 0; i < EltStride; ++i) {
5664         // If V[i+EltStride] is undef and this is the first round of mixing,
5665         // then it is safe to just drop this shuffle: V[i] is already in the
5666         // right place, the one element (since it's the first round) being
5667         // inserted as undef can be dropped.  This isn't safe for successive
5668         // rounds because they will permute elements within both vectors.
5669         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5670             EltStride == NumElems/2)
5671           continue;
5672
5673         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5674       }
5675       EltStride >>= 1;
5676     }
5677     return V[0];
5678   }
5679   return SDValue();
5680 }
5681
5682 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5683 // to create 256-bit vectors from two other 128-bit ones.
5684 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5685   DebugLoc dl = Op.getDebugLoc();
5686   MVT ResVT = Op.getValueType().getSimpleVT();
5687
5688   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5689
5690   SDValue V1 = Op.getOperand(0);
5691   SDValue V2 = Op.getOperand(1);
5692   unsigned NumElems = ResVT.getVectorNumElements();
5693
5694   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5695 }
5696
5697 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5698   assert(Op.getNumOperands() == 2);
5699
5700   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5701   // from two other 128-bit ones.
5702   return LowerAVXCONCAT_VECTORS(Op, DAG);
5703 }
5704
5705 // Try to lower a shuffle node into a simple blend instruction.
5706 static SDValue
5707 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5708                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5709   SDValue V1 = SVOp->getOperand(0);
5710   SDValue V2 = SVOp->getOperand(1);
5711   DebugLoc dl = SVOp->getDebugLoc();
5712   MVT VT = SVOp->getValueType(0).getSimpleVT();
5713   MVT EltVT = VT.getVectorElementType();
5714   unsigned NumElems = VT.getVectorNumElements();
5715
5716   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5717     return SDValue();
5718   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5719     return SDValue();
5720
5721   // Check the mask for BLEND and build the value.
5722   unsigned MaskValue = 0;
5723   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5724   unsigned NumLanes = (NumElems-1)/8 + 1;
5725   unsigned NumElemsInLane = NumElems / NumLanes;
5726
5727   // Blend for v16i16 should be symetric for the both lanes.
5728   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5729
5730     int SndLaneEltIdx = (NumLanes == 2) ?
5731       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5732     int EltIdx = SVOp->getMaskElt(i);
5733
5734     if ((EltIdx < 0 || EltIdx == (int)i) &&
5735         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5736       continue;
5737
5738     if (((unsigned)EltIdx == (i + NumElems)) &&
5739         (SndLaneEltIdx < 0 ||
5740          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5741       MaskValue |= (1<<i);
5742     else
5743       return SDValue();
5744   }
5745
5746   // Convert i32 vectors to floating point if it is not AVX2.
5747   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5748   MVT BlendVT = VT;
5749   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5750     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5751                                NumElems);
5752     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5753     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5754   }
5755
5756   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5757                             DAG.getConstant(MaskValue, MVT::i32));
5758   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5759 }
5760
5761 // v8i16 shuffles - Prefer shuffles in the following order:
5762 // 1. [all]   pshuflw, pshufhw, optional move
5763 // 2. [ssse3] 1 x pshufb
5764 // 3. [ssse3] 2 x pshufb + 1 x por
5765 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5766 static SDValue
5767 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5768                          SelectionDAG &DAG) {
5769   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5770   SDValue V1 = SVOp->getOperand(0);
5771   SDValue V2 = SVOp->getOperand(1);
5772   DebugLoc dl = SVOp->getDebugLoc();
5773   SmallVector<int, 8> MaskVals;
5774
5775   // Determine if more than 1 of the words in each of the low and high quadwords
5776   // of the result come from the same quadword of one of the two inputs.  Undef
5777   // mask values count as coming from any quadword, for better codegen.
5778   unsigned LoQuad[] = { 0, 0, 0, 0 };
5779   unsigned HiQuad[] = { 0, 0, 0, 0 };
5780   std::bitset<4> InputQuads;
5781   for (unsigned i = 0; i < 8; ++i) {
5782     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5783     int EltIdx = SVOp->getMaskElt(i);
5784     MaskVals.push_back(EltIdx);
5785     if (EltIdx < 0) {
5786       ++Quad[0];
5787       ++Quad[1];
5788       ++Quad[2];
5789       ++Quad[3];
5790       continue;
5791     }
5792     ++Quad[EltIdx / 4];
5793     InputQuads.set(EltIdx / 4);
5794   }
5795
5796   int BestLoQuad = -1;
5797   unsigned MaxQuad = 1;
5798   for (unsigned i = 0; i < 4; ++i) {
5799     if (LoQuad[i] > MaxQuad) {
5800       BestLoQuad = i;
5801       MaxQuad = LoQuad[i];
5802     }
5803   }
5804
5805   int BestHiQuad = -1;
5806   MaxQuad = 1;
5807   for (unsigned i = 0; i < 4; ++i) {
5808     if (HiQuad[i] > MaxQuad) {
5809       BestHiQuad = i;
5810       MaxQuad = HiQuad[i];
5811     }
5812   }
5813
5814   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5815   // of the two input vectors, shuffle them into one input vector so only a
5816   // single pshufb instruction is necessary. If There are more than 2 input
5817   // quads, disable the next transformation since it does not help SSSE3.
5818   bool V1Used = InputQuads[0] || InputQuads[1];
5819   bool V2Used = InputQuads[2] || InputQuads[3];
5820   if (Subtarget->hasSSSE3()) {
5821     if (InputQuads.count() == 2 && V1Used && V2Used) {
5822       BestLoQuad = InputQuads[0] ? 0 : 1;
5823       BestHiQuad = InputQuads[2] ? 2 : 3;
5824     }
5825     if (InputQuads.count() > 2) {
5826       BestLoQuad = -1;
5827       BestHiQuad = -1;
5828     }
5829   }
5830
5831   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5832   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5833   // words from all 4 input quadwords.
5834   SDValue NewV;
5835   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5836     int MaskV[] = {
5837       BestLoQuad < 0 ? 0 : BestLoQuad,
5838       BestHiQuad < 0 ? 1 : BestHiQuad
5839     };
5840     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5841                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5842                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5843     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5844
5845     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5846     // source words for the shuffle, to aid later transformations.
5847     bool AllWordsInNewV = true;
5848     bool InOrder[2] = { true, true };
5849     for (unsigned i = 0; i != 8; ++i) {
5850       int idx = MaskVals[i];
5851       if (idx != (int)i)
5852         InOrder[i/4] = false;
5853       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5854         continue;
5855       AllWordsInNewV = false;
5856       break;
5857     }
5858
5859     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5860     if (AllWordsInNewV) {
5861       for (int i = 0; i != 8; ++i) {
5862         int idx = MaskVals[i];
5863         if (idx < 0)
5864           continue;
5865         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5866         if ((idx != i) && idx < 4)
5867           pshufhw = false;
5868         if ((idx != i) && idx > 3)
5869           pshuflw = false;
5870       }
5871       V1 = NewV;
5872       V2Used = false;
5873       BestLoQuad = 0;
5874       BestHiQuad = 1;
5875     }
5876
5877     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5878     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5879     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5880       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5881       unsigned TargetMask = 0;
5882       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5883                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5884       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5885       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5886                              getShufflePSHUFLWImmediate(SVOp);
5887       V1 = NewV.getOperand(0);
5888       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5889     }
5890   }
5891
5892   // Promote splats to a larger type which usually leads to more efficient code.
5893   // FIXME: Is this true if pshufb is available?
5894   if (SVOp->isSplat())
5895     return PromoteSplat(SVOp, DAG);
5896
5897   // If we have SSSE3, and all words of the result are from 1 input vector,
5898   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5899   // is present, fall back to case 4.
5900   if (Subtarget->hasSSSE3()) {
5901     SmallVector<SDValue,16> pshufbMask;
5902
5903     // If we have elements from both input vectors, set the high bit of the
5904     // shuffle mask element to zero out elements that come from V2 in the V1
5905     // mask, and elements that come from V1 in the V2 mask, so that the two
5906     // results can be OR'd together.
5907     bool TwoInputs = V1Used && V2Used;
5908     for (unsigned i = 0; i != 8; ++i) {
5909       int EltIdx = MaskVals[i] * 2;
5910       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5911       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5912       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5913       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5914     }
5915     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5916     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5917                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5918                                  MVT::v16i8, &pshufbMask[0], 16));
5919     if (!TwoInputs)
5920       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5921
5922     // Calculate the shuffle mask for the second input, shuffle it, and
5923     // OR it with the first shuffled input.
5924     pshufbMask.clear();
5925     for (unsigned i = 0; i != 8; ++i) {
5926       int EltIdx = MaskVals[i] * 2;
5927       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5928       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5929       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5930       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5931     }
5932     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5933     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5934                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5935                                  MVT::v16i8, &pshufbMask[0], 16));
5936     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5937     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5938   }
5939
5940   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5941   // and update MaskVals with new element order.
5942   std::bitset<8> InOrder;
5943   if (BestLoQuad >= 0) {
5944     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5945     for (int i = 0; i != 4; ++i) {
5946       int idx = MaskVals[i];
5947       if (idx < 0) {
5948         InOrder.set(i);
5949       } else if ((idx / 4) == BestLoQuad) {
5950         MaskV[i] = idx & 3;
5951         InOrder.set(i);
5952       }
5953     }
5954     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5955                                 &MaskV[0]);
5956
5957     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5958       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5959       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5960                                   NewV.getOperand(0),
5961                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5962     }
5963   }
5964
5965   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5966   // and update MaskVals with the new element order.
5967   if (BestHiQuad >= 0) {
5968     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5969     for (unsigned i = 4; i != 8; ++i) {
5970       int idx = MaskVals[i];
5971       if (idx < 0) {
5972         InOrder.set(i);
5973       } else if ((idx / 4) == BestHiQuad) {
5974         MaskV[i] = (idx & 3) + 4;
5975         InOrder.set(i);
5976       }
5977     }
5978     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5979                                 &MaskV[0]);
5980
5981     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5982       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5983       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5984                                   NewV.getOperand(0),
5985                                   getShufflePSHUFHWImmediate(SVOp), DAG);
5986     }
5987   }
5988
5989   // In case BestHi & BestLo were both -1, which means each quadword has a word
5990   // from each of the four input quadwords, calculate the InOrder bitvector now
5991   // before falling through to the insert/extract cleanup.
5992   if (BestLoQuad == -1 && BestHiQuad == -1) {
5993     NewV = V1;
5994     for (int i = 0; i != 8; ++i)
5995       if (MaskVals[i] < 0 || MaskVals[i] == i)
5996         InOrder.set(i);
5997   }
5998
5999   // The other elements are put in the right place using pextrw and pinsrw.
6000   for (unsigned i = 0; i != 8; ++i) {
6001     if (InOrder[i])
6002       continue;
6003     int EltIdx = MaskVals[i];
6004     if (EltIdx < 0)
6005       continue;
6006     SDValue ExtOp = (EltIdx < 8) ?
6007       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6008                   DAG.getIntPtrConstant(EltIdx)) :
6009       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6010                   DAG.getIntPtrConstant(EltIdx - 8));
6011     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6012                        DAG.getIntPtrConstant(i));
6013   }
6014   return NewV;
6015 }
6016
6017 // v16i8 shuffles - Prefer shuffles in the following order:
6018 // 1. [ssse3] 1 x pshufb
6019 // 2. [ssse3] 2 x pshufb + 1 x por
6020 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6021 static
6022 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6023                                  SelectionDAG &DAG,
6024                                  const X86TargetLowering &TLI) {
6025   SDValue V1 = SVOp->getOperand(0);
6026   SDValue V2 = SVOp->getOperand(1);
6027   DebugLoc dl = SVOp->getDebugLoc();
6028   ArrayRef<int> MaskVals = SVOp->getMask();
6029
6030   // Promote splats to a larger type which usually leads to more efficient code.
6031   // FIXME: Is this true if pshufb is available?
6032   if (SVOp->isSplat())
6033     return PromoteSplat(SVOp, DAG);
6034
6035   // If we have SSSE3, case 1 is generated when all result bytes come from
6036   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6037   // present, fall back to case 3.
6038
6039   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6040   if (TLI.getSubtarget()->hasSSSE3()) {
6041     SmallVector<SDValue,16> pshufbMask;
6042
6043     // If all result elements are from one input vector, then only translate
6044     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6045     //
6046     // Otherwise, we have elements from both input vectors, and must zero out
6047     // elements that come from V2 in the first mask, and V1 in the second mask
6048     // so that we can OR them together.
6049     for (unsigned i = 0; i != 16; ++i) {
6050       int EltIdx = MaskVals[i];
6051       if (EltIdx < 0 || EltIdx >= 16)
6052         EltIdx = 0x80;
6053       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6054     }
6055     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6056                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6057                                  MVT::v16i8, &pshufbMask[0], 16));
6058
6059     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6060     // the 2nd operand if it's undefined or zero.
6061     if (V2.getOpcode() == ISD::UNDEF ||
6062         ISD::isBuildVectorAllZeros(V2.getNode()))
6063       return V1;
6064
6065     // Calculate the shuffle mask for the second input, shuffle it, and
6066     // OR it with the first shuffled input.
6067     pshufbMask.clear();
6068     for (unsigned i = 0; i != 16; ++i) {
6069       int EltIdx = MaskVals[i];
6070       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6071       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6072     }
6073     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6074                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6075                                  MVT::v16i8, &pshufbMask[0], 16));
6076     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6077   }
6078
6079   // No SSSE3 - Calculate in place words and then fix all out of place words
6080   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6081   // the 16 different words that comprise the two doublequadword input vectors.
6082   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6083   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6084   SDValue NewV = V1;
6085   for (int i = 0; i != 8; ++i) {
6086     int Elt0 = MaskVals[i*2];
6087     int Elt1 = MaskVals[i*2+1];
6088
6089     // This word of the result is all undef, skip it.
6090     if (Elt0 < 0 && Elt1 < 0)
6091       continue;
6092
6093     // This word of the result is already in the correct place, skip it.
6094     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6095       continue;
6096
6097     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6098     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6099     SDValue InsElt;
6100
6101     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6102     // using a single extract together, load it and store it.
6103     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6104       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6105                            DAG.getIntPtrConstant(Elt1 / 2));
6106       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6107                         DAG.getIntPtrConstant(i));
6108       continue;
6109     }
6110
6111     // If Elt1 is defined, extract it from the appropriate source.  If the
6112     // source byte is not also odd, shift the extracted word left 8 bits
6113     // otherwise clear the bottom 8 bits if we need to do an or.
6114     if (Elt1 >= 0) {
6115       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6116                            DAG.getIntPtrConstant(Elt1 / 2));
6117       if ((Elt1 & 1) == 0)
6118         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6119                              DAG.getConstant(8,
6120                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6121       else if (Elt0 >= 0)
6122         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6123                              DAG.getConstant(0xFF00, MVT::i16));
6124     }
6125     // If Elt0 is defined, extract it from the appropriate source.  If the
6126     // source byte is not also even, shift the extracted word right 8 bits. If
6127     // Elt1 was also defined, OR the extracted values together before
6128     // inserting them in the result.
6129     if (Elt0 >= 0) {
6130       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6131                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6132       if ((Elt0 & 1) != 0)
6133         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6134                               DAG.getConstant(8,
6135                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6136       else if (Elt1 >= 0)
6137         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6138                              DAG.getConstant(0x00FF, MVT::i16));
6139       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6140                          : InsElt0;
6141     }
6142     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6143                        DAG.getIntPtrConstant(i));
6144   }
6145   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6146 }
6147
6148 // v32i8 shuffles - Translate to VPSHUFB if possible.
6149 static
6150 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6151                                  const X86Subtarget *Subtarget,
6152                                  SelectionDAG &DAG) {
6153   MVT VT = SVOp->getValueType(0).getSimpleVT();
6154   SDValue V1 = SVOp->getOperand(0);
6155   SDValue V2 = SVOp->getOperand(1);
6156   DebugLoc dl = SVOp->getDebugLoc();
6157   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6158
6159   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6160   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6161   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6162
6163   // VPSHUFB may be generated if
6164   // (1) one of input vector is undefined or zeroinitializer.
6165   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6166   // And (2) the mask indexes don't cross the 128-bit lane.
6167   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6168       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6169     return SDValue();
6170
6171   if (V1IsAllZero && !V2IsAllZero) {
6172     CommuteVectorShuffleMask(MaskVals, 32);
6173     V1 = V2;
6174   }
6175   SmallVector<SDValue, 32> pshufbMask;
6176   for (unsigned i = 0; i != 32; i++) {
6177     int EltIdx = MaskVals[i];
6178     if (EltIdx < 0 || EltIdx >= 32)
6179       EltIdx = 0x80;
6180     else {
6181       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6182         // Cross lane is not allowed.
6183         return SDValue();
6184       EltIdx &= 0xf;
6185     }
6186     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6187   }
6188   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6189                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6190                                   MVT::v32i8, &pshufbMask[0], 32));
6191 }
6192
6193 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6194 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6195 /// done when every pair / quad of shuffle mask elements point to elements in
6196 /// the right sequence. e.g.
6197 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6198 static
6199 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6200                                  SelectionDAG &DAG) {
6201   MVT VT = SVOp->getValueType(0).getSimpleVT();
6202   DebugLoc dl = SVOp->getDebugLoc();
6203   unsigned NumElems = VT.getVectorNumElements();
6204   MVT NewVT;
6205   unsigned Scale;
6206   switch (VT.SimpleTy) {
6207   default: llvm_unreachable("Unexpected!");
6208   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6209   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6210   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6211   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6212   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6213   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6214   }
6215
6216   SmallVector<int, 8> MaskVec;
6217   for (unsigned i = 0; i != NumElems; i += Scale) {
6218     int StartIdx = -1;
6219     for (unsigned j = 0; j != Scale; ++j) {
6220       int EltIdx = SVOp->getMaskElt(i+j);
6221       if (EltIdx < 0)
6222         continue;
6223       if (StartIdx < 0)
6224         StartIdx = (EltIdx / Scale);
6225       if (EltIdx != (int)(StartIdx*Scale + j))
6226         return SDValue();
6227     }
6228     MaskVec.push_back(StartIdx);
6229   }
6230
6231   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6232   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6233   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6234 }
6235
6236 /// getVZextMovL - Return a zero-extending vector move low node.
6237 ///
6238 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6239                             SDValue SrcOp, SelectionDAG &DAG,
6240                             const X86Subtarget *Subtarget, DebugLoc dl) {
6241   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6242     LoadSDNode *LD = NULL;
6243     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6244       LD = dyn_cast<LoadSDNode>(SrcOp);
6245     if (!LD) {
6246       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6247       // instead.
6248       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6249       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6250           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6251           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6252           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6253         // PR2108
6254         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6255         return DAG.getNode(ISD::BITCAST, dl, VT,
6256                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6257                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6258                                                    OpVT,
6259                                                    SrcOp.getOperand(0)
6260                                                           .getOperand(0))));
6261       }
6262     }
6263   }
6264
6265   return DAG.getNode(ISD::BITCAST, dl, VT,
6266                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6267                                  DAG.getNode(ISD::BITCAST, dl,
6268                                              OpVT, SrcOp)));
6269 }
6270
6271 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6272 /// which could not be matched by any known target speficic shuffle
6273 static SDValue
6274 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6275
6276   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6277   if (NewOp.getNode())
6278     return NewOp;
6279
6280   MVT VT = SVOp->getValueType(0).getSimpleVT();
6281
6282   unsigned NumElems = VT.getVectorNumElements();
6283   unsigned NumLaneElems = NumElems / 2;
6284
6285   DebugLoc dl = SVOp->getDebugLoc();
6286   MVT EltVT = VT.getVectorElementType();
6287   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6288   SDValue Output[2];
6289
6290   SmallVector<int, 16> Mask;
6291   for (unsigned l = 0; l < 2; ++l) {
6292     // Build a shuffle mask for the output, discovering on the fly which
6293     // input vectors to use as shuffle operands (recorded in InputUsed).
6294     // If building a suitable shuffle vector proves too hard, then bail
6295     // out with UseBuildVector set.
6296     bool UseBuildVector = false;
6297     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6298     unsigned LaneStart = l * NumLaneElems;
6299     for (unsigned i = 0; i != NumLaneElems; ++i) {
6300       // The mask element.  This indexes into the input.
6301       int Idx = SVOp->getMaskElt(i+LaneStart);
6302       if (Idx < 0) {
6303         // the mask element does not index into any input vector.
6304         Mask.push_back(-1);
6305         continue;
6306       }
6307
6308       // The input vector this mask element indexes into.
6309       int Input = Idx / NumLaneElems;
6310
6311       // Turn the index into an offset from the start of the input vector.
6312       Idx -= Input * NumLaneElems;
6313
6314       // Find or create a shuffle vector operand to hold this input.
6315       unsigned OpNo;
6316       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6317         if (InputUsed[OpNo] == Input)
6318           // This input vector is already an operand.
6319           break;
6320         if (InputUsed[OpNo] < 0) {
6321           // Create a new operand for this input vector.
6322           InputUsed[OpNo] = Input;
6323           break;
6324         }
6325       }
6326
6327       if (OpNo >= array_lengthof(InputUsed)) {
6328         // More than two input vectors used!  Give up on trying to create a
6329         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6330         UseBuildVector = true;
6331         break;
6332       }
6333
6334       // Add the mask index for the new shuffle vector.
6335       Mask.push_back(Idx + OpNo * NumLaneElems);
6336     }
6337
6338     if (UseBuildVector) {
6339       SmallVector<SDValue, 16> SVOps;
6340       for (unsigned i = 0; i != NumLaneElems; ++i) {
6341         // The mask element.  This indexes into the input.
6342         int Idx = SVOp->getMaskElt(i+LaneStart);
6343         if (Idx < 0) {
6344           SVOps.push_back(DAG.getUNDEF(EltVT));
6345           continue;
6346         }
6347
6348         // The input vector this mask element indexes into.
6349         int Input = Idx / NumElems;
6350
6351         // Turn the index into an offset from the start of the input vector.
6352         Idx -= Input * NumElems;
6353
6354         // Extract the vector element by hand.
6355         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6356                                     SVOp->getOperand(Input),
6357                                     DAG.getIntPtrConstant(Idx)));
6358       }
6359
6360       // Construct the output using a BUILD_VECTOR.
6361       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6362                               SVOps.size());
6363     } else if (InputUsed[0] < 0) {
6364       // No input vectors were used! The result is undefined.
6365       Output[l] = DAG.getUNDEF(NVT);
6366     } else {
6367       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6368                                         (InputUsed[0] % 2) * NumLaneElems,
6369                                         DAG, dl);
6370       // If only one input was used, use an undefined vector for the other.
6371       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6372         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6373                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6374       // At least one input vector was used. Create a new shuffle vector.
6375       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6376     }
6377
6378     Mask.clear();
6379   }
6380
6381   // Concatenate the result back
6382   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6383 }
6384
6385 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6386 /// 4 elements, and match them with several different shuffle types.
6387 static SDValue
6388 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6389   SDValue V1 = SVOp->getOperand(0);
6390   SDValue V2 = SVOp->getOperand(1);
6391   DebugLoc dl = SVOp->getDebugLoc();
6392   MVT VT = SVOp->getValueType(0).getSimpleVT();
6393
6394   assert(VT.is128BitVector() && "Unsupported vector size");
6395
6396   std::pair<int, int> Locs[4];
6397   int Mask1[] = { -1, -1, -1, -1 };
6398   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6399
6400   unsigned NumHi = 0;
6401   unsigned NumLo = 0;
6402   for (unsigned i = 0; i != 4; ++i) {
6403     int Idx = PermMask[i];
6404     if (Idx < 0) {
6405       Locs[i] = std::make_pair(-1, -1);
6406     } else {
6407       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6408       if (Idx < 4) {
6409         Locs[i] = std::make_pair(0, NumLo);
6410         Mask1[NumLo] = Idx;
6411         NumLo++;
6412       } else {
6413         Locs[i] = std::make_pair(1, NumHi);
6414         if (2+NumHi < 4)
6415           Mask1[2+NumHi] = Idx;
6416         NumHi++;
6417       }
6418     }
6419   }
6420
6421   if (NumLo <= 2 && NumHi <= 2) {
6422     // If no more than two elements come from either vector. This can be
6423     // implemented with two shuffles. First shuffle gather the elements.
6424     // The second shuffle, which takes the first shuffle as both of its
6425     // vector operands, put the elements into the right order.
6426     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6427
6428     int Mask2[] = { -1, -1, -1, -1 };
6429
6430     for (unsigned i = 0; i != 4; ++i)
6431       if (Locs[i].first != -1) {
6432         unsigned Idx = (i < 2) ? 0 : 4;
6433         Idx += Locs[i].first * 2 + Locs[i].second;
6434         Mask2[i] = Idx;
6435       }
6436
6437     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6438   }
6439
6440   if (NumLo == 3 || NumHi == 3) {
6441     // Otherwise, we must have three elements from one vector, call it X, and
6442     // one element from the other, call it Y.  First, use a shufps to build an
6443     // intermediate vector with the one element from Y and the element from X
6444     // that will be in the same half in the final destination (the indexes don't
6445     // matter). Then, use a shufps to build the final vector, taking the half
6446     // containing the element from Y from the intermediate, and the other half
6447     // from X.
6448     if (NumHi == 3) {
6449       // Normalize it so the 3 elements come from V1.
6450       CommuteVectorShuffleMask(PermMask, 4);
6451       std::swap(V1, V2);
6452     }
6453
6454     // Find the element from V2.
6455     unsigned HiIndex;
6456     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6457       int Val = PermMask[HiIndex];
6458       if (Val < 0)
6459         continue;
6460       if (Val >= 4)
6461         break;
6462     }
6463
6464     Mask1[0] = PermMask[HiIndex];
6465     Mask1[1] = -1;
6466     Mask1[2] = PermMask[HiIndex^1];
6467     Mask1[3] = -1;
6468     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6469
6470     if (HiIndex >= 2) {
6471       Mask1[0] = PermMask[0];
6472       Mask1[1] = PermMask[1];
6473       Mask1[2] = HiIndex & 1 ? 6 : 4;
6474       Mask1[3] = HiIndex & 1 ? 4 : 6;
6475       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6476     }
6477
6478     Mask1[0] = HiIndex & 1 ? 2 : 0;
6479     Mask1[1] = HiIndex & 1 ? 0 : 2;
6480     Mask1[2] = PermMask[2];
6481     Mask1[3] = PermMask[3];
6482     if (Mask1[2] >= 0)
6483       Mask1[2] += 4;
6484     if (Mask1[3] >= 0)
6485       Mask1[3] += 4;
6486     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6487   }
6488
6489   // Break it into (shuffle shuffle_hi, shuffle_lo).
6490   int LoMask[] = { -1, -1, -1, -1 };
6491   int HiMask[] = { -1, -1, -1, -1 };
6492
6493   int *MaskPtr = LoMask;
6494   unsigned MaskIdx = 0;
6495   unsigned LoIdx = 0;
6496   unsigned HiIdx = 2;
6497   for (unsigned i = 0; i != 4; ++i) {
6498     if (i == 2) {
6499       MaskPtr = HiMask;
6500       MaskIdx = 1;
6501       LoIdx = 0;
6502       HiIdx = 2;
6503     }
6504     int Idx = PermMask[i];
6505     if (Idx < 0) {
6506       Locs[i] = std::make_pair(-1, -1);
6507     } else if (Idx < 4) {
6508       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6509       MaskPtr[LoIdx] = Idx;
6510       LoIdx++;
6511     } else {
6512       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6513       MaskPtr[HiIdx] = Idx;
6514       HiIdx++;
6515     }
6516   }
6517
6518   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6519   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6520   int MaskOps[] = { -1, -1, -1, -1 };
6521   for (unsigned i = 0; i != 4; ++i)
6522     if (Locs[i].first != -1)
6523       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6524   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6525 }
6526
6527 static bool MayFoldVectorLoad(SDValue V) {
6528   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6529     V = V.getOperand(0);
6530
6531   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6532     V = V.getOperand(0);
6533   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6534       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6535     // BUILD_VECTOR (load), undef
6536     V = V.getOperand(0);
6537
6538   return MayFoldLoad(V);
6539 }
6540
6541 static
6542 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6543   EVT VT = Op.getValueType();
6544
6545   // Canonizalize to v2f64.
6546   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6547   return DAG.getNode(ISD::BITCAST, dl, VT,
6548                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6549                                           V1, DAG));
6550 }
6551
6552 static
6553 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6554                         bool HasSSE2) {
6555   SDValue V1 = Op.getOperand(0);
6556   SDValue V2 = Op.getOperand(1);
6557   EVT VT = Op.getValueType();
6558
6559   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6560
6561   if (HasSSE2 && VT == MVT::v2f64)
6562     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6563
6564   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6565   return DAG.getNode(ISD::BITCAST, dl, VT,
6566                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6567                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6568                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6569 }
6570
6571 static
6572 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6573   SDValue V1 = Op.getOperand(0);
6574   SDValue V2 = Op.getOperand(1);
6575   EVT VT = Op.getValueType();
6576
6577   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6578          "unsupported shuffle type");
6579
6580   if (V2.getOpcode() == ISD::UNDEF)
6581     V2 = V1;
6582
6583   // v4i32 or v4f32
6584   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6585 }
6586
6587 static
6588 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6589   SDValue V1 = Op.getOperand(0);
6590   SDValue V2 = Op.getOperand(1);
6591   EVT VT = Op.getValueType();
6592   unsigned NumElems = VT.getVectorNumElements();
6593
6594   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6595   // operand of these instructions is only memory, so check if there's a
6596   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6597   // same masks.
6598   bool CanFoldLoad = false;
6599
6600   // Trivial case, when V2 comes from a load.
6601   if (MayFoldVectorLoad(V2))
6602     CanFoldLoad = true;
6603
6604   // When V1 is a load, it can be folded later into a store in isel, example:
6605   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6606   //    turns into:
6607   //  (MOVLPSmr addr:$src1, VR128:$src2)
6608   // So, recognize this potential and also use MOVLPS or MOVLPD
6609   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6610     CanFoldLoad = true;
6611
6612   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6613   if (CanFoldLoad) {
6614     if (HasSSE2 && NumElems == 2)
6615       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6616
6617     if (NumElems == 4)
6618       // If we don't care about the second element, proceed to use movss.
6619       if (SVOp->getMaskElt(1) != -1)
6620         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6621   }
6622
6623   // movl and movlp will both match v2i64, but v2i64 is never matched by
6624   // movl earlier because we make it strict to avoid messing with the movlp load
6625   // folding logic (see the code above getMOVLP call). Match it here then,
6626   // this is horrible, but will stay like this until we move all shuffle
6627   // matching to x86 specific nodes. Note that for the 1st condition all
6628   // types are matched with movsd.
6629   if (HasSSE2) {
6630     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6631     // as to remove this logic from here, as much as possible
6632     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6633       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6634     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6635   }
6636
6637   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6638
6639   // Invert the operand order and use SHUFPS to match it.
6640   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6641                               getShuffleSHUFImmediate(SVOp), DAG);
6642 }
6643
6644 // Reduce a vector shuffle to zext.
6645 SDValue
6646 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6647   // PMOVZX is only available from SSE41.
6648   if (!Subtarget->hasSSE41())
6649     return SDValue();
6650
6651   EVT VT = Op.getValueType();
6652
6653   // Only AVX2 support 256-bit vector integer extending.
6654   if (!Subtarget->hasInt256() && VT.is256BitVector())
6655     return SDValue();
6656
6657   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6658   DebugLoc DL = Op.getDebugLoc();
6659   SDValue V1 = Op.getOperand(0);
6660   SDValue V2 = Op.getOperand(1);
6661   unsigned NumElems = VT.getVectorNumElements();
6662
6663   // Extending is an unary operation and the element type of the source vector
6664   // won't be equal to or larger than i64.
6665   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6666       VT.getVectorElementType() == MVT::i64)
6667     return SDValue();
6668
6669   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6670   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6671   while ((1U << Shift) < NumElems) {
6672     if (SVOp->getMaskElt(1U << Shift) == 1)
6673       break;
6674     Shift += 1;
6675     // The maximal ratio is 8, i.e. from i8 to i64.
6676     if (Shift > 3)
6677       return SDValue();
6678   }
6679
6680   // Check the shuffle mask.
6681   unsigned Mask = (1U << Shift) - 1;
6682   for (unsigned i = 0; i != NumElems; ++i) {
6683     int EltIdx = SVOp->getMaskElt(i);
6684     if ((i & Mask) != 0 && EltIdx != -1)
6685       return SDValue();
6686     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6687       return SDValue();
6688   }
6689
6690   LLVMContext *Context = DAG.getContext();
6691   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6692   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6693   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6694
6695   if (!isTypeLegal(NVT))
6696     return SDValue();
6697
6698   // Simplify the operand as it's prepared to be fed into shuffle.
6699   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6700   if (V1.getOpcode() == ISD::BITCAST &&
6701       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6702       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6703       V1.getOperand(0)
6704         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6705     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6706     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6707     ConstantSDNode *CIdx =
6708       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6709     // If it's foldable, i.e. normal load with single use, we will let code
6710     // selection to fold it. Otherwise, we will short the conversion sequence.
6711     if (CIdx && CIdx->getZExtValue() == 0 &&
6712         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6713       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6714         // The "ext_vec_elt" node is wider than the result node.
6715         // In this case we should extract subvector from V.
6716         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6717         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6718         EVT FullVT = V.getValueType();
6719         EVT SubVecVT = EVT::getVectorVT(*Context, 
6720                                         FullVT.getVectorElementType(),
6721                                         FullVT.getVectorNumElements()/Ratio);
6722         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V, 
6723                         DAG.getIntPtrConstant(0));
6724       }
6725       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6726     }
6727   }
6728
6729   return DAG.getNode(ISD::BITCAST, DL, VT,
6730                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6731 }
6732
6733 SDValue
6734 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6735   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6736   MVT VT = Op.getValueType().getSimpleVT();
6737   DebugLoc dl = Op.getDebugLoc();
6738   SDValue V1 = Op.getOperand(0);
6739   SDValue V2 = Op.getOperand(1);
6740
6741   if (isZeroShuffle(SVOp))
6742     return getZeroVector(VT, Subtarget, DAG, dl);
6743
6744   // Handle splat operations
6745   if (SVOp->isSplat()) {
6746     // Use vbroadcast whenever the splat comes from a foldable load
6747     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6748     if (Broadcast.getNode())
6749       return Broadcast;
6750   }
6751
6752   // Check integer expanding shuffles.
6753   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6754   if (NewOp.getNode())
6755     return NewOp;
6756
6757   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6758   // do it!
6759   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6760       VT == MVT::v16i16 || VT == MVT::v32i8) {
6761     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6762     if (NewOp.getNode())
6763       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6764   } else if ((VT == MVT::v4i32 ||
6765              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6766     // FIXME: Figure out a cleaner way to do this.
6767     // Try to make use of movq to zero out the top part.
6768     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6769       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6770       if (NewOp.getNode()) {
6771         MVT NewVT = NewOp.getValueType().getSimpleVT();
6772         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6773                                NewVT, true, false))
6774           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6775                               DAG, Subtarget, dl);
6776       }
6777     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6778       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6779       if (NewOp.getNode()) {
6780         MVT NewVT = NewOp.getValueType().getSimpleVT();
6781         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6782           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6783                               DAG, Subtarget, dl);
6784       }
6785     }
6786   }
6787   return SDValue();
6788 }
6789
6790 SDValue
6791 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6792   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6793   SDValue V1 = Op.getOperand(0);
6794   SDValue V2 = Op.getOperand(1);
6795   MVT VT = Op.getValueType().getSimpleVT();
6796   DebugLoc dl = Op.getDebugLoc();
6797   unsigned NumElems = VT.getVectorNumElements();
6798   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6799   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6800   bool V1IsSplat = false;
6801   bool V2IsSplat = false;
6802   bool HasSSE2 = Subtarget->hasSSE2();
6803   bool HasFp256    = Subtarget->hasFp256();
6804   bool HasInt256   = Subtarget->hasInt256();
6805   MachineFunction &MF = DAG.getMachineFunction();
6806   bool OptForSize = MF.getFunction()->getAttributes().
6807     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6808
6809   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6810
6811   if (V1IsUndef && V2IsUndef)
6812     return DAG.getUNDEF(VT);
6813
6814   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6815
6816   // Vector shuffle lowering takes 3 steps:
6817   //
6818   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6819   //    narrowing and commutation of operands should be handled.
6820   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6821   //    shuffle nodes.
6822   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6823   //    so the shuffle can be broken into other shuffles and the legalizer can
6824   //    try the lowering again.
6825   //
6826   // The general idea is that no vector_shuffle operation should be left to
6827   // be matched during isel, all of them must be converted to a target specific
6828   // node here.
6829
6830   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6831   // narrowing and commutation of operands should be handled. The actual code
6832   // doesn't include all of those, work in progress...
6833   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6834   if (NewOp.getNode())
6835     return NewOp;
6836
6837   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6838
6839   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6840   // unpckh_undef). Only use pshufd if speed is more important than size.
6841   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6842     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6843   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6844     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6845
6846   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6847       V2IsUndef && MayFoldVectorLoad(V1))
6848     return getMOVDDup(Op, dl, V1, DAG);
6849
6850   if (isMOVHLPS_v_undef_Mask(M, VT))
6851     return getMOVHighToLow(Op, dl, DAG);
6852
6853   // Use to match splats
6854   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6855       (VT == MVT::v2f64 || VT == MVT::v2i64))
6856     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6857
6858   if (isPSHUFDMask(M, VT)) {
6859     // The actual implementation will match the mask in the if above and then
6860     // during isel it can match several different instructions, not only pshufd
6861     // as its name says, sad but true, emulate the behavior for now...
6862     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6863       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6864
6865     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6866
6867     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6868       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6869
6870     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6871       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6872                                   DAG);
6873
6874     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6875                                 TargetMask, DAG);
6876   }
6877
6878   // Check if this can be converted into a logical shift.
6879   bool isLeft = false;
6880   unsigned ShAmt = 0;
6881   SDValue ShVal;
6882   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6883   if (isShift && ShVal.hasOneUse()) {
6884     // If the shifted value has multiple uses, it may be cheaper to use
6885     // v_set0 + movlhps or movhlps, etc.
6886     MVT EltVT = VT.getVectorElementType();
6887     ShAmt *= EltVT.getSizeInBits();
6888     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6889   }
6890
6891   if (isMOVLMask(M, VT)) {
6892     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6893       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6894     if (!isMOVLPMask(M, VT)) {
6895       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6896         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6897
6898       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6899         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6900     }
6901   }
6902
6903   // FIXME: fold these into legal mask.
6904   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6905     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6906
6907   if (isMOVHLPSMask(M, VT))
6908     return getMOVHighToLow(Op, dl, DAG);
6909
6910   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6911     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6912
6913   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6914     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6915
6916   if (isMOVLPMask(M, VT))
6917     return getMOVLP(Op, dl, DAG, HasSSE2);
6918
6919   if (ShouldXformToMOVHLPS(M, VT) ||
6920       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6921     return CommuteVectorShuffle(SVOp, DAG);
6922
6923   if (isShift) {
6924     // No better options. Use a vshldq / vsrldq.
6925     MVT EltVT = VT.getVectorElementType();
6926     ShAmt *= EltVT.getSizeInBits();
6927     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6928   }
6929
6930   bool Commuted = false;
6931   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6932   // 1,1,1,1 -> v8i16 though.
6933   V1IsSplat = isSplatVector(V1.getNode());
6934   V2IsSplat = isSplatVector(V2.getNode());
6935
6936   // Canonicalize the splat or undef, if present, to be on the RHS.
6937   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6938     CommuteVectorShuffleMask(M, NumElems);
6939     std::swap(V1, V2);
6940     std::swap(V1IsSplat, V2IsSplat);
6941     Commuted = true;
6942   }
6943
6944   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6945     // Shuffling low element of v1 into undef, just return v1.
6946     if (V2IsUndef)
6947       return V1;
6948     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6949     // the instruction selector will not match, so get a canonical MOVL with
6950     // swapped operands to undo the commute.
6951     return getMOVL(DAG, dl, VT, V2, V1);
6952   }
6953
6954   if (isUNPCKLMask(M, VT, HasInt256))
6955     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6956
6957   if (isUNPCKHMask(M, VT, HasInt256))
6958     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6959
6960   if (V2IsSplat) {
6961     // Normalize mask so all entries that point to V2 points to its first
6962     // element then try to match unpck{h|l} again. If match, return a
6963     // new vector_shuffle with the corrected mask.p
6964     SmallVector<int, 8> NewMask(M.begin(), M.end());
6965     NormalizeMask(NewMask, NumElems);
6966     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6967       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6968     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
6969       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6970   }
6971
6972   if (Commuted) {
6973     // Commute is back and try unpck* again.
6974     // FIXME: this seems wrong.
6975     CommuteVectorShuffleMask(M, NumElems);
6976     std::swap(V1, V2);
6977     std::swap(V1IsSplat, V2IsSplat);
6978     Commuted = false;
6979
6980     if (isUNPCKLMask(M, VT, HasInt256))
6981       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6982
6983     if (isUNPCKHMask(M, VT, HasInt256))
6984       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6985   }
6986
6987   // Normalize the node to match x86 shuffle ops if needed
6988   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
6989     return CommuteVectorShuffle(SVOp, DAG);
6990
6991   // The checks below are all present in isShuffleMaskLegal, but they are
6992   // inlined here right now to enable us to directly emit target specific
6993   // nodes, and remove one by one until they don't return Op anymore.
6994
6995   if (isPALIGNRMask(M, VT, Subtarget))
6996     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6997                                 getShufflePALIGNRImmediate(SVOp),
6998                                 DAG);
6999
7000   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7001       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7002     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7003       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7004   }
7005
7006   if (isPSHUFHWMask(M, VT, HasInt256))
7007     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7008                                 getShufflePSHUFHWImmediate(SVOp),
7009                                 DAG);
7010
7011   if (isPSHUFLWMask(M, VT, HasInt256))
7012     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7013                                 getShufflePSHUFLWImmediate(SVOp),
7014                                 DAG);
7015
7016   if (isSHUFPMask(M, VT, HasFp256))
7017     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7018                                 getShuffleSHUFImmediate(SVOp), DAG);
7019
7020   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7021     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7022   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7023     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7024
7025   //===--------------------------------------------------------------------===//
7026   // Generate target specific nodes for 128 or 256-bit shuffles only
7027   // supported in the AVX instruction set.
7028   //
7029
7030   // Handle VMOVDDUPY permutations
7031   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7032     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7033
7034   // Handle VPERMILPS/D* permutations
7035   if (isVPERMILPMask(M, VT, HasFp256)) {
7036     if (HasInt256 && VT == MVT::v8i32)
7037       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7038                                   getShuffleSHUFImmediate(SVOp), DAG);
7039     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7040                                 getShuffleSHUFImmediate(SVOp), DAG);
7041   }
7042
7043   // Handle VPERM2F128/VPERM2I128 permutations
7044   if (isVPERM2X128Mask(M, VT, HasFp256))
7045     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7046                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7047
7048   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7049   if (BlendOp.getNode())
7050     return BlendOp;
7051
7052   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7053     SmallVector<SDValue, 8> permclMask;
7054     for (unsigned i = 0; i != 8; ++i) {
7055       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7056     }
7057     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7058                                &permclMask[0], 8);
7059     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7060     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7061                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7062   }
7063
7064   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7065     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7066                                 getShuffleCLImmediate(SVOp), DAG);
7067
7068   //===--------------------------------------------------------------------===//
7069   // Since no target specific shuffle was selected for this generic one,
7070   // lower it into other known shuffles. FIXME: this isn't true yet, but
7071   // this is the plan.
7072   //
7073
7074   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7075   if (VT == MVT::v8i16) {
7076     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7077     if (NewOp.getNode())
7078       return NewOp;
7079   }
7080
7081   if (VT == MVT::v16i8) {
7082     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7083     if (NewOp.getNode())
7084       return NewOp;
7085   }
7086
7087   if (VT == MVT::v32i8) {
7088     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7089     if (NewOp.getNode())
7090       return NewOp;
7091   }
7092
7093   // Handle all 128-bit wide vectors with 4 elements, and match them with
7094   // several different shuffle types.
7095   if (NumElems == 4 && VT.is128BitVector())
7096     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7097
7098   // Handle general 256-bit shuffles
7099   if (VT.is256BitVector())
7100     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7101
7102   return SDValue();
7103 }
7104
7105 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7106   MVT VT = Op.getValueType().getSimpleVT();
7107   DebugLoc dl = Op.getDebugLoc();
7108
7109   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7110     return SDValue();
7111
7112   if (VT.getSizeInBits() == 8) {
7113     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7114                                   Op.getOperand(0), Op.getOperand(1));
7115     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7116                                   DAG.getValueType(VT));
7117     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7118   }
7119
7120   if (VT.getSizeInBits() == 16) {
7121     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7122     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7123     if (Idx == 0)
7124       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7125                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7126                                      DAG.getNode(ISD::BITCAST, dl,
7127                                                  MVT::v4i32,
7128                                                  Op.getOperand(0)),
7129                                      Op.getOperand(1)));
7130     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7131                                   Op.getOperand(0), Op.getOperand(1));
7132     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7133                                   DAG.getValueType(VT));
7134     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7135   }
7136
7137   if (VT == MVT::f32) {
7138     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7139     // the result back to FR32 register. It's only worth matching if the
7140     // result has a single use which is a store or a bitcast to i32.  And in
7141     // the case of a store, it's not worth it if the index is a constant 0,
7142     // because a MOVSSmr can be used instead, which is smaller and faster.
7143     if (!Op.hasOneUse())
7144       return SDValue();
7145     SDNode *User = *Op.getNode()->use_begin();
7146     if ((User->getOpcode() != ISD::STORE ||
7147          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7148           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7149         (User->getOpcode() != ISD::BITCAST ||
7150          User->getValueType(0) != MVT::i32))
7151       return SDValue();
7152     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7153                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7154                                               Op.getOperand(0)),
7155                                               Op.getOperand(1));
7156     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7157   }
7158
7159   if (VT == MVT::i32 || VT == MVT::i64) {
7160     // ExtractPS/pextrq works with constant index.
7161     if (isa<ConstantSDNode>(Op.getOperand(1)))
7162       return Op;
7163   }
7164   return SDValue();
7165 }
7166
7167 SDValue
7168 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7169                                            SelectionDAG &DAG) const {
7170   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7171     return SDValue();
7172
7173   SDValue Vec = Op.getOperand(0);
7174   MVT VecVT = Vec.getValueType().getSimpleVT();
7175
7176   // If this is a 256-bit vector result, first extract the 128-bit vector and
7177   // then extract the element from the 128-bit vector.
7178   if (VecVT.is256BitVector()) {
7179     DebugLoc dl = Op.getNode()->getDebugLoc();
7180     unsigned NumElems = VecVT.getVectorNumElements();
7181     SDValue Idx = Op.getOperand(1);
7182     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7183
7184     // Get the 128-bit vector.
7185     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7186
7187     if (IdxVal >= NumElems/2)
7188       IdxVal -= NumElems/2;
7189     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7190                        DAG.getConstant(IdxVal, MVT::i32));
7191   }
7192
7193   assert(VecVT.is128BitVector() && "Unexpected vector length");
7194
7195   if (Subtarget->hasSSE41()) {
7196     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7197     if (Res.getNode())
7198       return Res;
7199   }
7200
7201   MVT VT = Op.getValueType().getSimpleVT();
7202   DebugLoc dl = Op.getDebugLoc();
7203   // TODO: handle v16i8.
7204   if (VT.getSizeInBits() == 16) {
7205     SDValue Vec = Op.getOperand(0);
7206     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7207     if (Idx == 0)
7208       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7209                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7210                                      DAG.getNode(ISD::BITCAST, dl,
7211                                                  MVT::v4i32, Vec),
7212                                      Op.getOperand(1)));
7213     // Transform it so it match pextrw which produces a 32-bit result.
7214     MVT EltVT = MVT::i32;
7215     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7216                                   Op.getOperand(0), Op.getOperand(1));
7217     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7218                                   DAG.getValueType(VT));
7219     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7220   }
7221
7222   if (VT.getSizeInBits() == 32) {
7223     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7224     if (Idx == 0)
7225       return Op;
7226
7227     // SHUFPS the element to the lowest double word, then movss.
7228     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7229     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7230     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7231                                        DAG.getUNDEF(VVT), Mask);
7232     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7233                        DAG.getIntPtrConstant(0));
7234   }
7235
7236   if (VT.getSizeInBits() == 64) {
7237     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7238     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7239     //        to match extract_elt for f64.
7240     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7241     if (Idx == 0)
7242       return Op;
7243
7244     // UNPCKHPD the element to the lowest double word, then movsd.
7245     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7246     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7247     int Mask[2] = { 1, -1 };
7248     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7249     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7250                                        DAG.getUNDEF(VVT), Mask);
7251     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7252                        DAG.getIntPtrConstant(0));
7253   }
7254
7255   return SDValue();
7256 }
7257
7258 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7259   MVT VT = Op.getValueType().getSimpleVT();
7260   MVT EltVT = VT.getVectorElementType();
7261   DebugLoc dl = Op.getDebugLoc();
7262
7263   SDValue N0 = Op.getOperand(0);
7264   SDValue N1 = Op.getOperand(1);
7265   SDValue N2 = Op.getOperand(2);
7266
7267   if (!VT.is128BitVector())
7268     return SDValue();
7269
7270   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7271       isa<ConstantSDNode>(N2)) {
7272     unsigned Opc;
7273     if (VT == MVT::v8i16)
7274       Opc = X86ISD::PINSRW;
7275     else if (VT == MVT::v16i8)
7276       Opc = X86ISD::PINSRB;
7277     else
7278       Opc = X86ISD::PINSRB;
7279
7280     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7281     // argument.
7282     if (N1.getValueType() != MVT::i32)
7283       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7284     if (N2.getValueType() != MVT::i32)
7285       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7286     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7287   }
7288
7289   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7290     // Bits [7:6] of the constant are the source select.  This will always be
7291     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7292     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7293     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7294     // Bits [5:4] of the constant are the destination select.  This is the
7295     //  value of the incoming immediate.
7296     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7297     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7298     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7299     // Create this as a scalar to vector..
7300     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7301     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7302   }
7303
7304   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7305     // PINSR* works with constant index.
7306     return Op;
7307   }
7308   return SDValue();
7309 }
7310
7311 SDValue
7312 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7313   MVT VT = Op.getValueType().getSimpleVT();
7314   MVT EltVT = VT.getVectorElementType();
7315
7316   DebugLoc dl = Op.getDebugLoc();
7317   SDValue N0 = Op.getOperand(0);
7318   SDValue N1 = Op.getOperand(1);
7319   SDValue N2 = Op.getOperand(2);
7320
7321   // If this is a 256-bit vector result, first extract the 128-bit vector,
7322   // insert the element into the extracted half and then place it back.
7323   if (VT.is256BitVector()) {
7324     if (!isa<ConstantSDNode>(N2))
7325       return SDValue();
7326
7327     // Get the desired 128-bit vector half.
7328     unsigned NumElems = VT.getVectorNumElements();
7329     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7330     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7331
7332     // Insert the element into the desired half.
7333     bool Upper = IdxVal >= NumElems/2;
7334     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7335                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7336
7337     // Insert the changed part back to the 256-bit vector
7338     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7339   }
7340
7341   if (Subtarget->hasSSE41())
7342     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7343
7344   if (EltVT == MVT::i8)
7345     return SDValue();
7346
7347   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7348     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7349     // as its second argument.
7350     if (N1.getValueType() != MVT::i32)
7351       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7352     if (N2.getValueType() != MVT::i32)
7353       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7354     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7355   }
7356   return SDValue();
7357 }
7358
7359 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7360   LLVMContext *Context = DAG.getContext();
7361   DebugLoc dl = Op.getDebugLoc();
7362   MVT OpVT = Op.getValueType().getSimpleVT();
7363
7364   // If this is a 256-bit vector result, first insert into a 128-bit
7365   // vector and then insert into the 256-bit vector.
7366   if (!OpVT.is128BitVector()) {
7367     // Insert into a 128-bit vector.
7368     EVT VT128 = EVT::getVectorVT(*Context,
7369                                  OpVT.getVectorElementType(),
7370                                  OpVT.getVectorNumElements() / 2);
7371
7372     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7373
7374     // Insert the 128-bit vector.
7375     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7376   }
7377
7378   if (OpVT == MVT::v1i64 &&
7379       Op.getOperand(0).getValueType() == MVT::i64)
7380     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7381
7382   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7383   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7384   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7385                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7386 }
7387
7388 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7389 // a simple subregister reference or explicit instructions to grab
7390 // upper bits of a vector.
7391 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7392                                       SelectionDAG &DAG) {
7393   if (Subtarget->hasFp256()) {
7394     DebugLoc dl = Op.getNode()->getDebugLoc();
7395     SDValue Vec = Op.getNode()->getOperand(0);
7396     SDValue Idx = Op.getNode()->getOperand(1);
7397
7398     if (Op.getNode()->getValueType(0).is128BitVector() &&
7399         Vec.getNode()->getValueType(0).is256BitVector() &&
7400         isa<ConstantSDNode>(Idx)) {
7401       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7402       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7403     }
7404   }
7405   return SDValue();
7406 }
7407
7408 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7409 // simple superregister reference or explicit instructions to insert
7410 // the upper bits of a vector.
7411 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7412                                      SelectionDAG &DAG) {
7413   if (Subtarget->hasFp256()) {
7414     DebugLoc dl = Op.getNode()->getDebugLoc();
7415     SDValue Vec = Op.getNode()->getOperand(0);
7416     SDValue SubVec = Op.getNode()->getOperand(1);
7417     SDValue Idx = Op.getNode()->getOperand(2);
7418
7419     if (Op.getNode()->getValueType(0).is256BitVector() &&
7420         SubVec.getNode()->getValueType(0).is128BitVector() &&
7421         isa<ConstantSDNode>(Idx)) {
7422       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7423       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7424     }
7425   }
7426   return SDValue();
7427 }
7428
7429 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7430 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7431 // one of the above mentioned nodes. It has to be wrapped because otherwise
7432 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7433 // be used to form addressing mode. These wrapped nodes will be selected
7434 // into MOV32ri.
7435 SDValue
7436 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7437   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7438
7439   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7440   // global base reg.
7441   unsigned char OpFlag = 0;
7442   unsigned WrapperKind = X86ISD::Wrapper;
7443   CodeModel::Model M = getTargetMachine().getCodeModel();
7444
7445   if (Subtarget->isPICStyleRIPRel() &&
7446       (M == CodeModel::Small || M == CodeModel::Kernel))
7447     WrapperKind = X86ISD::WrapperRIP;
7448   else if (Subtarget->isPICStyleGOT())
7449     OpFlag = X86II::MO_GOTOFF;
7450   else if (Subtarget->isPICStyleStubPIC())
7451     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7452
7453   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7454                                              CP->getAlignment(),
7455                                              CP->getOffset(), OpFlag);
7456   DebugLoc DL = CP->getDebugLoc();
7457   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7458   // With PIC, the address is actually $g + Offset.
7459   if (OpFlag) {
7460     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7461                          DAG.getNode(X86ISD::GlobalBaseReg,
7462                                      DebugLoc(), getPointerTy()),
7463                          Result);
7464   }
7465
7466   return Result;
7467 }
7468
7469 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7470   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7471
7472   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7473   // global base reg.
7474   unsigned char OpFlag = 0;
7475   unsigned WrapperKind = X86ISD::Wrapper;
7476   CodeModel::Model M = getTargetMachine().getCodeModel();
7477
7478   if (Subtarget->isPICStyleRIPRel() &&
7479       (M == CodeModel::Small || M == CodeModel::Kernel))
7480     WrapperKind = X86ISD::WrapperRIP;
7481   else if (Subtarget->isPICStyleGOT())
7482     OpFlag = X86II::MO_GOTOFF;
7483   else if (Subtarget->isPICStyleStubPIC())
7484     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7485
7486   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7487                                           OpFlag);
7488   DebugLoc DL = JT->getDebugLoc();
7489   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7490
7491   // With PIC, the address is actually $g + Offset.
7492   if (OpFlag)
7493     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7494                          DAG.getNode(X86ISD::GlobalBaseReg,
7495                                      DebugLoc(), getPointerTy()),
7496                          Result);
7497
7498   return Result;
7499 }
7500
7501 SDValue
7502 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7503   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7504
7505   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7506   // global base reg.
7507   unsigned char OpFlag = 0;
7508   unsigned WrapperKind = X86ISD::Wrapper;
7509   CodeModel::Model M = getTargetMachine().getCodeModel();
7510
7511   if (Subtarget->isPICStyleRIPRel() &&
7512       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7513     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7514       OpFlag = X86II::MO_GOTPCREL;
7515     WrapperKind = X86ISD::WrapperRIP;
7516   } else if (Subtarget->isPICStyleGOT()) {
7517     OpFlag = X86II::MO_GOT;
7518   } else if (Subtarget->isPICStyleStubPIC()) {
7519     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7520   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7521     OpFlag = X86II::MO_DARWIN_NONLAZY;
7522   }
7523
7524   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7525
7526   DebugLoc DL = Op.getDebugLoc();
7527   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7528
7529   // With PIC, the address is actually $g + Offset.
7530   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7531       !Subtarget->is64Bit()) {
7532     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7533                          DAG.getNode(X86ISD::GlobalBaseReg,
7534                                      DebugLoc(), getPointerTy()),
7535                          Result);
7536   }
7537
7538   // For symbols that require a load from a stub to get the address, emit the
7539   // load.
7540   if (isGlobalStubReference(OpFlag))
7541     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7542                          MachinePointerInfo::getGOT(), false, false, false, 0);
7543
7544   return Result;
7545 }
7546
7547 SDValue
7548 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7549   // Create the TargetBlockAddressAddress node.
7550   unsigned char OpFlags =
7551     Subtarget->ClassifyBlockAddressReference();
7552   CodeModel::Model M = getTargetMachine().getCodeModel();
7553   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7554   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7555   DebugLoc dl = Op.getDebugLoc();
7556   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7557                                              OpFlags);
7558
7559   if (Subtarget->isPICStyleRIPRel() &&
7560       (M == CodeModel::Small || M == CodeModel::Kernel))
7561     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7562   else
7563     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7564
7565   // With PIC, the address is actually $g + Offset.
7566   if (isGlobalRelativeToPICBase(OpFlags)) {
7567     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7568                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7569                          Result);
7570   }
7571
7572   return Result;
7573 }
7574
7575 SDValue
7576 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7577                                       int64_t Offset, SelectionDAG &DAG) const {
7578   // Create the TargetGlobalAddress node, folding in the constant
7579   // offset if it is legal.
7580   unsigned char OpFlags =
7581     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7582   CodeModel::Model M = getTargetMachine().getCodeModel();
7583   SDValue Result;
7584   if (OpFlags == X86II::MO_NO_FLAG &&
7585       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7586     // A direct static reference to a global.
7587     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7588     Offset = 0;
7589   } else {
7590     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7591   }
7592
7593   if (Subtarget->isPICStyleRIPRel() &&
7594       (M == CodeModel::Small || M == CodeModel::Kernel))
7595     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7596   else
7597     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7598
7599   // With PIC, the address is actually $g + Offset.
7600   if (isGlobalRelativeToPICBase(OpFlags)) {
7601     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7602                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7603                          Result);
7604   }
7605
7606   // For globals that require a load from a stub to get the address, emit the
7607   // load.
7608   if (isGlobalStubReference(OpFlags))
7609     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7610                          MachinePointerInfo::getGOT(), false, false, false, 0);
7611
7612   // If there was a non-zero offset that we didn't fold, create an explicit
7613   // addition for it.
7614   if (Offset != 0)
7615     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7616                          DAG.getConstant(Offset, getPointerTy()));
7617
7618   return Result;
7619 }
7620
7621 SDValue
7622 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7623   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7624   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7625   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7626 }
7627
7628 static SDValue
7629 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7630            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7631            unsigned char OperandFlags, bool LocalDynamic = false) {
7632   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7633   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7634   DebugLoc dl = GA->getDebugLoc();
7635   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7636                                            GA->getValueType(0),
7637                                            GA->getOffset(),
7638                                            OperandFlags);
7639
7640   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7641                                            : X86ISD::TLSADDR;
7642
7643   if (InFlag) {
7644     SDValue Ops[] = { Chain,  TGA, *InFlag };
7645     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 3);
7646   } else {
7647     SDValue Ops[]  = { Chain, TGA };
7648     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, 2);
7649   }
7650
7651   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7652   MFI->setAdjustsStack(true);
7653
7654   SDValue Flag = Chain.getValue(1);
7655   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7656 }
7657
7658 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7659 static SDValue
7660 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7661                                 const EVT PtrVT) {
7662   SDValue InFlag;
7663   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7664   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7665                                    DAG.getNode(X86ISD::GlobalBaseReg,
7666                                                DebugLoc(), PtrVT), InFlag);
7667   InFlag = Chain.getValue(1);
7668
7669   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7670 }
7671
7672 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7673 static SDValue
7674 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7675                                 const EVT PtrVT) {
7676   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7677                     X86::RAX, X86II::MO_TLSGD);
7678 }
7679
7680 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7681                                            SelectionDAG &DAG,
7682                                            const EVT PtrVT,
7683                                            bool is64Bit) {
7684   DebugLoc dl = GA->getDebugLoc();
7685
7686   // Get the start address of the TLS block for this module.
7687   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7688       .getInfo<X86MachineFunctionInfo>();
7689   MFI->incNumLocalDynamicTLSAccesses();
7690
7691   SDValue Base;
7692   if (is64Bit) {
7693     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7694                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7695   } else {
7696     SDValue InFlag;
7697     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7698         DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT), InFlag);
7699     InFlag = Chain.getValue(1);
7700     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7701                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7702   }
7703
7704   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7705   // of Base.
7706
7707   // Build x@dtpoff.
7708   unsigned char OperandFlags = X86II::MO_DTPOFF;
7709   unsigned WrapperKind = X86ISD::Wrapper;
7710   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7711                                            GA->getValueType(0),
7712                                            GA->getOffset(), OperandFlags);
7713   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7714
7715   // Add x@dtpoff with the base.
7716   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7717 }
7718
7719 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7720 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7721                                    const EVT PtrVT, TLSModel::Model model,
7722                                    bool is64Bit, bool isPIC) {
7723   DebugLoc dl = GA->getDebugLoc();
7724
7725   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7726   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7727                                                          is64Bit ? 257 : 256));
7728
7729   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7730                                       DAG.getIntPtrConstant(0),
7731                                       MachinePointerInfo(Ptr),
7732                                       false, false, false, 0);
7733
7734   unsigned char OperandFlags = 0;
7735   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7736   // initialexec.
7737   unsigned WrapperKind = X86ISD::Wrapper;
7738   if (model == TLSModel::LocalExec) {
7739     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7740   } else if (model == TLSModel::InitialExec) {
7741     if (is64Bit) {
7742       OperandFlags = X86II::MO_GOTTPOFF;
7743       WrapperKind = X86ISD::WrapperRIP;
7744     } else {
7745       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7746     }
7747   } else {
7748     llvm_unreachable("Unexpected model");
7749   }
7750
7751   // emit "addl x@ntpoff,%eax" (local exec)
7752   // or "addl x@indntpoff,%eax" (initial exec)
7753   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7754   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7755                                            GA->getValueType(0),
7756                                            GA->getOffset(), OperandFlags);
7757   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7758
7759   if (model == TLSModel::InitialExec) {
7760     if (isPIC && !is64Bit) {
7761       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7762                           DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), PtrVT),
7763                            Offset);
7764     }
7765
7766     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7767                          MachinePointerInfo::getGOT(), false, false, false,
7768                          0);
7769   }
7770
7771   // The address of the thread local variable is the add of the thread
7772   // pointer with the offset of the variable.
7773   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7774 }
7775
7776 SDValue
7777 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7778
7779   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7780   const GlobalValue *GV = GA->getGlobal();
7781
7782   if (Subtarget->isTargetELF()) {
7783     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7784
7785     switch (model) {
7786       case TLSModel::GeneralDynamic:
7787         if (Subtarget->is64Bit())
7788           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7789         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7790       case TLSModel::LocalDynamic:
7791         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7792                                            Subtarget->is64Bit());
7793       case TLSModel::InitialExec:
7794       case TLSModel::LocalExec:
7795         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7796                                    Subtarget->is64Bit(),
7797                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7798     }
7799     llvm_unreachable("Unknown TLS model.");
7800   }
7801
7802   if (Subtarget->isTargetDarwin()) {
7803     // Darwin only has one model of TLS.  Lower to that.
7804     unsigned char OpFlag = 0;
7805     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7806                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7807
7808     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7809     // global base reg.
7810     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7811                   !Subtarget->is64Bit();
7812     if (PIC32)
7813       OpFlag = X86II::MO_TLVP_PIC_BASE;
7814     else
7815       OpFlag = X86II::MO_TLVP;
7816     DebugLoc DL = Op.getDebugLoc();
7817     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7818                                                 GA->getValueType(0),
7819                                                 GA->getOffset(), OpFlag);
7820     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7821
7822     // With PIC32, the address is actually $g + Offset.
7823     if (PIC32)
7824       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7825                            DAG.getNode(X86ISD::GlobalBaseReg,
7826                                        DebugLoc(), getPointerTy()),
7827                            Offset);
7828
7829     // Lowering the machine isd will make sure everything is in the right
7830     // location.
7831     SDValue Chain = DAG.getEntryNode();
7832     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7833     SDValue Args[] = { Chain, Offset };
7834     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7835
7836     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7837     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7838     MFI->setAdjustsStack(true);
7839
7840     // And our return value (tls address) is in the standard call return value
7841     // location.
7842     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7843     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7844                               Chain.getValue(1));
7845   }
7846
7847   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7848     // Just use the implicit TLS architecture
7849     // Need to generate someting similar to:
7850     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7851     //                                  ; from TEB
7852     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7853     //   mov     rcx, qword [rdx+rcx*8]
7854     //   mov     eax, .tls$:tlsvar
7855     //   [rax+rcx] contains the address
7856     // Windows 64bit: gs:0x58
7857     // Windows 32bit: fs:__tls_array
7858
7859     // If GV is an alias then use the aliasee for determining
7860     // thread-localness.
7861     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7862       GV = GA->resolveAliasedGlobal(false);
7863     DebugLoc dl = GA->getDebugLoc();
7864     SDValue Chain = DAG.getEntryNode();
7865
7866     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7867     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7868     // use its literal value of 0x2C.
7869     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7870                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7871                                                              256)
7872                                         : Type::getInt32PtrTy(*DAG.getContext(),
7873                                                               257));
7874
7875     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7876       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7877         DAG.getExternalSymbol("_tls_array", getPointerTy()));
7878
7879     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7880                                         MachinePointerInfo(Ptr),
7881                                         false, false, false, 0);
7882
7883     // Load the _tls_index variable
7884     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7885     if (Subtarget->is64Bit())
7886       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7887                            IDX, MachinePointerInfo(), MVT::i32,
7888                            false, false, 0);
7889     else
7890       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7891                         false, false, false, 0);
7892
7893     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7894                                     getPointerTy());
7895     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7896
7897     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7898     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7899                       false, false, false, 0);
7900
7901     // Get the offset of start of .tls section
7902     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7903                                              GA->getValueType(0),
7904                                              GA->getOffset(), X86II::MO_SECREL);
7905     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7906
7907     // The address of the thread local variable is the add of the thread
7908     // pointer with the offset of the variable.
7909     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7910   }
7911
7912   llvm_unreachable("TLS not implemented for this target.");
7913 }
7914
7915 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7916 /// and take a 2 x i32 value to shift plus a shift amount.
7917 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7918   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7919   EVT VT = Op.getValueType();
7920   unsigned VTBits = VT.getSizeInBits();
7921   DebugLoc dl = Op.getDebugLoc();
7922   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7923   SDValue ShOpLo = Op.getOperand(0);
7924   SDValue ShOpHi = Op.getOperand(1);
7925   SDValue ShAmt  = Op.getOperand(2);
7926   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7927                                      DAG.getConstant(VTBits - 1, MVT::i8))
7928                        : DAG.getConstant(0, VT);
7929
7930   SDValue Tmp2, Tmp3;
7931   if (Op.getOpcode() == ISD::SHL_PARTS) {
7932     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7933     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7934   } else {
7935     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7936     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7937   }
7938
7939   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7940                                 DAG.getConstant(VTBits, MVT::i8));
7941   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7942                              AndNode, DAG.getConstant(0, MVT::i8));
7943
7944   SDValue Hi, Lo;
7945   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7946   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7947   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7948
7949   if (Op.getOpcode() == ISD::SHL_PARTS) {
7950     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7951     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7952   } else {
7953     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7954     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7955   }
7956
7957   SDValue Ops[2] = { Lo, Hi };
7958   return DAG.getMergeValues(Ops, 2, dl);
7959 }
7960
7961 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7962                                            SelectionDAG &DAG) const {
7963   EVT SrcVT = Op.getOperand(0).getValueType();
7964
7965   if (SrcVT.isVector())
7966     return SDValue();
7967
7968   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7969          "Unknown SINT_TO_FP to lower!");
7970
7971   // These are really Legal; return the operand so the caller accepts it as
7972   // Legal.
7973   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7974     return Op;
7975   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7976       Subtarget->is64Bit()) {
7977     return Op;
7978   }
7979
7980   DebugLoc dl = Op.getDebugLoc();
7981   unsigned Size = SrcVT.getSizeInBits()/8;
7982   MachineFunction &MF = DAG.getMachineFunction();
7983   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7984   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7985   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7986                                StackSlot,
7987                                MachinePointerInfo::getFixedStack(SSFI),
7988                                false, false, 0);
7989   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7990 }
7991
7992 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7993                                      SDValue StackSlot,
7994                                      SelectionDAG &DAG) const {
7995   // Build the FILD
7996   DebugLoc DL = Op.getDebugLoc();
7997   SDVTList Tys;
7998   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7999   if (useSSE)
8000     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8001   else
8002     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8003
8004   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8005
8006   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8007   MachineMemOperand *MMO;
8008   if (FI) {
8009     int SSFI = FI->getIndex();
8010     MMO =
8011       DAG.getMachineFunction()
8012       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8013                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8014   } else {
8015     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8016     StackSlot = StackSlot.getOperand(1);
8017   }
8018   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8019   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8020                                            X86ISD::FILD, DL,
8021                                            Tys, Ops, array_lengthof(Ops),
8022                                            SrcVT, MMO);
8023
8024   if (useSSE) {
8025     Chain = Result.getValue(1);
8026     SDValue InFlag = Result.getValue(2);
8027
8028     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8029     // shouldn't be necessary except that RFP cannot be live across
8030     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8031     MachineFunction &MF = DAG.getMachineFunction();
8032     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8033     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8034     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8035     Tys = DAG.getVTList(MVT::Other);
8036     SDValue Ops[] = {
8037       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8038     };
8039     MachineMemOperand *MMO =
8040       DAG.getMachineFunction()
8041       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8042                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8043
8044     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8045                                     Ops, array_lengthof(Ops),
8046                                     Op.getValueType(), MMO);
8047     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8048                          MachinePointerInfo::getFixedStack(SSFI),
8049                          false, false, false, 0);
8050   }
8051
8052   return Result;
8053 }
8054
8055 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8056 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8057                                                SelectionDAG &DAG) const {
8058   // This algorithm is not obvious. Here it is what we're trying to output:
8059   /*
8060      movq       %rax,  %xmm0
8061      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8062      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8063      #ifdef __SSE3__
8064        haddpd   %xmm0, %xmm0
8065      #else
8066        pshufd   $0x4e, %xmm0, %xmm1
8067        addpd    %xmm1, %xmm0
8068      #endif
8069   */
8070
8071   DebugLoc dl = Op.getDebugLoc();
8072   LLVMContext *Context = DAG.getContext();
8073
8074   // Build some magic constants.
8075   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8076   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8077   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8078
8079   SmallVector<Constant*,2> CV1;
8080   CV1.push_back(
8081     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8082                                       APInt(64, 0x4330000000000000ULL))));
8083   CV1.push_back(
8084     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8085                                       APInt(64, 0x4530000000000000ULL))));
8086   Constant *C1 = ConstantVector::get(CV1);
8087   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8088
8089   // Load the 64-bit value into an XMM register.
8090   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8091                             Op.getOperand(0));
8092   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8093                               MachinePointerInfo::getConstantPool(),
8094                               false, false, false, 16);
8095   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8096                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8097                               CLod0);
8098
8099   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8100                               MachinePointerInfo::getConstantPool(),
8101                               false, false, false, 16);
8102   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8103   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8104   SDValue Result;
8105
8106   if (Subtarget->hasSSE3()) {
8107     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8108     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8109   } else {
8110     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8111     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8112                                            S2F, 0x4E, DAG);
8113     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8114                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8115                          Sub);
8116   }
8117
8118   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8119                      DAG.getIntPtrConstant(0));
8120 }
8121
8122 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8123 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8124                                                SelectionDAG &DAG) const {
8125   DebugLoc dl = Op.getDebugLoc();
8126   // FP constant to bias correct the final result.
8127   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8128                                    MVT::f64);
8129
8130   // Load the 32-bit value into an XMM register.
8131   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8132                              Op.getOperand(0));
8133
8134   // Zero out the upper parts of the register.
8135   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8136
8137   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8138                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8139                      DAG.getIntPtrConstant(0));
8140
8141   // Or the load with the bias.
8142   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8143                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8144                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8145                                                    MVT::v2f64, Load)),
8146                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8147                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8148                                                    MVT::v2f64, Bias)));
8149   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8150                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8151                    DAG.getIntPtrConstant(0));
8152
8153   // Subtract the bias.
8154   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8155
8156   // Handle final rounding.
8157   EVT DestVT = Op.getValueType();
8158
8159   if (DestVT.bitsLT(MVT::f64))
8160     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8161                        DAG.getIntPtrConstant(0));
8162   if (DestVT.bitsGT(MVT::f64))
8163     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8164
8165   // Handle final rounding.
8166   return Sub;
8167 }
8168
8169 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8170                                                SelectionDAG &DAG) const {
8171   SDValue N0 = Op.getOperand(0);
8172   EVT SVT = N0.getValueType();
8173   DebugLoc dl = Op.getDebugLoc();
8174
8175   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8176           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8177          "Custom UINT_TO_FP is not supported!");
8178
8179   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8180                              SVT.getVectorNumElements());
8181   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8182                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8183 }
8184
8185 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8186                                            SelectionDAG &DAG) const {
8187   SDValue N0 = Op.getOperand(0);
8188   DebugLoc dl = Op.getDebugLoc();
8189
8190   if (Op.getValueType().isVector())
8191     return lowerUINT_TO_FP_vec(Op, DAG);
8192
8193   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8194   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8195   // the optimization here.
8196   if (DAG.SignBitIsZero(N0))
8197     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8198
8199   EVT SrcVT = N0.getValueType();
8200   EVT DstVT = Op.getValueType();
8201   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8202     return LowerUINT_TO_FP_i64(Op, DAG);
8203   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8204     return LowerUINT_TO_FP_i32(Op, DAG);
8205   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8206     return SDValue();
8207
8208   // Make a 64-bit buffer, and use it to build an FILD.
8209   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8210   if (SrcVT == MVT::i32) {
8211     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8212     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8213                                      getPointerTy(), StackSlot, WordOff);
8214     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8215                                   StackSlot, MachinePointerInfo(),
8216                                   false, false, 0);
8217     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8218                                   OffsetSlot, MachinePointerInfo(),
8219                                   false, false, 0);
8220     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8221     return Fild;
8222   }
8223
8224   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8225   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8226                                StackSlot, MachinePointerInfo(),
8227                                false, false, 0);
8228   // For i64 source, we need to add the appropriate power of 2 if the input
8229   // was negative.  This is the same as the optimization in
8230   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8231   // we must be careful to do the computation in x87 extended precision, not
8232   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8233   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8234   MachineMemOperand *MMO =
8235     DAG.getMachineFunction()
8236     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8237                           MachineMemOperand::MOLoad, 8, 8);
8238
8239   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8240   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8241   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8242                                          MVT::i64, MMO);
8243
8244   APInt FF(32, 0x5F800000ULL);
8245
8246   // Check whether the sign bit is set.
8247   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8248                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8249                                  ISD::SETLT);
8250
8251   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8252   SDValue FudgePtr = DAG.getConstantPool(
8253                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8254                                          getPointerTy());
8255
8256   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8257   SDValue Zero = DAG.getIntPtrConstant(0);
8258   SDValue Four = DAG.getIntPtrConstant(4);
8259   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8260                                Zero, Four);
8261   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8262
8263   // Load the value out, extending it from f32 to f80.
8264   // FIXME: Avoid the extend by constructing the right constant pool?
8265   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8266                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8267                                  MVT::f32, false, false, 4);
8268   // Extend everything to 80 bits to force it to be done on x87.
8269   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8270   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8271 }
8272
8273 std::pair<SDValue,SDValue>
8274 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8275                                     bool IsSigned, bool IsReplace) const {
8276   DebugLoc DL = Op.getDebugLoc();
8277
8278   EVT DstTy = Op.getValueType();
8279
8280   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8281     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8282     DstTy = MVT::i64;
8283   }
8284
8285   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8286          DstTy.getSimpleVT() >= MVT::i16 &&
8287          "Unknown FP_TO_INT to lower!");
8288
8289   // These are really Legal.
8290   if (DstTy == MVT::i32 &&
8291       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8292     return std::make_pair(SDValue(), SDValue());
8293   if (Subtarget->is64Bit() &&
8294       DstTy == MVT::i64 &&
8295       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8296     return std::make_pair(SDValue(), SDValue());
8297
8298   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8299   // stack slot, or into the FTOL runtime function.
8300   MachineFunction &MF = DAG.getMachineFunction();
8301   unsigned MemSize = DstTy.getSizeInBits()/8;
8302   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8303   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8304
8305   unsigned Opc;
8306   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8307     Opc = X86ISD::WIN_FTOL;
8308   else
8309     switch (DstTy.getSimpleVT().SimpleTy) {
8310     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8311     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8312     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8313     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8314     }
8315
8316   SDValue Chain = DAG.getEntryNode();
8317   SDValue Value = Op.getOperand(0);
8318   EVT TheVT = Op.getOperand(0).getValueType();
8319   // FIXME This causes a redundant load/store if the SSE-class value is already
8320   // in memory, such as if it is on the callstack.
8321   if (isScalarFPTypeInSSEReg(TheVT)) {
8322     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8323     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8324                          MachinePointerInfo::getFixedStack(SSFI),
8325                          false, false, 0);
8326     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8327     SDValue Ops[] = {
8328       Chain, StackSlot, DAG.getValueType(TheVT)
8329     };
8330
8331     MachineMemOperand *MMO =
8332       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8333                               MachineMemOperand::MOLoad, MemSize, MemSize);
8334     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8335                                     DstTy, MMO);
8336     Chain = Value.getValue(1);
8337     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8338     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8339   }
8340
8341   MachineMemOperand *MMO =
8342     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8343                             MachineMemOperand::MOStore, MemSize, MemSize);
8344
8345   if (Opc != X86ISD::WIN_FTOL) {
8346     // Build the FP_TO_INT*_IN_MEM
8347     SDValue Ops[] = { Chain, Value, StackSlot };
8348     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8349                                            Ops, 3, DstTy, MMO);
8350     return std::make_pair(FIST, StackSlot);
8351   } else {
8352     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8353       DAG.getVTList(MVT::Other, MVT::Glue),
8354       Chain, Value);
8355     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8356       MVT::i32, ftol.getValue(1));
8357     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8358       MVT::i32, eax.getValue(2));
8359     SDValue Ops[] = { eax, edx };
8360     SDValue pair = IsReplace
8361       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, 2)
8362       : DAG.getMergeValues(Ops, 2, DL);
8363     return std::make_pair(pair, SDValue());
8364   }
8365 }
8366
8367 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8368                               const X86Subtarget *Subtarget) {
8369   MVT VT = Op->getValueType(0).getSimpleVT();
8370   SDValue In = Op->getOperand(0);
8371   MVT InVT = In.getValueType().getSimpleVT();
8372   DebugLoc dl = Op->getDebugLoc();
8373
8374   // Optimize vectors in AVX mode:
8375   //
8376   //   v8i16 -> v8i32
8377   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8378   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8379   //   Concat upper and lower parts.
8380   //
8381   //   v4i32 -> v4i64
8382   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8383   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8384   //   Concat upper and lower parts.
8385   //
8386
8387   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8388       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8389     return SDValue();
8390
8391   if (Subtarget->hasInt256())
8392     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8393
8394   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8395   SDValue Undef = DAG.getUNDEF(InVT);
8396   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8397   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8398   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8399
8400   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8401                              VT.getVectorNumElements()/2);
8402
8403   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8404   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8405
8406   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8407 }
8408
8409 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8410                                            SelectionDAG &DAG) const {
8411   if (Subtarget->hasFp256()) {
8412     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8413     if (Res.getNode())
8414       return Res;
8415   }
8416
8417   return SDValue();
8418 }
8419 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8420                                             SelectionDAG &DAG) const {
8421   DebugLoc DL = Op.getDebugLoc();
8422   MVT VT = Op.getValueType().getSimpleVT();
8423   SDValue In = Op.getOperand(0);
8424   MVT SVT = In.getValueType().getSimpleVT();
8425
8426   if (Subtarget->hasFp256()) {
8427     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8428     if (Res.getNode())
8429       return Res;
8430   }
8431
8432   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8433       VT.getVectorNumElements() != SVT.getVectorNumElements())
8434     return SDValue();
8435
8436   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8437
8438   // AVX2 has better support of integer extending.
8439   if (Subtarget->hasInt256())
8440     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8441
8442   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8443   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8444   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8445                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8446                                                 DAG.getUNDEF(MVT::v8i16),
8447                                                 &Mask[0]));
8448
8449   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8450 }
8451
8452 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8453   DebugLoc DL = Op.getDebugLoc();
8454   MVT VT = Op.getValueType().getSimpleVT();
8455   SDValue In = Op.getOperand(0);
8456   MVT SVT = In.getValueType().getSimpleVT();
8457
8458   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8459     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8460     if (Subtarget->hasInt256()) {
8461       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8462       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8463       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8464                                 ShufMask);
8465       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8466                          DAG.getIntPtrConstant(0));
8467     }
8468
8469     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8470     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8471                                DAG.getIntPtrConstant(0));
8472     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8473                                DAG.getIntPtrConstant(2));
8474
8475     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8476     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8477
8478     // The PSHUFD mask:
8479     static const int ShufMask1[] = {0, 2, 0, 0};
8480     SDValue Undef = DAG.getUNDEF(VT);
8481     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8482     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8483
8484     // The MOVLHPS mask:
8485     static const int ShufMask2[] = {0, 1, 4, 5};
8486     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8487   }
8488
8489   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8490     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8491     if (Subtarget->hasInt256()) {
8492       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8493
8494       SmallVector<SDValue,32> pshufbMask;
8495       for (unsigned i = 0; i < 2; ++i) {
8496         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8497         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8498         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8499         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8500         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8501         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8502         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8503         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8504         for (unsigned j = 0; j < 8; ++j)
8505           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8506       }
8507       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8508                                &pshufbMask[0], 32);
8509       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8510       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8511
8512       static const int ShufMask[] = {0,  2,  -1,  -1};
8513       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8514                                 &ShufMask[0]);
8515       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8516                        DAG.getIntPtrConstant(0));
8517       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8518     }
8519
8520     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8521                                DAG.getIntPtrConstant(0));
8522
8523     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8524                                DAG.getIntPtrConstant(4));
8525
8526     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8527     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8528
8529     // The PSHUFB mask:
8530     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8531                                    -1, -1, -1, -1, -1, -1, -1, -1};
8532
8533     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8534     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8535     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8536
8537     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8538     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8539
8540     // The MOVLHPS Mask:
8541     static const int ShufMask2[] = {0, 1, 4, 5};
8542     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8543     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8544   }
8545
8546   // Handle truncation of V256 to V128 using shuffles.
8547   if (!VT.is128BitVector() || !SVT.is256BitVector())
8548     return SDValue();
8549
8550   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8551          "Invalid op");
8552   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8553
8554   unsigned NumElems = VT.getVectorNumElements();
8555   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8556                              NumElems * 2);
8557
8558   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8559   // Prepare truncation shuffle mask
8560   for (unsigned i = 0; i != NumElems; ++i)
8561     MaskVec[i] = i * 2;
8562   SDValue V = DAG.getVectorShuffle(NVT, DL,
8563                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8564                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8565   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8566                      DAG.getIntPtrConstant(0));
8567 }
8568
8569 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8570                                            SelectionDAG &DAG) const {
8571   MVT VT = Op.getValueType().getSimpleVT();
8572   if (VT.isVector()) {
8573     if (VT == MVT::v8i16)
8574       return DAG.getNode(ISD::TRUNCATE, Op.getDebugLoc(), VT,
8575                          DAG.getNode(ISD::FP_TO_SINT, Op.getDebugLoc(),
8576                                      MVT::v8i32, Op.getOperand(0)));
8577     return SDValue();
8578   }
8579
8580   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8581     /*IsSigned=*/ true, /*IsReplace=*/ false);
8582   SDValue FIST = Vals.first, StackSlot = Vals.second;
8583   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8584   if (FIST.getNode() == 0) return Op;
8585
8586   if (StackSlot.getNode())
8587     // Load the result.
8588     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8589                        FIST, StackSlot, MachinePointerInfo(),
8590                        false, false, false, 0);
8591
8592   // The node is the result.
8593   return FIST;
8594 }
8595
8596 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8597                                            SelectionDAG &DAG) const {
8598   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8599     /*IsSigned=*/ false, /*IsReplace=*/ false);
8600   SDValue FIST = Vals.first, StackSlot = Vals.second;
8601   assert(FIST.getNode() && "Unexpected failure");
8602
8603   if (StackSlot.getNode())
8604     // Load the result.
8605     return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8606                        FIST, StackSlot, MachinePointerInfo(),
8607                        false, false, false, 0);
8608
8609   // The node is the result.
8610   return FIST;
8611 }
8612
8613 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8614   DebugLoc DL = Op.getDebugLoc();
8615   MVT VT = Op.getValueType().getSimpleVT();
8616   SDValue In = Op.getOperand(0);
8617   MVT SVT = In.getValueType().getSimpleVT();
8618
8619   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8620
8621   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8622                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8623                                  In, DAG.getUNDEF(SVT)));
8624 }
8625
8626 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8627   LLVMContext *Context = DAG.getContext();
8628   DebugLoc dl = Op.getDebugLoc();
8629   MVT VT = Op.getValueType().getSimpleVT();
8630   MVT EltVT = VT;
8631   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8632   if (VT.isVector()) {
8633     EltVT = VT.getVectorElementType();
8634     NumElts = VT.getVectorNumElements();
8635   }
8636   Constant *C;
8637   if (EltVT == MVT::f64)
8638     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8639                                           APInt(64, ~(1ULL << 63))));
8640   else
8641     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8642                                           APInt(32, ~(1U << 31))));
8643   C = ConstantVector::getSplat(NumElts, C);
8644   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8645   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8646   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8647                              MachinePointerInfo::getConstantPool(),
8648                              false, false, false, Alignment);
8649   if (VT.isVector()) {
8650     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8651     return DAG.getNode(ISD::BITCAST, dl, VT,
8652                        DAG.getNode(ISD::AND, dl, ANDVT,
8653                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8654                                                Op.getOperand(0)),
8655                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8656   }
8657   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8658 }
8659
8660 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8661   LLVMContext *Context = DAG.getContext();
8662   DebugLoc dl = Op.getDebugLoc();
8663   MVT VT = Op.getValueType().getSimpleVT();
8664   MVT EltVT = VT;
8665   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8666   if (VT.isVector()) {
8667     EltVT = VT.getVectorElementType();
8668     NumElts = VT.getVectorNumElements();
8669   }
8670   Constant *C;
8671   if (EltVT == MVT::f64)
8672     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8673                                           APInt(64, 1ULL << 63)));
8674   else
8675     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8676                                           APInt(32, 1U << 31)));
8677   C = ConstantVector::getSplat(NumElts, C);
8678   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8679   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8680   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8681                              MachinePointerInfo::getConstantPool(),
8682                              false, false, false, Alignment);
8683   if (VT.isVector()) {
8684     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8685     return DAG.getNode(ISD::BITCAST, dl, VT,
8686                        DAG.getNode(ISD::XOR, dl, XORVT,
8687                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8688                                                Op.getOperand(0)),
8689                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8690   }
8691
8692   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8693 }
8694
8695 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8696   LLVMContext *Context = DAG.getContext();
8697   SDValue Op0 = Op.getOperand(0);
8698   SDValue Op1 = Op.getOperand(1);
8699   DebugLoc dl = Op.getDebugLoc();
8700   MVT VT = Op.getValueType().getSimpleVT();
8701   MVT SrcVT = Op1.getValueType().getSimpleVT();
8702
8703   // If second operand is smaller, extend it first.
8704   if (SrcVT.bitsLT(VT)) {
8705     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8706     SrcVT = VT;
8707   }
8708   // And if it is bigger, shrink it first.
8709   if (SrcVT.bitsGT(VT)) {
8710     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8711     SrcVT = VT;
8712   }
8713
8714   // At this point the operands and the result should have the same
8715   // type, and that won't be f80 since that is not custom lowered.
8716
8717   // First get the sign bit of second operand.
8718   SmallVector<Constant*,4> CV;
8719   if (SrcVT == MVT::f64) {
8720     const fltSemantics &Sem = APFloat::IEEEdouble;
8721     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8722     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8723   } else {
8724     const fltSemantics &Sem = APFloat::IEEEsingle;
8725     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8726     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8727     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8728     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8729   }
8730   Constant *C = ConstantVector::get(CV);
8731   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8732   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8733                               MachinePointerInfo::getConstantPool(),
8734                               false, false, false, 16);
8735   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8736
8737   // Shift sign bit right or left if the two operands have different types.
8738   if (SrcVT.bitsGT(VT)) {
8739     // Op0 is MVT::f32, Op1 is MVT::f64.
8740     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8741     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8742                           DAG.getConstant(32, MVT::i32));
8743     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8744     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8745                           DAG.getIntPtrConstant(0));
8746   }
8747
8748   // Clear first operand sign bit.
8749   CV.clear();
8750   if (VT == MVT::f64) {
8751     const fltSemantics &Sem = APFloat::IEEEdouble;
8752     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8753                                                    APInt(64, ~(1ULL << 63)))));
8754     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8755   } else {
8756     const fltSemantics &Sem = APFloat::IEEEsingle;
8757     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8758                                                    APInt(32, ~(1U << 31)))));
8759     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8760     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8761     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8762   }
8763   C = ConstantVector::get(CV);
8764   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8765   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8766                               MachinePointerInfo::getConstantPool(),
8767                               false, false, false, 16);
8768   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8769
8770   // Or the value with the sign bit.
8771   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8772 }
8773
8774 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8775   SDValue N0 = Op.getOperand(0);
8776   DebugLoc dl = Op.getDebugLoc();
8777   MVT VT = Op.getValueType().getSimpleVT();
8778
8779   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8780   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8781                                   DAG.getConstant(1, VT));
8782   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8783 }
8784
8785 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8786 //
8787 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8788                                                   SelectionDAG &DAG) const {
8789   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8790
8791   if (!Subtarget->hasSSE41())
8792     return SDValue();
8793
8794   if (!Op->hasOneUse())
8795     return SDValue();
8796
8797   SDNode *N = Op.getNode();
8798   DebugLoc DL = N->getDebugLoc();
8799
8800   SmallVector<SDValue, 8> Opnds;
8801   DenseMap<SDValue, unsigned> VecInMap;
8802   EVT VT = MVT::Other;
8803
8804   // Recognize a special case where a vector is casted into wide integer to
8805   // test all 0s.
8806   Opnds.push_back(N->getOperand(0));
8807   Opnds.push_back(N->getOperand(1));
8808
8809   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8810     SmallVector<SDValue, 8>::const_iterator I = Opnds.begin() + Slot;
8811     // BFS traverse all OR'd operands.
8812     if (I->getOpcode() == ISD::OR) {
8813       Opnds.push_back(I->getOperand(0));
8814       Opnds.push_back(I->getOperand(1));
8815       // Re-evaluate the number of nodes to be traversed.
8816       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8817       continue;
8818     }
8819
8820     // Quit if a non-EXTRACT_VECTOR_ELT
8821     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8822       return SDValue();
8823
8824     // Quit if without a constant index.
8825     SDValue Idx = I->getOperand(1);
8826     if (!isa<ConstantSDNode>(Idx))
8827       return SDValue();
8828
8829     SDValue ExtractedFromVec = I->getOperand(0);
8830     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8831     if (M == VecInMap.end()) {
8832       VT = ExtractedFromVec.getValueType();
8833       // Quit if not 128/256-bit vector.
8834       if (!VT.is128BitVector() && !VT.is256BitVector())
8835         return SDValue();
8836       // Quit if not the same type.
8837       if (VecInMap.begin() != VecInMap.end() &&
8838           VT != VecInMap.begin()->first.getValueType())
8839         return SDValue();
8840       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8841     }
8842     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8843   }
8844
8845   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8846          "Not extracted from 128-/256-bit vector.");
8847
8848   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8849   SmallVector<SDValue, 8> VecIns;
8850
8851   for (DenseMap<SDValue, unsigned>::const_iterator
8852         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8853     // Quit if not all elements are used.
8854     if (I->second != FullMask)
8855       return SDValue();
8856     VecIns.push_back(I->first);
8857   }
8858
8859   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8860
8861   // Cast all vectors into TestVT for PTEST.
8862   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8863     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8864
8865   // If more than one full vectors are evaluated, OR them first before PTEST.
8866   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8867     // Each iteration will OR 2 nodes and append the result until there is only
8868     // 1 node left, i.e. the final OR'd value of all vectors.
8869     SDValue LHS = VecIns[Slot];
8870     SDValue RHS = VecIns[Slot + 1];
8871     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8872   }
8873
8874   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8875                      VecIns.back(), VecIns.back());
8876 }
8877
8878 /// Emit nodes that will be selected as "test Op0,Op0", or something
8879 /// equivalent.
8880 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8881                                     SelectionDAG &DAG) const {
8882   DebugLoc dl = Op.getDebugLoc();
8883
8884   // CF and OF aren't always set the way we want. Determine which
8885   // of these we need.
8886   bool NeedCF = false;
8887   bool NeedOF = false;
8888   switch (X86CC) {
8889   default: break;
8890   case X86::COND_A: case X86::COND_AE:
8891   case X86::COND_B: case X86::COND_BE:
8892     NeedCF = true;
8893     break;
8894   case X86::COND_G: case X86::COND_GE:
8895   case X86::COND_L: case X86::COND_LE:
8896   case X86::COND_O: case X86::COND_NO:
8897     NeedOF = true;
8898     break;
8899   }
8900
8901   // See if we can use the EFLAGS value from the operand instead of
8902   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8903   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8904   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8905     // Emit a CMP with 0, which is the TEST pattern.
8906     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8907                        DAG.getConstant(0, Op.getValueType()));
8908
8909   unsigned Opcode = 0;
8910   unsigned NumOperands = 0;
8911
8912   // Truncate operations may prevent the merge of the SETCC instruction
8913   // and the arithmetic intruction before it. Attempt to truncate the operands
8914   // of the arithmetic instruction and use a reduced bit-width instruction.
8915   bool NeedTruncation = false;
8916   SDValue ArithOp = Op;
8917   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8918     SDValue Arith = Op->getOperand(0);
8919     // Both the trunc and the arithmetic op need to have one user each.
8920     if (Arith->hasOneUse())
8921       switch (Arith.getOpcode()) {
8922         default: break;
8923         case ISD::ADD:
8924         case ISD::SUB:
8925         case ISD::AND:
8926         case ISD::OR:
8927         case ISD::XOR: {
8928           NeedTruncation = true;
8929           ArithOp = Arith;
8930         }
8931       }
8932   }
8933
8934   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8935   // which may be the result of a CAST.  We use the variable 'Op', which is the
8936   // non-casted variable when we check for possible users.
8937   switch (ArithOp.getOpcode()) {
8938   case ISD::ADD:
8939     // Due to an isel shortcoming, be conservative if this add is likely to be
8940     // selected as part of a load-modify-store instruction. When the root node
8941     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8942     // uses of other nodes in the match, such as the ADD in this case. This
8943     // leads to the ADD being left around and reselected, with the result being
8944     // two adds in the output.  Alas, even if none our users are stores, that
8945     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8946     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8947     // climbing the DAG back to the root, and it doesn't seem to be worth the
8948     // effort.
8949     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8950          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8951       if (UI->getOpcode() != ISD::CopyToReg &&
8952           UI->getOpcode() != ISD::SETCC &&
8953           UI->getOpcode() != ISD::STORE)
8954         goto default_case;
8955
8956     if (ConstantSDNode *C =
8957         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8958       // An add of one will be selected as an INC.
8959       if (C->getAPIntValue() == 1) {
8960         Opcode = X86ISD::INC;
8961         NumOperands = 1;
8962         break;
8963       }
8964
8965       // An add of negative one (subtract of one) will be selected as a DEC.
8966       if (C->getAPIntValue().isAllOnesValue()) {
8967         Opcode = X86ISD::DEC;
8968         NumOperands = 1;
8969         break;
8970       }
8971     }
8972
8973     // Otherwise use a regular EFLAGS-setting add.
8974     Opcode = X86ISD::ADD;
8975     NumOperands = 2;
8976     break;
8977   case ISD::AND: {
8978     // If the primary and result isn't used, don't bother using X86ISD::AND,
8979     // because a TEST instruction will be better.
8980     bool NonFlagUse = false;
8981     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8982            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8983       SDNode *User = *UI;
8984       unsigned UOpNo = UI.getOperandNo();
8985       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8986         // Look pass truncate.
8987         UOpNo = User->use_begin().getOperandNo();
8988         User = *User->use_begin();
8989       }
8990
8991       if (User->getOpcode() != ISD::BRCOND &&
8992           User->getOpcode() != ISD::SETCC &&
8993           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
8994         NonFlagUse = true;
8995         break;
8996       }
8997     }
8998
8999     if (!NonFlagUse)
9000       break;
9001   }
9002     // FALL THROUGH
9003   case ISD::SUB:
9004   case ISD::OR:
9005   case ISD::XOR:
9006     // Due to the ISEL shortcoming noted above, be conservative if this op is
9007     // likely to be selected as part of a load-modify-store instruction.
9008     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9009            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9010       if (UI->getOpcode() == ISD::STORE)
9011         goto default_case;
9012
9013     // Otherwise use a regular EFLAGS-setting instruction.
9014     switch (ArithOp.getOpcode()) {
9015     default: llvm_unreachable("unexpected operator!");
9016     case ISD::SUB: Opcode = X86ISD::SUB; break;
9017     case ISD::XOR: Opcode = X86ISD::XOR; break;
9018     case ISD::AND: Opcode = X86ISD::AND; break;
9019     case ISD::OR: {
9020       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9021         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9022         if (EFLAGS.getNode())
9023           return EFLAGS;
9024       }
9025       Opcode = X86ISD::OR;
9026       break;
9027     }
9028     }
9029
9030     NumOperands = 2;
9031     break;
9032   case X86ISD::ADD:
9033   case X86ISD::SUB:
9034   case X86ISD::INC:
9035   case X86ISD::DEC:
9036   case X86ISD::OR:
9037   case X86ISD::XOR:
9038   case X86ISD::AND:
9039     return SDValue(Op.getNode(), 1);
9040   default:
9041   default_case:
9042     break;
9043   }
9044
9045   // If we found that truncation is beneficial, perform the truncation and
9046   // update 'Op'.
9047   if (NeedTruncation) {
9048     EVT VT = Op.getValueType();
9049     SDValue WideVal = Op->getOperand(0);
9050     EVT WideVT = WideVal.getValueType();
9051     unsigned ConvertedOp = 0;
9052     // Use a target machine opcode to prevent further DAGCombine
9053     // optimizations that may separate the arithmetic operations
9054     // from the setcc node.
9055     switch (WideVal.getOpcode()) {
9056       default: break;
9057       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9058       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9059       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9060       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9061       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9062     }
9063
9064     if (ConvertedOp) {
9065       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9066       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9067         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9068         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9069         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9070       }
9071     }
9072   }
9073
9074   if (Opcode == 0)
9075     // Emit a CMP with 0, which is the TEST pattern.
9076     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9077                        DAG.getConstant(0, Op.getValueType()));
9078
9079   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9080   SmallVector<SDValue, 4> Ops;
9081   for (unsigned i = 0; i != NumOperands; ++i)
9082     Ops.push_back(Op.getOperand(i));
9083
9084   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9085   DAG.ReplaceAllUsesWith(Op, New);
9086   return SDValue(New.getNode(), 1);
9087 }
9088
9089 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9090 /// equivalent.
9091 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9092                                    SelectionDAG &DAG) const {
9093   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9094     if (C->getAPIntValue() == 0)
9095       return EmitTest(Op0, X86CC, DAG);
9096
9097   DebugLoc dl = Op0.getDebugLoc();
9098   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9099        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9100     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9101     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9102     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9103                               Op0, Op1);
9104     return SDValue(Sub.getNode(), 1);
9105   }
9106   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9107 }
9108
9109 /// Convert a comparison if required by the subtarget.
9110 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9111                                                  SelectionDAG &DAG) const {
9112   // If the subtarget does not support the FUCOMI instruction, floating-point
9113   // comparisons have to be converted.
9114   if (Subtarget->hasCMov() ||
9115       Cmp.getOpcode() != X86ISD::CMP ||
9116       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9117       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9118     return Cmp;
9119
9120   // The instruction selector will select an FUCOM instruction instead of
9121   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9122   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9123   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9124   DebugLoc dl = Cmp.getDebugLoc();
9125   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9126   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9127   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9128                             DAG.getConstant(8, MVT::i8));
9129   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9130   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9131 }
9132
9133 static bool isAllOnes(SDValue V) {
9134   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9135   return C && C->isAllOnesValue();
9136 }
9137
9138 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9139 /// if it's possible.
9140 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9141                                      DebugLoc dl, SelectionDAG &DAG) const {
9142   SDValue Op0 = And.getOperand(0);
9143   SDValue Op1 = And.getOperand(1);
9144   if (Op0.getOpcode() == ISD::TRUNCATE)
9145     Op0 = Op0.getOperand(0);
9146   if (Op1.getOpcode() == ISD::TRUNCATE)
9147     Op1 = Op1.getOperand(0);
9148
9149   SDValue LHS, RHS;
9150   if (Op1.getOpcode() == ISD::SHL)
9151     std::swap(Op0, Op1);
9152   if (Op0.getOpcode() == ISD::SHL) {
9153     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9154       if (And00C->getZExtValue() == 1) {
9155         // If we looked past a truncate, check that it's only truncating away
9156         // known zeros.
9157         unsigned BitWidth = Op0.getValueSizeInBits();
9158         unsigned AndBitWidth = And.getValueSizeInBits();
9159         if (BitWidth > AndBitWidth) {
9160           APInt Zeros, Ones;
9161           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9162           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9163             return SDValue();
9164         }
9165         LHS = Op1;
9166         RHS = Op0.getOperand(1);
9167       }
9168   } else if (Op1.getOpcode() == ISD::Constant) {
9169     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9170     uint64_t AndRHSVal = AndRHS->getZExtValue();
9171     SDValue AndLHS = Op0;
9172
9173     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9174       LHS = AndLHS.getOperand(0);
9175       RHS = AndLHS.getOperand(1);
9176     }
9177
9178     // Use BT if the immediate can't be encoded in a TEST instruction.
9179     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9180       LHS = AndLHS;
9181       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9182     }
9183   }
9184
9185   if (LHS.getNode()) {
9186     // If the LHS is of the form (x ^ -1) then replace the LHS with x and flip
9187     // the condition code later.
9188     bool Invert = false;
9189     if (LHS.getOpcode() == ISD::XOR && isAllOnes(LHS.getOperand(1))) {
9190       Invert = true;
9191       LHS = LHS.getOperand(0);
9192     }
9193
9194     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9195     // instruction.  Since the shift amount is in-range-or-undefined, we know
9196     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9197     // the encoding for the i16 version is larger than the i32 version.
9198     // Also promote i16 to i32 for performance / code size reason.
9199     if (LHS.getValueType() == MVT::i8 ||
9200         LHS.getValueType() == MVT::i16)
9201       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9202
9203     // If the operand types disagree, extend the shift amount to match.  Since
9204     // BT ignores high bits (like shifts) we can use anyextend.
9205     if (LHS.getValueType() != RHS.getValueType())
9206       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9207
9208     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9209     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9210     // Flip the condition if the LHS was a not instruction
9211     if (Invert)
9212       Cond = X86::GetOppositeBranchCondition(Cond);
9213     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9214                        DAG.getConstant(Cond, MVT::i8), BT);
9215   }
9216
9217   return SDValue();
9218 }
9219
9220 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9221 // ones, and then concatenate the result back.
9222 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9223   MVT VT = Op.getValueType().getSimpleVT();
9224
9225   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9226          "Unsupported value type for operation");
9227
9228   unsigned NumElems = VT.getVectorNumElements();
9229   DebugLoc dl = Op.getDebugLoc();
9230   SDValue CC = Op.getOperand(2);
9231
9232   // Extract the LHS vectors
9233   SDValue LHS = Op.getOperand(0);
9234   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9235   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9236
9237   // Extract the RHS vectors
9238   SDValue RHS = Op.getOperand(1);
9239   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9240   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9241
9242   // Issue the operation on the smaller types and concatenate the result back
9243   MVT EltVT = VT.getVectorElementType();
9244   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9245   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9246                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9247                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9248 }
9249
9250 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9251                            SelectionDAG &DAG) {
9252   SDValue Cond;
9253   SDValue Op0 = Op.getOperand(0);
9254   SDValue Op1 = Op.getOperand(1);
9255   SDValue CC = Op.getOperand(2);
9256   MVT VT = Op.getValueType().getSimpleVT();
9257   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9258   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9259   DebugLoc dl = Op.getDebugLoc();
9260
9261   if (isFP) {
9262 #ifndef NDEBUG
9263     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9264     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9265 #endif
9266
9267     unsigned SSECC;
9268     bool Swap = false;
9269
9270     // SSE Condition code mapping:
9271     //  0 - EQ
9272     //  1 - LT
9273     //  2 - LE
9274     //  3 - UNORD
9275     //  4 - NEQ
9276     //  5 - NLT
9277     //  6 - NLE
9278     //  7 - ORD
9279     switch (SetCCOpcode) {
9280     default: llvm_unreachable("Unexpected SETCC condition");
9281     case ISD::SETOEQ:
9282     case ISD::SETEQ:  SSECC = 0; break;
9283     case ISD::SETOGT:
9284     case ISD::SETGT: Swap = true; // Fallthrough
9285     case ISD::SETLT:
9286     case ISD::SETOLT: SSECC = 1; break;
9287     case ISD::SETOGE:
9288     case ISD::SETGE: Swap = true; // Fallthrough
9289     case ISD::SETLE:
9290     case ISD::SETOLE: SSECC = 2; break;
9291     case ISD::SETUO:  SSECC = 3; break;
9292     case ISD::SETUNE:
9293     case ISD::SETNE:  SSECC = 4; break;
9294     case ISD::SETULE: Swap = true; // Fallthrough
9295     case ISD::SETUGE: SSECC = 5; break;
9296     case ISD::SETULT: Swap = true; // Fallthrough
9297     case ISD::SETUGT: SSECC = 6; break;
9298     case ISD::SETO:   SSECC = 7; break;
9299     case ISD::SETUEQ:
9300     case ISD::SETONE: SSECC = 8; break;
9301     }
9302     if (Swap)
9303       std::swap(Op0, Op1);
9304
9305     // In the two special cases we can't handle, emit two comparisons.
9306     if (SSECC == 8) {
9307       unsigned CC0, CC1;
9308       unsigned CombineOpc;
9309       if (SetCCOpcode == ISD::SETUEQ) {
9310         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9311       } else {
9312         assert(SetCCOpcode == ISD::SETONE);
9313         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9314       }
9315
9316       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9317                                  DAG.getConstant(CC0, MVT::i8));
9318       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9319                                  DAG.getConstant(CC1, MVT::i8));
9320       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9321     }
9322     // Handle all other FP comparisons here.
9323     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9324                        DAG.getConstant(SSECC, MVT::i8));
9325   }
9326
9327   // Break 256-bit integer vector compare into smaller ones.
9328   if (VT.is256BitVector() && !Subtarget->hasInt256())
9329     return Lower256IntVSETCC(Op, DAG);
9330
9331   // We are handling one of the integer comparisons here.  Since SSE only has
9332   // GT and EQ comparisons for integer, swapping operands and multiple
9333   // operations may be required for some comparisons.
9334   unsigned Opc;
9335   bool Swap = false, Invert = false, FlipSigns = false;
9336
9337   switch (SetCCOpcode) {
9338   default: llvm_unreachable("Unexpected SETCC condition");
9339   case ISD::SETNE:  Invert = true;
9340   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9341   case ISD::SETLT:  Swap = true;
9342   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9343   case ISD::SETGE:  Swap = true;
9344   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9345   case ISD::SETULT: Swap = true;
9346   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9347   case ISD::SETUGE: Swap = true;
9348   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9349   }
9350   if (Swap)
9351     std::swap(Op0, Op1);
9352
9353   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
9354   // bits of the inputs before performing those operations.
9355   if (FlipSigns) {
9356     EVT EltVT = VT.getVectorElementType();
9357     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
9358                                       EltVT);
9359     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
9360     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
9361                                     SignBits.size());
9362     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
9363     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
9364   }
9365
9366   // Check that the operation in question is available (most are plain SSE2,
9367   // but PCMPGTQ and PCMPEQQ have different requirements).
9368   if (VT == MVT::v2i64) {
9369     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9370       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9371
9372       // First cast everything to the right type,
9373       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9374       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9375
9376       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9377       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9378       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9379
9380       // Create masks for only the low parts/high parts of the 64 bit integers.
9381       const int MaskHi[] = { 1, 1, 3, 3 };
9382       const int MaskLo[] = { 0, 0, 2, 2 };
9383       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9384       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9385       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9386
9387       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9388       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9389
9390       if (Invert)
9391         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9392
9393       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9394     }
9395
9396     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9397       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9398       // pcmpeqd + pshufd + pand.
9399       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9400
9401       // First cast everything to the right type,
9402       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9403       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9404
9405       // Do the compare.
9406       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9407
9408       // Make sure the lower and upper halves are both all-ones.
9409       const int Mask[] = { 1, 0, 3, 2 };
9410       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9411       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9412
9413       if (Invert)
9414         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9415
9416       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9417     }
9418   }
9419
9420   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9421
9422   // If the logical-not of the result is required, perform that now.
9423   if (Invert)
9424     Result = DAG.getNOT(dl, Result, VT);
9425
9426   return Result;
9427 }
9428
9429 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9430
9431   MVT VT = Op.getValueType().getSimpleVT();
9432
9433   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9434
9435   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9436   SDValue Op0 = Op.getOperand(0);
9437   SDValue Op1 = Op.getOperand(1);
9438   DebugLoc dl = Op.getDebugLoc();
9439   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9440
9441   // Optimize to BT if possible.
9442   // Lower (X & (1 << N)) == 0 to BT(X, N).
9443   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9444   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9445   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9446       Op1.getOpcode() == ISD::Constant &&
9447       cast<ConstantSDNode>(Op1)->isNullValue() &&
9448       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9449     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9450     if (NewSetCC.getNode())
9451       return NewSetCC;
9452   }
9453
9454   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9455   // these.
9456   if (Op1.getOpcode() == ISD::Constant &&
9457       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9458        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9459       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9460
9461     // If the input is a setcc, then reuse the input setcc or use a new one with
9462     // the inverted condition.
9463     if (Op0.getOpcode() == X86ISD::SETCC) {
9464       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9465       bool Invert = (CC == ISD::SETNE) ^
9466         cast<ConstantSDNode>(Op1)->isNullValue();
9467       if (!Invert) return Op0;
9468
9469       CCode = X86::GetOppositeBranchCondition(CCode);
9470       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9471                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9472     }
9473   }
9474
9475   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9476   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9477   if (X86CC == X86::COND_INVALID)
9478     return SDValue();
9479
9480   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9481   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9482   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9483                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9484 }
9485
9486 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9487 static bool isX86LogicalCmp(SDValue Op) {
9488   unsigned Opc = Op.getNode()->getOpcode();
9489   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9490       Opc == X86ISD::SAHF)
9491     return true;
9492   if (Op.getResNo() == 1 &&
9493       (Opc == X86ISD::ADD ||
9494        Opc == X86ISD::SUB ||
9495        Opc == X86ISD::ADC ||
9496        Opc == X86ISD::SBB ||
9497        Opc == X86ISD::SMUL ||
9498        Opc == X86ISD::UMUL ||
9499        Opc == X86ISD::INC ||
9500        Opc == X86ISD::DEC ||
9501        Opc == X86ISD::OR ||
9502        Opc == X86ISD::XOR ||
9503        Opc == X86ISD::AND))
9504     return true;
9505
9506   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9507     return true;
9508
9509   return false;
9510 }
9511
9512 static bool isZero(SDValue V) {
9513   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9514   return C && C->isNullValue();
9515 }
9516
9517 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9518   if (V.getOpcode() != ISD::TRUNCATE)
9519     return false;
9520
9521   SDValue VOp0 = V.getOperand(0);
9522   unsigned InBits = VOp0.getValueSizeInBits();
9523   unsigned Bits = V.getValueSizeInBits();
9524   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9525 }
9526
9527 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9528   bool addTest = true;
9529   SDValue Cond  = Op.getOperand(0);
9530   SDValue Op1 = Op.getOperand(1);
9531   SDValue Op2 = Op.getOperand(2);
9532   DebugLoc DL = Op.getDebugLoc();
9533   SDValue CC;
9534
9535   if (Cond.getOpcode() == ISD::SETCC) {
9536     SDValue NewCond = LowerSETCC(Cond, DAG);
9537     if (NewCond.getNode())
9538       Cond = NewCond;
9539   }
9540
9541   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9542   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9543   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9544   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9545   if (Cond.getOpcode() == X86ISD::SETCC &&
9546       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9547       isZero(Cond.getOperand(1).getOperand(1))) {
9548     SDValue Cmp = Cond.getOperand(1);
9549
9550     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9551
9552     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9553         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9554       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9555
9556       SDValue CmpOp0 = Cmp.getOperand(0);
9557       // Apply further optimizations for special cases
9558       // (select (x != 0), -1, 0) -> neg & sbb
9559       // (select (x == 0), 0, -1) -> neg & sbb
9560       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9561         if (YC->isNullValue() &&
9562             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9563           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9564           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9565                                     DAG.getConstant(0, CmpOp0.getValueType()),
9566                                     CmpOp0);
9567           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9568                                     DAG.getConstant(X86::COND_B, MVT::i8),
9569                                     SDValue(Neg.getNode(), 1));
9570           return Res;
9571         }
9572
9573       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9574                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9575       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9576
9577       SDValue Res =   // Res = 0 or -1.
9578         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9579                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9580
9581       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9582         Res = DAG.getNOT(DL, Res, Res.getValueType());
9583
9584       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9585       if (N2C == 0 || !N2C->isNullValue())
9586         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9587       return Res;
9588     }
9589   }
9590
9591   // Look past (and (setcc_carry (cmp ...)), 1).
9592   if (Cond.getOpcode() == ISD::AND &&
9593       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9594     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9595     if (C && C->getAPIntValue() == 1)
9596       Cond = Cond.getOperand(0);
9597   }
9598
9599   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9600   // setting operand in place of the X86ISD::SETCC.
9601   unsigned CondOpcode = Cond.getOpcode();
9602   if (CondOpcode == X86ISD::SETCC ||
9603       CondOpcode == X86ISD::SETCC_CARRY) {
9604     CC = Cond.getOperand(0);
9605
9606     SDValue Cmp = Cond.getOperand(1);
9607     unsigned Opc = Cmp.getOpcode();
9608     MVT VT = Op.getValueType().getSimpleVT();
9609
9610     bool IllegalFPCMov = false;
9611     if (VT.isFloatingPoint() && !VT.isVector() &&
9612         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9613       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9614
9615     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9616         Opc == X86ISD::BT) { // FIXME
9617       Cond = Cmp;
9618       addTest = false;
9619     }
9620   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9621              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9622              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9623               Cond.getOperand(0).getValueType() != MVT::i8)) {
9624     SDValue LHS = Cond.getOperand(0);
9625     SDValue RHS = Cond.getOperand(1);
9626     unsigned X86Opcode;
9627     unsigned X86Cond;
9628     SDVTList VTs;
9629     switch (CondOpcode) {
9630     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9631     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9632     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9633     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9634     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9635     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9636     default: llvm_unreachable("unexpected overflowing operator");
9637     }
9638     if (CondOpcode == ISD::UMULO)
9639       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9640                           MVT::i32);
9641     else
9642       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9643
9644     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9645
9646     if (CondOpcode == ISD::UMULO)
9647       Cond = X86Op.getValue(2);
9648     else
9649       Cond = X86Op.getValue(1);
9650
9651     CC = DAG.getConstant(X86Cond, MVT::i8);
9652     addTest = false;
9653   }
9654
9655   if (addTest) {
9656     // Look pass the truncate if the high bits are known zero.
9657     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9658         Cond = Cond.getOperand(0);
9659
9660     // We know the result of AND is compared against zero. Try to match
9661     // it to BT.
9662     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9663       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9664       if (NewSetCC.getNode()) {
9665         CC = NewSetCC.getOperand(0);
9666         Cond = NewSetCC.getOperand(1);
9667         addTest = false;
9668       }
9669     }
9670   }
9671
9672   if (addTest) {
9673     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9674     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9675   }
9676
9677   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9678   // a <  b ?  0 : -1 -> RES = setcc_carry
9679   // a >= b ? -1 :  0 -> RES = setcc_carry
9680   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9681   if (Cond.getOpcode() == X86ISD::SUB) {
9682     Cond = ConvertCmpIfNecessary(Cond, DAG);
9683     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9684
9685     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9686         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9687       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9688                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9689       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9690         return DAG.getNOT(DL, Res, Res.getValueType());
9691       return Res;
9692     }
9693   }
9694
9695   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9696   // widen the cmov and push the truncate through. This avoids introducing a new
9697   // branch during isel and doesn't add any extensions.
9698   if (Op.getValueType() == MVT::i8 &&
9699       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9700     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9701     if (T1.getValueType() == T2.getValueType() &&
9702         // Blacklist CopyFromReg to avoid partial register stalls.
9703         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9704       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9705       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9706       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9707     }
9708   }
9709
9710   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9711   // condition is true.
9712   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9713   SDValue Ops[] = { Op2, Op1, CC, Cond };
9714   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9715 }
9716
9717 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9718                                             SelectionDAG &DAG) const {
9719   MVT VT = Op->getValueType(0).getSimpleVT();
9720   SDValue In = Op->getOperand(0);
9721   MVT InVT = In.getValueType().getSimpleVT();
9722   DebugLoc dl = Op->getDebugLoc();
9723
9724   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9725       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9726     return SDValue();
9727
9728   if (Subtarget->hasInt256())
9729     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9730
9731   // Optimize vectors in AVX mode
9732   // Sign extend  v8i16 to v8i32 and
9733   //              v4i32 to v4i64
9734   //
9735   // Divide input vector into two parts
9736   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9737   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9738   // concat the vectors to original VT
9739
9740   unsigned NumElems = InVT.getVectorNumElements();
9741   SDValue Undef = DAG.getUNDEF(InVT);
9742
9743   SmallVector<int,8> ShufMask1(NumElems, -1);
9744   for (unsigned i = 0; i != NumElems/2; ++i)
9745     ShufMask1[i] = i;
9746
9747   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9748
9749   SmallVector<int,8> ShufMask2(NumElems, -1);
9750   for (unsigned i = 0; i != NumElems/2; ++i)
9751     ShufMask2[i] = i + NumElems/2;
9752
9753   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9754
9755   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9756                                 VT.getVectorNumElements()/2);
9757
9758   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9759   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9760
9761   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9762 }
9763
9764 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9765 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9766 // from the AND / OR.
9767 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9768   Opc = Op.getOpcode();
9769   if (Opc != ISD::OR && Opc != ISD::AND)
9770     return false;
9771   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9772           Op.getOperand(0).hasOneUse() &&
9773           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9774           Op.getOperand(1).hasOneUse());
9775 }
9776
9777 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9778 // 1 and that the SETCC node has a single use.
9779 static bool isXor1OfSetCC(SDValue Op) {
9780   if (Op.getOpcode() != ISD::XOR)
9781     return false;
9782   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9783   if (N1C && N1C->getAPIntValue() == 1) {
9784     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9785       Op.getOperand(0).hasOneUse();
9786   }
9787   return false;
9788 }
9789
9790 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9791   bool addTest = true;
9792   SDValue Chain = Op.getOperand(0);
9793   SDValue Cond  = Op.getOperand(1);
9794   SDValue Dest  = Op.getOperand(2);
9795   DebugLoc dl = Op.getDebugLoc();
9796   SDValue CC;
9797   bool Inverted = false;
9798
9799   if (Cond.getOpcode() == ISD::SETCC) {
9800     // Check for setcc([su]{add,sub,mul}o == 0).
9801     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9802         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9803         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9804         Cond.getOperand(0).getResNo() == 1 &&
9805         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9806          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9807          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9808          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9809          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9810          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9811       Inverted = true;
9812       Cond = Cond.getOperand(0);
9813     } else {
9814       SDValue NewCond = LowerSETCC(Cond, DAG);
9815       if (NewCond.getNode())
9816         Cond = NewCond;
9817     }
9818   }
9819 #if 0
9820   // FIXME: LowerXALUO doesn't handle these!!
9821   else if (Cond.getOpcode() == X86ISD::ADD  ||
9822            Cond.getOpcode() == X86ISD::SUB  ||
9823            Cond.getOpcode() == X86ISD::SMUL ||
9824            Cond.getOpcode() == X86ISD::UMUL)
9825     Cond = LowerXALUO(Cond, DAG);
9826 #endif
9827
9828   // Look pass (and (setcc_carry (cmp ...)), 1).
9829   if (Cond.getOpcode() == ISD::AND &&
9830       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9831     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9832     if (C && C->getAPIntValue() == 1)
9833       Cond = Cond.getOperand(0);
9834   }
9835
9836   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9837   // setting operand in place of the X86ISD::SETCC.
9838   unsigned CondOpcode = Cond.getOpcode();
9839   if (CondOpcode == X86ISD::SETCC ||
9840       CondOpcode == X86ISD::SETCC_CARRY) {
9841     CC = Cond.getOperand(0);
9842
9843     SDValue Cmp = Cond.getOperand(1);
9844     unsigned Opc = Cmp.getOpcode();
9845     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9846     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9847       Cond = Cmp;
9848       addTest = false;
9849     } else {
9850       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9851       default: break;
9852       case X86::COND_O:
9853       case X86::COND_B:
9854         // These can only come from an arithmetic instruction with overflow,
9855         // e.g. SADDO, UADDO.
9856         Cond = Cond.getNode()->getOperand(1);
9857         addTest = false;
9858         break;
9859       }
9860     }
9861   }
9862   CondOpcode = Cond.getOpcode();
9863   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9864       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9865       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9866        Cond.getOperand(0).getValueType() != MVT::i8)) {
9867     SDValue LHS = Cond.getOperand(0);
9868     SDValue RHS = Cond.getOperand(1);
9869     unsigned X86Opcode;
9870     unsigned X86Cond;
9871     SDVTList VTs;
9872     switch (CondOpcode) {
9873     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9874     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9875     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9876     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9877     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9878     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9879     default: llvm_unreachable("unexpected overflowing operator");
9880     }
9881     if (Inverted)
9882       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9883     if (CondOpcode == ISD::UMULO)
9884       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9885                           MVT::i32);
9886     else
9887       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9888
9889     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9890
9891     if (CondOpcode == ISD::UMULO)
9892       Cond = X86Op.getValue(2);
9893     else
9894       Cond = X86Op.getValue(1);
9895
9896     CC = DAG.getConstant(X86Cond, MVT::i8);
9897     addTest = false;
9898   } else {
9899     unsigned CondOpc;
9900     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9901       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9902       if (CondOpc == ISD::OR) {
9903         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9904         // two branches instead of an explicit OR instruction with a
9905         // separate test.
9906         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9907             isX86LogicalCmp(Cmp)) {
9908           CC = Cond.getOperand(0).getOperand(0);
9909           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9910                               Chain, Dest, CC, Cmp);
9911           CC = Cond.getOperand(1).getOperand(0);
9912           Cond = Cmp;
9913           addTest = false;
9914         }
9915       } else { // ISD::AND
9916         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9917         // two branches instead of an explicit AND instruction with a
9918         // separate test. However, we only do this if this block doesn't
9919         // have a fall-through edge, because this requires an explicit
9920         // jmp when the condition is false.
9921         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9922             isX86LogicalCmp(Cmp) &&
9923             Op.getNode()->hasOneUse()) {
9924           X86::CondCode CCode =
9925             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9926           CCode = X86::GetOppositeBranchCondition(CCode);
9927           CC = DAG.getConstant(CCode, MVT::i8);
9928           SDNode *User = *Op.getNode()->use_begin();
9929           // Look for an unconditional branch following this conditional branch.
9930           // We need this because we need to reverse the successors in order
9931           // to implement FCMP_OEQ.
9932           if (User->getOpcode() == ISD::BR) {
9933             SDValue FalseBB = User->getOperand(1);
9934             SDNode *NewBR =
9935               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9936             assert(NewBR == User);
9937             (void)NewBR;
9938             Dest = FalseBB;
9939
9940             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9941                                 Chain, Dest, CC, Cmp);
9942             X86::CondCode CCode =
9943               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9944             CCode = X86::GetOppositeBranchCondition(CCode);
9945             CC = DAG.getConstant(CCode, MVT::i8);
9946             Cond = Cmp;
9947             addTest = false;
9948           }
9949         }
9950       }
9951     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9952       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9953       // It should be transformed during dag combiner except when the condition
9954       // is set by a arithmetics with overflow node.
9955       X86::CondCode CCode =
9956         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9957       CCode = X86::GetOppositeBranchCondition(CCode);
9958       CC = DAG.getConstant(CCode, MVT::i8);
9959       Cond = Cond.getOperand(0).getOperand(1);
9960       addTest = false;
9961     } else if (Cond.getOpcode() == ISD::SETCC &&
9962                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9963       // For FCMP_OEQ, we can emit
9964       // two branches instead of an explicit AND instruction with a
9965       // separate test. However, we only do this if this block doesn't
9966       // have a fall-through edge, because this requires an explicit
9967       // jmp when the condition is false.
9968       if (Op.getNode()->hasOneUse()) {
9969         SDNode *User = *Op.getNode()->use_begin();
9970         // Look for an unconditional branch following this conditional branch.
9971         // We need this because we need to reverse the successors in order
9972         // to implement FCMP_OEQ.
9973         if (User->getOpcode() == ISD::BR) {
9974           SDValue FalseBB = User->getOperand(1);
9975           SDNode *NewBR =
9976             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9977           assert(NewBR == User);
9978           (void)NewBR;
9979           Dest = FalseBB;
9980
9981           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9982                                     Cond.getOperand(0), Cond.getOperand(1));
9983           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9984           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9985           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9986                               Chain, Dest, CC, Cmp);
9987           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9988           Cond = Cmp;
9989           addTest = false;
9990         }
9991       }
9992     } else if (Cond.getOpcode() == ISD::SETCC &&
9993                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9994       // For FCMP_UNE, we can emit
9995       // two branches instead of an explicit AND instruction with a
9996       // separate test. However, we only do this if this block doesn't
9997       // have a fall-through edge, because this requires an explicit
9998       // jmp when the condition is false.
9999       if (Op.getNode()->hasOneUse()) {
10000         SDNode *User = *Op.getNode()->use_begin();
10001         // Look for an unconditional branch following this conditional branch.
10002         // We need this because we need to reverse the successors in order
10003         // to implement FCMP_UNE.
10004         if (User->getOpcode() == ISD::BR) {
10005           SDValue FalseBB = User->getOperand(1);
10006           SDNode *NewBR =
10007             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10008           assert(NewBR == User);
10009           (void)NewBR;
10010
10011           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10012                                     Cond.getOperand(0), Cond.getOperand(1));
10013           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10014           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10015           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10016                               Chain, Dest, CC, Cmp);
10017           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10018           Cond = Cmp;
10019           addTest = false;
10020           Dest = FalseBB;
10021         }
10022       }
10023     }
10024   }
10025
10026   if (addTest) {
10027     // Look pass the truncate if the high bits are known zero.
10028     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10029         Cond = Cond.getOperand(0);
10030
10031     // We know the result of AND is compared against zero. Try to match
10032     // it to BT.
10033     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10034       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10035       if (NewSetCC.getNode()) {
10036         CC = NewSetCC.getOperand(0);
10037         Cond = NewSetCC.getOperand(1);
10038         addTest = false;
10039       }
10040     }
10041   }
10042
10043   if (addTest) {
10044     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10045     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10046   }
10047   Cond = ConvertCmpIfNecessary(Cond, DAG);
10048   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10049                      Chain, Dest, CC, Cond);
10050 }
10051
10052 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10053 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10054 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10055 // that the guard pages used by the OS virtual memory manager are allocated in
10056 // correct sequence.
10057 SDValue
10058 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10059                                            SelectionDAG &DAG) const {
10060   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10061           getTargetMachine().Options.EnableSegmentedStacks) &&
10062          "This should be used only on Windows targets or when segmented stacks "
10063          "are being used");
10064   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10065   DebugLoc dl = Op.getDebugLoc();
10066
10067   // Get the inputs.
10068   SDValue Chain = Op.getOperand(0);
10069   SDValue Size  = Op.getOperand(1);
10070   // FIXME: Ensure alignment here
10071
10072   bool Is64Bit = Subtarget->is64Bit();
10073   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10074
10075   if (getTargetMachine().Options.EnableSegmentedStacks) {
10076     MachineFunction &MF = DAG.getMachineFunction();
10077     MachineRegisterInfo &MRI = MF.getRegInfo();
10078
10079     if (Is64Bit) {
10080       // The 64 bit implementation of segmented stacks needs to clobber both r10
10081       // r11. This makes it impossible to use it along with nested parameters.
10082       const Function *F = MF.getFunction();
10083
10084       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10085            I != E; ++I)
10086         if (I->hasNestAttr())
10087           report_fatal_error("Cannot use segmented stacks with functions that "
10088                              "have nested arguments.");
10089     }
10090
10091     const TargetRegisterClass *AddrRegClass =
10092       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10093     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10094     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10095     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10096                                 DAG.getRegister(Vreg, SPTy));
10097     SDValue Ops1[2] = { Value, Chain };
10098     return DAG.getMergeValues(Ops1, 2, dl);
10099   } else {
10100     SDValue Flag;
10101     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10102
10103     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10104     Flag = Chain.getValue(1);
10105     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10106
10107     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10108     Flag = Chain.getValue(1);
10109
10110     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10111                                SPTy).getValue(1);
10112
10113     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10114     return DAG.getMergeValues(Ops1, 2, dl);
10115   }
10116 }
10117
10118 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10119   MachineFunction &MF = DAG.getMachineFunction();
10120   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10121
10122   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10123   DebugLoc DL = Op.getDebugLoc();
10124
10125   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10126     // vastart just stores the address of the VarArgsFrameIndex slot into the
10127     // memory location argument.
10128     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10129                                    getPointerTy());
10130     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10131                         MachinePointerInfo(SV), false, false, 0);
10132   }
10133
10134   // __va_list_tag:
10135   //   gp_offset         (0 - 6 * 8)
10136   //   fp_offset         (48 - 48 + 8 * 16)
10137   //   overflow_arg_area (point to parameters coming in memory).
10138   //   reg_save_area
10139   SmallVector<SDValue, 8> MemOps;
10140   SDValue FIN = Op.getOperand(1);
10141   // Store gp_offset
10142   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10143                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10144                                                MVT::i32),
10145                                FIN, MachinePointerInfo(SV), false, false, 0);
10146   MemOps.push_back(Store);
10147
10148   // Store fp_offset
10149   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10150                     FIN, DAG.getIntPtrConstant(4));
10151   Store = DAG.getStore(Op.getOperand(0), DL,
10152                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10153                                        MVT::i32),
10154                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10155   MemOps.push_back(Store);
10156
10157   // Store ptr to overflow_arg_area
10158   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10159                     FIN, DAG.getIntPtrConstant(4));
10160   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10161                                     getPointerTy());
10162   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10163                        MachinePointerInfo(SV, 8),
10164                        false, false, 0);
10165   MemOps.push_back(Store);
10166
10167   // Store ptr to reg_save_area.
10168   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10169                     FIN, DAG.getIntPtrConstant(8));
10170   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10171                                     getPointerTy());
10172   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10173                        MachinePointerInfo(SV, 16), false, false, 0);
10174   MemOps.push_back(Store);
10175   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10176                      &MemOps[0], MemOps.size());
10177 }
10178
10179 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10180   assert(Subtarget->is64Bit() &&
10181          "LowerVAARG only handles 64-bit va_arg!");
10182   assert((Subtarget->isTargetLinux() ||
10183           Subtarget->isTargetDarwin()) &&
10184           "Unhandled target in LowerVAARG");
10185   assert(Op.getNode()->getNumOperands() == 4);
10186   SDValue Chain = Op.getOperand(0);
10187   SDValue SrcPtr = Op.getOperand(1);
10188   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10189   unsigned Align = Op.getConstantOperandVal(3);
10190   DebugLoc dl = Op.getDebugLoc();
10191
10192   EVT ArgVT = Op.getNode()->getValueType(0);
10193   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10194   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10195   uint8_t ArgMode;
10196
10197   // Decide which area this value should be read from.
10198   // TODO: Implement the AMD64 ABI in its entirety. This simple
10199   // selection mechanism works only for the basic types.
10200   if (ArgVT == MVT::f80) {
10201     llvm_unreachable("va_arg for f80 not yet implemented");
10202   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10203     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10204   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10205     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10206   } else {
10207     llvm_unreachable("Unhandled argument type in LowerVAARG");
10208   }
10209
10210   if (ArgMode == 2) {
10211     // Sanity Check: Make sure using fp_offset makes sense.
10212     assert(!getTargetMachine().Options.UseSoftFloat &&
10213            !(DAG.getMachineFunction()
10214                 .getFunction()->getAttributes()
10215                 .hasAttribute(AttributeSet::FunctionIndex,
10216                               Attribute::NoImplicitFloat)) &&
10217            Subtarget->hasSSE1());
10218   }
10219
10220   // Insert VAARG_64 node into the DAG
10221   // VAARG_64 returns two values: Variable Argument Address, Chain
10222   SmallVector<SDValue, 11> InstOps;
10223   InstOps.push_back(Chain);
10224   InstOps.push_back(SrcPtr);
10225   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10226   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10227   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10228   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10229   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10230                                           VTs, &InstOps[0], InstOps.size(),
10231                                           MVT::i64,
10232                                           MachinePointerInfo(SV),
10233                                           /*Align=*/0,
10234                                           /*Volatile=*/false,
10235                                           /*ReadMem=*/true,
10236                                           /*WriteMem=*/true);
10237   Chain = VAARG.getValue(1);
10238
10239   // Load the next argument and return it
10240   return DAG.getLoad(ArgVT, dl,
10241                      Chain,
10242                      VAARG,
10243                      MachinePointerInfo(),
10244                      false, false, false, 0);
10245 }
10246
10247 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10248                            SelectionDAG &DAG) {
10249   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10250   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10251   SDValue Chain = Op.getOperand(0);
10252   SDValue DstPtr = Op.getOperand(1);
10253   SDValue SrcPtr = Op.getOperand(2);
10254   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10255   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10256   DebugLoc DL = Op.getDebugLoc();
10257
10258   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10259                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10260                        false,
10261                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10262 }
10263
10264 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10265 // may or may not be a constant. Takes immediate version of shift as input.
10266 static SDValue getTargetVShiftNode(unsigned Opc, DebugLoc dl, EVT VT,
10267                                    SDValue SrcOp, SDValue ShAmt,
10268                                    SelectionDAG &DAG) {
10269   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10270
10271   if (isa<ConstantSDNode>(ShAmt)) {
10272     // Constant may be a TargetConstant. Use a regular constant.
10273     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10274     switch (Opc) {
10275       default: llvm_unreachable("Unknown target vector shift node");
10276       case X86ISD::VSHLI:
10277       case X86ISD::VSRLI:
10278       case X86ISD::VSRAI:
10279         return DAG.getNode(Opc, dl, VT, SrcOp,
10280                            DAG.getConstant(ShiftAmt, MVT::i32));
10281     }
10282   }
10283
10284   // Change opcode to non-immediate version
10285   switch (Opc) {
10286     default: llvm_unreachable("Unknown target vector shift node");
10287     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10288     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10289     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10290   }
10291
10292   // Need to build a vector containing shift amount
10293   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10294   SDValue ShOps[4];
10295   ShOps[0] = ShAmt;
10296   ShOps[1] = DAG.getConstant(0, MVT::i32);
10297   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10298   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10299
10300   // The return type has to be a 128-bit type with the same element
10301   // type as the input type.
10302   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10303   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10304
10305   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10306   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10307 }
10308
10309 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10310   DebugLoc dl = Op.getDebugLoc();
10311   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10312   switch (IntNo) {
10313   default: return SDValue();    // Don't custom lower most intrinsics.
10314   // Comparison intrinsics.
10315   case Intrinsic::x86_sse_comieq_ss:
10316   case Intrinsic::x86_sse_comilt_ss:
10317   case Intrinsic::x86_sse_comile_ss:
10318   case Intrinsic::x86_sse_comigt_ss:
10319   case Intrinsic::x86_sse_comige_ss:
10320   case Intrinsic::x86_sse_comineq_ss:
10321   case Intrinsic::x86_sse_ucomieq_ss:
10322   case Intrinsic::x86_sse_ucomilt_ss:
10323   case Intrinsic::x86_sse_ucomile_ss:
10324   case Intrinsic::x86_sse_ucomigt_ss:
10325   case Intrinsic::x86_sse_ucomige_ss:
10326   case Intrinsic::x86_sse_ucomineq_ss:
10327   case Intrinsic::x86_sse2_comieq_sd:
10328   case Intrinsic::x86_sse2_comilt_sd:
10329   case Intrinsic::x86_sse2_comile_sd:
10330   case Intrinsic::x86_sse2_comigt_sd:
10331   case Intrinsic::x86_sse2_comige_sd:
10332   case Intrinsic::x86_sse2_comineq_sd:
10333   case Intrinsic::x86_sse2_ucomieq_sd:
10334   case Intrinsic::x86_sse2_ucomilt_sd:
10335   case Intrinsic::x86_sse2_ucomile_sd:
10336   case Intrinsic::x86_sse2_ucomigt_sd:
10337   case Intrinsic::x86_sse2_ucomige_sd:
10338   case Intrinsic::x86_sse2_ucomineq_sd: {
10339     unsigned Opc;
10340     ISD::CondCode CC;
10341     switch (IntNo) {
10342     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10343     case Intrinsic::x86_sse_comieq_ss:
10344     case Intrinsic::x86_sse2_comieq_sd:
10345       Opc = X86ISD::COMI;
10346       CC = ISD::SETEQ;
10347       break;
10348     case Intrinsic::x86_sse_comilt_ss:
10349     case Intrinsic::x86_sse2_comilt_sd:
10350       Opc = X86ISD::COMI;
10351       CC = ISD::SETLT;
10352       break;
10353     case Intrinsic::x86_sse_comile_ss:
10354     case Intrinsic::x86_sse2_comile_sd:
10355       Opc = X86ISD::COMI;
10356       CC = ISD::SETLE;
10357       break;
10358     case Intrinsic::x86_sse_comigt_ss:
10359     case Intrinsic::x86_sse2_comigt_sd:
10360       Opc = X86ISD::COMI;
10361       CC = ISD::SETGT;
10362       break;
10363     case Intrinsic::x86_sse_comige_ss:
10364     case Intrinsic::x86_sse2_comige_sd:
10365       Opc = X86ISD::COMI;
10366       CC = ISD::SETGE;
10367       break;
10368     case Intrinsic::x86_sse_comineq_ss:
10369     case Intrinsic::x86_sse2_comineq_sd:
10370       Opc = X86ISD::COMI;
10371       CC = ISD::SETNE;
10372       break;
10373     case Intrinsic::x86_sse_ucomieq_ss:
10374     case Intrinsic::x86_sse2_ucomieq_sd:
10375       Opc = X86ISD::UCOMI;
10376       CC = ISD::SETEQ;
10377       break;
10378     case Intrinsic::x86_sse_ucomilt_ss:
10379     case Intrinsic::x86_sse2_ucomilt_sd:
10380       Opc = X86ISD::UCOMI;
10381       CC = ISD::SETLT;
10382       break;
10383     case Intrinsic::x86_sse_ucomile_ss:
10384     case Intrinsic::x86_sse2_ucomile_sd:
10385       Opc = X86ISD::UCOMI;
10386       CC = ISD::SETLE;
10387       break;
10388     case Intrinsic::x86_sse_ucomigt_ss:
10389     case Intrinsic::x86_sse2_ucomigt_sd:
10390       Opc = X86ISD::UCOMI;
10391       CC = ISD::SETGT;
10392       break;
10393     case Intrinsic::x86_sse_ucomige_ss:
10394     case Intrinsic::x86_sse2_ucomige_sd:
10395       Opc = X86ISD::UCOMI;
10396       CC = ISD::SETGE;
10397       break;
10398     case Intrinsic::x86_sse_ucomineq_ss:
10399     case Intrinsic::x86_sse2_ucomineq_sd:
10400       Opc = X86ISD::UCOMI;
10401       CC = ISD::SETNE;
10402       break;
10403     }
10404
10405     SDValue LHS = Op.getOperand(1);
10406     SDValue RHS = Op.getOperand(2);
10407     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10408     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10409     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10410     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10411                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10412     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10413   }
10414
10415   // Arithmetic intrinsics.
10416   case Intrinsic::x86_sse2_pmulu_dq:
10417   case Intrinsic::x86_avx2_pmulu_dq:
10418     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10419                        Op.getOperand(1), Op.getOperand(2));
10420
10421   // SSE2/AVX2 sub with unsigned saturation intrinsics
10422   case Intrinsic::x86_sse2_psubus_b:
10423   case Intrinsic::x86_sse2_psubus_w:
10424   case Intrinsic::x86_avx2_psubus_b:
10425   case Intrinsic::x86_avx2_psubus_w:
10426     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10427                        Op.getOperand(1), Op.getOperand(2));
10428
10429   // SSE3/AVX horizontal add/sub intrinsics
10430   case Intrinsic::x86_sse3_hadd_ps:
10431   case Intrinsic::x86_sse3_hadd_pd:
10432   case Intrinsic::x86_avx_hadd_ps_256:
10433   case Intrinsic::x86_avx_hadd_pd_256:
10434   case Intrinsic::x86_sse3_hsub_ps:
10435   case Intrinsic::x86_sse3_hsub_pd:
10436   case Intrinsic::x86_avx_hsub_ps_256:
10437   case Intrinsic::x86_avx_hsub_pd_256:
10438   case Intrinsic::x86_ssse3_phadd_w_128:
10439   case Intrinsic::x86_ssse3_phadd_d_128:
10440   case Intrinsic::x86_avx2_phadd_w:
10441   case Intrinsic::x86_avx2_phadd_d:
10442   case Intrinsic::x86_ssse3_phsub_w_128:
10443   case Intrinsic::x86_ssse3_phsub_d_128:
10444   case Intrinsic::x86_avx2_phsub_w:
10445   case Intrinsic::x86_avx2_phsub_d: {
10446     unsigned Opcode;
10447     switch (IntNo) {
10448     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10449     case Intrinsic::x86_sse3_hadd_ps:
10450     case Intrinsic::x86_sse3_hadd_pd:
10451     case Intrinsic::x86_avx_hadd_ps_256:
10452     case Intrinsic::x86_avx_hadd_pd_256:
10453       Opcode = X86ISD::FHADD;
10454       break;
10455     case Intrinsic::x86_sse3_hsub_ps:
10456     case Intrinsic::x86_sse3_hsub_pd:
10457     case Intrinsic::x86_avx_hsub_ps_256:
10458     case Intrinsic::x86_avx_hsub_pd_256:
10459       Opcode = X86ISD::FHSUB;
10460       break;
10461     case Intrinsic::x86_ssse3_phadd_w_128:
10462     case Intrinsic::x86_ssse3_phadd_d_128:
10463     case Intrinsic::x86_avx2_phadd_w:
10464     case Intrinsic::x86_avx2_phadd_d:
10465       Opcode = X86ISD::HADD;
10466       break;
10467     case Intrinsic::x86_ssse3_phsub_w_128:
10468     case Intrinsic::x86_ssse3_phsub_d_128:
10469     case Intrinsic::x86_avx2_phsub_w:
10470     case Intrinsic::x86_avx2_phsub_d:
10471       Opcode = X86ISD::HSUB;
10472       break;
10473     }
10474     return DAG.getNode(Opcode, dl, Op.getValueType(),
10475                        Op.getOperand(1), Op.getOperand(2));
10476   }
10477
10478   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10479   case Intrinsic::x86_sse2_pmaxu_b:
10480   case Intrinsic::x86_sse41_pmaxuw:
10481   case Intrinsic::x86_sse41_pmaxud:
10482   case Intrinsic::x86_avx2_pmaxu_b:
10483   case Intrinsic::x86_avx2_pmaxu_w:
10484   case Intrinsic::x86_avx2_pmaxu_d:
10485   case Intrinsic::x86_sse2_pminu_b:
10486   case Intrinsic::x86_sse41_pminuw:
10487   case Intrinsic::x86_sse41_pminud:
10488   case Intrinsic::x86_avx2_pminu_b:
10489   case Intrinsic::x86_avx2_pminu_w:
10490   case Intrinsic::x86_avx2_pminu_d:
10491   case Intrinsic::x86_sse41_pmaxsb:
10492   case Intrinsic::x86_sse2_pmaxs_w:
10493   case Intrinsic::x86_sse41_pmaxsd:
10494   case Intrinsic::x86_avx2_pmaxs_b:
10495   case Intrinsic::x86_avx2_pmaxs_w:
10496   case Intrinsic::x86_avx2_pmaxs_d:
10497   case Intrinsic::x86_sse41_pminsb:
10498   case Intrinsic::x86_sse2_pmins_w:
10499   case Intrinsic::x86_sse41_pminsd:
10500   case Intrinsic::x86_avx2_pmins_b:
10501   case Intrinsic::x86_avx2_pmins_w:
10502   case Intrinsic::x86_avx2_pmins_d: {
10503     unsigned Opcode;
10504     switch (IntNo) {
10505     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10506     case Intrinsic::x86_sse2_pmaxu_b:
10507     case Intrinsic::x86_sse41_pmaxuw:
10508     case Intrinsic::x86_sse41_pmaxud:
10509     case Intrinsic::x86_avx2_pmaxu_b:
10510     case Intrinsic::x86_avx2_pmaxu_w:
10511     case Intrinsic::x86_avx2_pmaxu_d:
10512       Opcode = X86ISD::UMAX;
10513       break;
10514     case Intrinsic::x86_sse2_pminu_b:
10515     case Intrinsic::x86_sse41_pminuw:
10516     case Intrinsic::x86_sse41_pminud:
10517     case Intrinsic::x86_avx2_pminu_b:
10518     case Intrinsic::x86_avx2_pminu_w:
10519     case Intrinsic::x86_avx2_pminu_d:
10520       Opcode = X86ISD::UMIN;
10521       break;
10522     case Intrinsic::x86_sse41_pmaxsb:
10523     case Intrinsic::x86_sse2_pmaxs_w:
10524     case Intrinsic::x86_sse41_pmaxsd:
10525     case Intrinsic::x86_avx2_pmaxs_b:
10526     case Intrinsic::x86_avx2_pmaxs_w:
10527     case Intrinsic::x86_avx2_pmaxs_d:
10528       Opcode = X86ISD::SMAX;
10529       break;
10530     case Intrinsic::x86_sse41_pminsb:
10531     case Intrinsic::x86_sse2_pmins_w:
10532     case Intrinsic::x86_sse41_pminsd:
10533     case Intrinsic::x86_avx2_pmins_b:
10534     case Intrinsic::x86_avx2_pmins_w:
10535     case Intrinsic::x86_avx2_pmins_d:
10536       Opcode = X86ISD::SMIN;
10537       break;
10538     }
10539     return DAG.getNode(Opcode, dl, Op.getValueType(),
10540                        Op.getOperand(1), Op.getOperand(2));
10541   }
10542
10543   // SSE/SSE2/AVX floating point max/min intrinsics.
10544   case Intrinsic::x86_sse_max_ps:
10545   case Intrinsic::x86_sse2_max_pd:
10546   case Intrinsic::x86_avx_max_ps_256:
10547   case Intrinsic::x86_avx_max_pd_256:
10548   case Intrinsic::x86_sse_min_ps:
10549   case Intrinsic::x86_sse2_min_pd:
10550   case Intrinsic::x86_avx_min_ps_256:
10551   case Intrinsic::x86_avx_min_pd_256: {
10552     unsigned Opcode;
10553     switch (IntNo) {
10554     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10555     case Intrinsic::x86_sse_max_ps:
10556     case Intrinsic::x86_sse2_max_pd:
10557     case Intrinsic::x86_avx_max_ps_256:
10558     case Intrinsic::x86_avx_max_pd_256:
10559       Opcode = X86ISD::FMAX;
10560       break;
10561     case Intrinsic::x86_sse_min_ps:
10562     case Intrinsic::x86_sse2_min_pd:
10563     case Intrinsic::x86_avx_min_ps_256:
10564     case Intrinsic::x86_avx_min_pd_256:
10565       Opcode = X86ISD::FMIN;
10566       break;
10567     }
10568     return DAG.getNode(Opcode, dl, Op.getValueType(),
10569                        Op.getOperand(1), Op.getOperand(2));
10570   }
10571
10572   // AVX2 variable shift intrinsics
10573   case Intrinsic::x86_avx2_psllv_d:
10574   case Intrinsic::x86_avx2_psllv_q:
10575   case Intrinsic::x86_avx2_psllv_d_256:
10576   case Intrinsic::x86_avx2_psllv_q_256:
10577   case Intrinsic::x86_avx2_psrlv_d:
10578   case Intrinsic::x86_avx2_psrlv_q:
10579   case Intrinsic::x86_avx2_psrlv_d_256:
10580   case Intrinsic::x86_avx2_psrlv_q_256:
10581   case Intrinsic::x86_avx2_psrav_d:
10582   case Intrinsic::x86_avx2_psrav_d_256: {
10583     unsigned Opcode;
10584     switch (IntNo) {
10585     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10586     case Intrinsic::x86_avx2_psllv_d:
10587     case Intrinsic::x86_avx2_psllv_q:
10588     case Intrinsic::x86_avx2_psllv_d_256:
10589     case Intrinsic::x86_avx2_psllv_q_256:
10590       Opcode = ISD::SHL;
10591       break;
10592     case Intrinsic::x86_avx2_psrlv_d:
10593     case Intrinsic::x86_avx2_psrlv_q:
10594     case Intrinsic::x86_avx2_psrlv_d_256:
10595     case Intrinsic::x86_avx2_psrlv_q_256:
10596       Opcode = ISD::SRL;
10597       break;
10598     case Intrinsic::x86_avx2_psrav_d:
10599     case Intrinsic::x86_avx2_psrav_d_256:
10600       Opcode = ISD::SRA;
10601       break;
10602     }
10603     return DAG.getNode(Opcode, dl, Op.getValueType(),
10604                        Op.getOperand(1), Op.getOperand(2));
10605   }
10606
10607   case Intrinsic::x86_ssse3_pshuf_b_128:
10608   case Intrinsic::x86_avx2_pshuf_b:
10609     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10610                        Op.getOperand(1), Op.getOperand(2));
10611
10612   case Intrinsic::x86_ssse3_psign_b_128:
10613   case Intrinsic::x86_ssse3_psign_w_128:
10614   case Intrinsic::x86_ssse3_psign_d_128:
10615   case Intrinsic::x86_avx2_psign_b:
10616   case Intrinsic::x86_avx2_psign_w:
10617   case Intrinsic::x86_avx2_psign_d:
10618     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10619                        Op.getOperand(1), Op.getOperand(2));
10620
10621   case Intrinsic::x86_sse41_insertps:
10622     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10623                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10624
10625   case Intrinsic::x86_avx_vperm2f128_ps_256:
10626   case Intrinsic::x86_avx_vperm2f128_pd_256:
10627   case Intrinsic::x86_avx_vperm2f128_si_256:
10628   case Intrinsic::x86_avx2_vperm2i128:
10629     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10630                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10631
10632   case Intrinsic::x86_avx2_permd:
10633   case Intrinsic::x86_avx2_permps:
10634     // Operands intentionally swapped. Mask is last operand to intrinsic,
10635     // but second operand for node/intruction.
10636     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10637                        Op.getOperand(2), Op.getOperand(1));
10638
10639   case Intrinsic::x86_sse_sqrt_ps:
10640   case Intrinsic::x86_sse2_sqrt_pd:
10641   case Intrinsic::x86_avx_sqrt_ps_256:
10642   case Intrinsic::x86_avx_sqrt_pd_256:
10643     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10644
10645   // ptest and testp intrinsics. The intrinsic these come from are designed to
10646   // return an integer value, not just an instruction so lower it to the ptest
10647   // or testp pattern and a setcc for the result.
10648   case Intrinsic::x86_sse41_ptestz:
10649   case Intrinsic::x86_sse41_ptestc:
10650   case Intrinsic::x86_sse41_ptestnzc:
10651   case Intrinsic::x86_avx_ptestz_256:
10652   case Intrinsic::x86_avx_ptestc_256:
10653   case Intrinsic::x86_avx_ptestnzc_256:
10654   case Intrinsic::x86_avx_vtestz_ps:
10655   case Intrinsic::x86_avx_vtestc_ps:
10656   case Intrinsic::x86_avx_vtestnzc_ps:
10657   case Intrinsic::x86_avx_vtestz_pd:
10658   case Intrinsic::x86_avx_vtestc_pd:
10659   case Intrinsic::x86_avx_vtestnzc_pd:
10660   case Intrinsic::x86_avx_vtestz_ps_256:
10661   case Intrinsic::x86_avx_vtestc_ps_256:
10662   case Intrinsic::x86_avx_vtestnzc_ps_256:
10663   case Intrinsic::x86_avx_vtestz_pd_256:
10664   case Intrinsic::x86_avx_vtestc_pd_256:
10665   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10666     bool IsTestPacked = false;
10667     unsigned X86CC;
10668     switch (IntNo) {
10669     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10670     case Intrinsic::x86_avx_vtestz_ps:
10671     case Intrinsic::x86_avx_vtestz_pd:
10672     case Intrinsic::x86_avx_vtestz_ps_256:
10673     case Intrinsic::x86_avx_vtestz_pd_256:
10674       IsTestPacked = true; // Fallthrough
10675     case Intrinsic::x86_sse41_ptestz:
10676     case Intrinsic::x86_avx_ptestz_256:
10677       // ZF = 1
10678       X86CC = X86::COND_E;
10679       break;
10680     case Intrinsic::x86_avx_vtestc_ps:
10681     case Intrinsic::x86_avx_vtestc_pd:
10682     case Intrinsic::x86_avx_vtestc_ps_256:
10683     case Intrinsic::x86_avx_vtestc_pd_256:
10684       IsTestPacked = true; // Fallthrough
10685     case Intrinsic::x86_sse41_ptestc:
10686     case Intrinsic::x86_avx_ptestc_256:
10687       // CF = 1
10688       X86CC = X86::COND_B;
10689       break;
10690     case Intrinsic::x86_avx_vtestnzc_ps:
10691     case Intrinsic::x86_avx_vtestnzc_pd:
10692     case Intrinsic::x86_avx_vtestnzc_ps_256:
10693     case Intrinsic::x86_avx_vtestnzc_pd_256:
10694       IsTestPacked = true; // Fallthrough
10695     case Intrinsic::x86_sse41_ptestnzc:
10696     case Intrinsic::x86_avx_ptestnzc_256:
10697       // ZF and CF = 0
10698       X86CC = X86::COND_A;
10699       break;
10700     }
10701
10702     SDValue LHS = Op.getOperand(1);
10703     SDValue RHS = Op.getOperand(2);
10704     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10705     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10706     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10707     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10708     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10709   }
10710
10711   // SSE/AVX shift intrinsics
10712   case Intrinsic::x86_sse2_psll_w:
10713   case Intrinsic::x86_sse2_psll_d:
10714   case Intrinsic::x86_sse2_psll_q:
10715   case Intrinsic::x86_avx2_psll_w:
10716   case Intrinsic::x86_avx2_psll_d:
10717   case Intrinsic::x86_avx2_psll_q:
10718   case Intrinsic::x86_sse2_psrl_w:
10719   case Intrinsic::x86_sse2_psrl_d:
10720   case Intrinsic::x86_sse2_psrl_q:
10721   case Intrinsic::x86_avx2_psrl_w:
10722   case Intrinsic::x86_avx2_psrl_d:
10723   case Intrinsic::x86_avx2_psrl_q:
10724   case Intrinsic::x86_sse2_psra_w:
10725   case Intrinsic::x86_sse2_psra_d:
10726   case Intrinsic::x86_avx2_psra_w:
10727   case Intrinsic::x86_avx2_psra_d: {
10728     unsigned Opcode;
10729     switch (IntNo) {
10730     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10731     case Intrinsic::x86_sse2_psll_w:
10732     case Intrinsic::x86_sse2_psll_d:
10733     case Intrinsic::x86_sse2_psll_q:
10734     case Intrinsic::x86_avx2_psll_w:
10735     case Intrinsic::x86_avx2_psll_d:
10736     case Intrinsic::x86_avx2_psll_q:
10737       Opcode = X86ISD::VSHL;
10738       break;
10739     case Intrinsic::x86_sse2_psrl_w:
10740     case Intrinsic::x86_sse2_psrl_d:
10741     case Intrinsic::x86_sse2_psrl_q:
10742     case Intrinsic::x86_avx2_psrl_w:
10743     case Intrinsic::x86_avx2_psrl_d:
10744     case Intrinsic::x86_avx2_psrl_q:
10745       Opcode = X86ISD::VSRL;
10746       break;
10747     case Intrinsic::x86_sse2_psra_w:
10748     case Intrinsic::x86_sse2_psra_d:
10749     case Intrinsic::x86_avx2_psra_w:
10750     case Intrinsic::x86_avx2_psra_d:
10751       Opcode = X86ISD::VSRA;
10752       break;
10753     }
10754     return DAG.getNode(Opcode, dl, Op.getValueType(),
10755                        Op.getOperand(1), Op.getOperand(2));
10756   }
10757
10758   // SSE/AVX immediate shift intrinsics
10759   case Intrinsic::x86_sse2_pslli_w:
10760   case Intrinsic::x86_sse2_pslli_d:
10761   case Intrinsic::x86_sse2_pslli_q:
10762   case Intrinsic::x86_avx2_pslli_w:
10763   case Intrinsic::x86_avx2_pslli_d:
10764   case Intrinsic::x86_avx2_pslli_q:
10765   case Intrinsic::x86_sse2_psrli_w:
10766   case Intrinsic::x86_sse2_psrli_d:
10767   case Intrinsic::x86_sse2_psrli_q:
10768   case Intrinsic::x86_avx2_psrli_w:
10769   case Intrinsic::x86_avx2_psrli_d:
10770   case Intrinsic::x86_avx2_psrli_q:
10771   case Intrinsic::x86_sse2_psrai_w:
10772   case Intrinsic::x86_sse2_psrai_d:
10773   case Intrinsic::x86_avx2_psrai_w:
10774   case Intrinsic::x86_avx2_psrai_d: {
10775     unsigned Opcode;
10776     switch (IntNo) {
10777     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10778     case Intrinsic::x86_sse2_pslli_w:
10779     case Intrinsic::x86_sse2_pslli_d:
10780     case Intrinsic::x86_sse2_pslli_q:
10781     case Intrinsic::x86_avx2_pslli_w:
10782     case Intrinsic::x86_avx2_pslli_d:
10783     case Intrinsic::x86_avx2_pslli_q:
10784       Opcode = X86ISD::VSHLI;
10785       break;
10786     case Intrinsic::x86_sse2_psrli_w:
10787     case Intrinsic::x86_sse2_psrli_d:
10788     case Intrinsic::x86_sse2_psrli_q:
10789     case Intrinsic::x86_avx2_psrli_w:
10790     case Intrinsic::x86_avx2_psrli_d:
10791     case Intrinsic::x86_avx2_psrli_q:
10792       Opcode = X86ISD::VSRLI;
10793       break;
10794     case Intrinsic::x86_sse2_psrai_w:
10795     case Intrinsic::x86_sse2_psrai_d:
10796     case Intrinsic::x86_avx2_psrai_w:
10797     case Intrinsic::x86_avx2_psrai_d:
10798       Opcode = X86ISD::VSRAI;
10799       break;
10800     }
10801     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10802                                Op.getOperand(1), Op.getOperand(2), DAG);
10803   }
10804
10805   case Intrinsic::x86_sse42_pcmpistria128:
10806   case Intrinsic::x86_sse42_pcmpestria128:
10807   case Intrinsic::x86_sse42_pcmpistric128:
10808   case Intrinsic::x86_sse42_pcmpestric128:
10809   case Intrinsic::x86_sse42_pcmpistrio128:
10810   case Intrinsic::x86_sse42_pcmpestrio128:
10811   case Intrinsic::x86_sse42_pcmpistris128:
10812   case Intrinsic::x86_sse42_pcmpestris128:
10813   case Intrinsic::x86_sse42_pcmpistriz128:
10814   case Intrinsic::x86_sse42_pcmpestriz128: {
10815     unsigned Opcode;
10816     unsigned X86CC;
10817     switch (IntNo) {
10818     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10819     case Intrinsic::x86_sse42_pcmpistria128:
10820       Opcode = X86ISD::PCMPISTRI;
10821       X86CC = X86::COND_A;
10822       break;
10823     case Intrinsic::x86_sse42_pcmpestria128:
10824       Opcode = X86ISD::PCMPESTRI;
10825       X86CC = X86::COND_A;
10826       break;
10827     case Intrinsic::x86_sse42_pcmpistric128:
10828       Opcode = X86ISD::PCMPISTRI;
10829       X86CC = X86::COND_B;
10830       break;
10831     case Intrinsic::x86_sse42_pcmpestric128:
10832       Opcode = X86ISD::PCMPESTRI;
10833       X86CC = X86::COND_B;
10834       break;
10835     case Intrinsic::x86_sse42_pcmpistrio128:
10836       Opcode = X86ISD::PCMPISTRI;
10837       X86CC = X86::COND_O;
10838       break;
10839     case Intrinsic::x86_sse42_pcmpestrio128:
10840       Opcode = X86ISD::PCMPESTRI;
10841       X86CC = X86::COND_O;
10842       break;
10843     case Intrinsic::x86_sse42_pcmpistris128:
10844       Opcode = X86ISD::PCMPISTRI;
10845       X86CC = X86::COND_S;
10846       break;
10847     case Intrinsic::x86_sse42_pcmpestris128:
10848       Opcode = X86ISD::PCMPESTRI;
10849       X86CC = X86::COND_S;
10850       break;
10851     case Intrinsic::x86_sse42_pcmpistriz128:
10852       Opcode = X86ISD::PCMPISTRI;
10853       X86CC = X86::COND_E;
10854       break;
10855     case Intrinsic::x86_sse42_pcmpestriz128:
10856       Opcode = X86ISD::PCMPESTRI;
10857       X86CC = X86::COND_E;
10858       break;
10859     }
10860     SmallVector<SDValue, 5> NewOps;
10861     NewOps.append(Op->op_begin()+1, Op->op_end());
10862     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10863     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10864     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10865                                 DAG.getConstant(X86CC, MVT::i8),
10866                                 SDValue(PCMP.getNode(), 1));
10867     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10868   }
10869
10870   case Intrinsic::x86_sse42_pcmpistri128:
10871   case Intrinsic::x86_sse42_pcmpestri128: {
10872     unsigned Opcode;
10873     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10874       Opcode = X86ISD::PCMPISTRI;
10875     else
10876       Opcode = X86ISD::PCMPESTRI;
10877
10878     SmallVector<SDValue, 5> NewOps;
10879     NewOps.append(Op->op_begin()+1, Op->op_end());
10880     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10881     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10882   }
10883   case Intrinsic::x86_fma_vfmadd_ps:
10884   case Intrinsic::x86_fma_vfmadd_pd:
10885   case Intrinsic::x86_fma_vfmsub_ps:
10886   case Intrinsic::x86_fma_vfmsub_pd:
10887   case Intrinsic::x86_fma_vfnmadd_ps:
10888   case Intrinsic::x86_fma_vfnmadd_pd:
10889   case Intrinsic::x86_fma_vfnmsub_ps:
10890   case Intrinsic::x86_fma_vfnmsub_pd:
10891   case Intrinsic::x86_fma_vfmaddsub_ps:
10892   case Intrinsic::x86_fma_vfmaddsub_pd:
10893   case Intrinsic::x86_fma_vfmsubadd_ps:
10894   case Intrinsic::x86_fma_vfmsubadd_pd:
10895   case Intrinsic::x86_fma_vfmadd_ps_256:
10896   case Intrinsic::x86_fma_vfmadd_pd_256:
10897   case Intrinsic::x86_fma_vfmsub_ps_256:
10898   case Intrinsic::x86_fma_vfmsub_pd_256:
10899   case Intrinsic::x86_fma_vfnmadd_ps_256:
10900   case Intrinsic::x86_fma_vfnmadd_pd_256:
10901   case Intrinsic::x86_fma_vfnmsub_ps_256:
10902   case Intrinsic::x86_fma_vfnmsub_pd_256:
10903   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10904   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10905   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10906   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10907     unsigned Opc;
10908     switch (IntNo) {
10909     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10910     case Intrinsic::x86_fma_vfmadd_ps:
10911     case Intrinsic::x86_fma_vfmadd_pd:
10912     case Intrinsic::x86_fma_vfmadd_ps_256:
10913     case Intrinsic::x86_fma_vfmadd_pd_256:
10914       Opc = X86ISD::FMADD;
10915       break;
10916     case Intrinsic::x86_fma_vfmsub_ps:
10917     case Intrinsic::x86_fma_vfmsub_pd:
10918     case Intrinsic::x86_fma_vfmsub_ps_256:
10919     case Intrinsic::x86_fma_vfmsub_pd_256:
10920       Opc = X86ISD::FMSUB;
10921       break;
10922     case Intrinsic::x86_fma_vfnmadd_ps:
10923     case Intrinsic::x86_fma_vfnmadd_pd:
10924     case Intrinsic::x86_fma_vfnmadd_ps_256:
10925     case Intrinsic::x86_fma_vfnmadd_pd_256:
10926       Opc = X86ISD::FNMADD;
10927       break;
10928     case Intrinsic::x86_fma_vfnmsub_ps:
10929     case Intrinsic::x86_fma_vfnmsub_pd:
10930     case Intrinsic::x86_fma_vfnmsub_ps_256:
10931     case Intrinsic::x86_fma_vfnmsub_pd_256:
10932       Opc = X86ISD::FNMSUB;
10933       break;
10934     case Intrinsic::x86_fma_vfmaddsub_ps:
10935     case Intrinsic::x86_fma_vfmaddsub_pd:
10936     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10937     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10938       Opc = X86ISD::FMADDSUB;
10939       break;
10940     case Intrinsic::x86_fma_vfmsubadd_ps:
10941     case Intrinsic::x86_fma_vfmsubadd_pd:
10942     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10943     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10944       Opc = X86ISD::FMSUBADD;
10945       break;
10946     }
10947
10948     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10949                        Op.getOperand(2), Op.getOperand(3));
10950   }
10951   }
10952 }
10953
10954 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10955   DebugLoc dl = Op.getDebugLoc();
10956   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10957   switch (IntNo) {
10958   default: return SDValue();    // Don't custom lower most intrinsics.
10959
10960   // RDRAND/RDSEED intrinsics.
10961   case Intrinsic::x86_rdrand_16:
10962   case Intrinsic::x86_rdrand_32:
10963   case Intrinsic::x86_rdrand_64:
10964   case Intrinsic::x86_rdseed_16:
10965   case Intrinsic::x86_rdseed_32:
10966   case Intrinsic::x86_rdseed_64: {
10967     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10968                        IntNo == Intrinsic::x86_rdseed_32 ||
10969                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
10970                                                             X86ISD::RDRAND;
10971     // Emit the node with the right value type.
10972     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
10973     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
10974
10975     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
10976     // Otherwise return the value from Rand, which is always 0, casted to i32.
10977     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
10978                       DAG.getConstant(1, Op->getValueType(1)),
10979                       DAG.getConstant(X86::COND_B, MVT::i32),
10980                       SDValue(Result.getNode(), 1) };
10981     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
10982                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
10983                                   Ops, 4);
10984
10985     // Return { result, isValid, chain }.
10986     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
10987                        SDValue(Result.getNode(), 2));
10988   }
10989
10990   // XTEST intrinsics.
10991   case Intrinsic::x86_xtest: {
10992     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
10993     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
10994     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10995                                 DAG.getConstant(X86::COND_NE, MVT::i8),
10996                                 InTrans);
10997     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
10998     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
10999                        Ret, SDValue(InTrans.getNode(), 1));
11000   }
11001   }
11002 }
11003
11004 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11005                                            SelectionDAG &DAG) const {
11006   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11007   MFI->setReturnAddressIsTaken(true);
11008
11009   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11010   DebugLoc dl = Op.getDebugLoc();
11011   EVT PtrVT = getPointerTy();
11012
11013   if (Depth > 0) {
11014     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11015     SDValue Offset =
11016       DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11017     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11018                        DAG.getNode(ISD::ADD, dl, PtrVT,
11019                                    FrameAddr, Offset),
11020                        MachinePointerInfo(), false, false, false, 0);
11021   }
11022
11023   // Just load the return address.
11024   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11025   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11026                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11027 }
11028
11029 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11030   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11031   MFI->setFrameAddressIsTaken(true);
11032
11033   EVT VT = Op.getValueType();
11034   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
11035   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11036   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
11037   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11038   while (Depth--)
11039     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11040                             MachinePointerInfo(),
11041                             false, false, false, 0);
11042   return FrameAddr;
11043 }
11044
11045 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11046                                                      SelectionDAG &DAG) const {
11047   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11048 }
11049
11050 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11051   SDValue Chain     = Op.getOperand(0);
11052   SDValue Offset    = Op.getOperand(1);
11053   SDValue Handler   = Op.getOperand(2);
11054   DebugLoc dl       = Op.getDebugLoc();
11055
11056   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
11057                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
11058                                      getPointerTy());
11059   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
11060
11061   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
11062                                   DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11063   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
11064   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11065                        false, false, 0);
11066   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11067
11068   return DAG.getNode(X86ISD::EH_RETURN, dl,
11069                      MVT::Other,
11070                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
11071 }
11072
11073 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11074                                                SelectionDAG &DAG) const {
11075   DebugLoc DL = Op.getDebugLoc();
11076   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11077                      DAG.getVTList(MVT::i32, MVT::Other),
11078                      Op.getOperand(0), Op.getOperand(1));
11079 }
11080
11081 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11082                                                 SelectionDAG &DAG) const {
11083   DebugLoc DL = Op.getDebugLoc();
11084   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11085                      Op.getOperand(0), Op.getOperand(1));
11086 }
11087
11088 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11089   return Op.getOperand(0);
11090 }
11091
11092 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11093                                                 SelectionDAG &DAG) const {
11094   SDValue Root = Op.getOperand(0);
11095   SDValue Trmp = Op.getOperand(1); // trampoline
11096   SDValue FPtr = Op.getOperand(2); // nested function
11097   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11098   DebugLoc dl  = Op.getDebugLoc();
11099
11100   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11101   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11102
11103   if (Subtarget->is64Bit()) {
11104     SDValue OutChains[6];
11105
11106     // Large code-model.
11107     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11108     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11109
11110     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11111     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11112
11113     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11114
11115     // Load the pointer to the nested function into R11.
11116     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11117     SDValue Addr = Trmp;
11118     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11119                                 Addr, MachinePointerInfo(TrmpAddr),
11120                                 false, false, 0);
11121
11122     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11123                        DAG.getConstant(2, MVT::i64));
11124     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11125                                 MachinePointerInfo(TrmpAddr, 2),
11126                                 false, false, 2);
11127
11128     // Load the 'nest' parameter value into R10.
11129     // R10 is specified in X86CallingConv.td
11130     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11131     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11132                        DAG.getConstant(10, MVT::i64));
11133     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11134                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11135                                 false, false, 0);
11136
11137     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11138                        DAG.getConstant(12, MVT::i64));
11139     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11140                                 MachinePointerInfo(TrmpAddr, 12),
11141                                 false, false, 2);
11142
11143     // Jump to the nested function.
11144     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11145     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11146                        DAG.getConstant(20, MVT::i64));
11147     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11148                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11149                                 false, false, 0);
11150
11151     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11152     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11153                        DAG.getConstant(22, MVT::i64));
11154     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11155                                 MachinePointerInfo(TrmpAddr, 22),
11156                                 false, false, 0);
11157
11158     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11159   } else {
11160     const Function *Func =
11161       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11162     CallingConv::ID CC = Func->getCallingConv();
11163     unsigned NestReg;
11164
11165     switch (CC) {
11166     default:
11167       llvm_unreachable("Unsupported calling convention");
11168     case CallingConv::C:
11169     case CallingConv::X86_StdCall: {
11170       // Pass 'nest' parameter in ECX.
11171       // Must be kept in sync with X86CallingConv.td
11172       NestReg = X86::ECX;
11173
11174       // Check that ECX wasn't needed by an 'inreg' parameter.
11175       FunctionType *FTy = Func->getFunctionType();
11176       const AttributeSet &Attrs = Func->getAttributes();
11177
11178       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11179         unsigned InRegCount = 0;
11180         unsigned Idx = 1;
11181
11182         for (FunctionType::param_iterator I = FTy->param_begin(),
11183              E = FTy->param_end(); I != E; ++I, ++Idx)
11184           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11185             // FIXME: should only count parameters that are lowered to integers.
11186             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11187
11188         if (InRegCount > 2) {
11189           report_fatal_error("Nest register in use - reduce number of inreg"
11190                              " parameters!");
11191         }
11192       }
11193       break;
11194     }
11195     case CallingConv::X86_FastCall:
11196     case CallingConv::X86_ThisCall:
11197     case CallingConv::Fast:
11198       // Pass 'nest' parameter in EAX.
11199       // Must be kept in sync with X86CallingConv.td
11200       NestReg = X86::EAX;
11201       break;
11202     }
11203
11204     SDValue OutChains[4];
11205     SDValue Addr, Disp;
11206
11207     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11208                        DAG.getConstant(10, MVT::i32));
11209     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11210
11211     // This is storing the opcode for MOV32ri.
11212     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11213     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11214     OutChains[0] = DAG.getStore(Root, dl,
11215                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11216                                 Trmp, MachinePointerInfo(TrmpAddr),
11217                                 false, false, 0);
11218
11219     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11220                        DAG.getConstant(1, MVT::i32));
11221     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11222                                 MachinePointerInfo(TrmpAddr, 1),
11223                                 false, false, 1);
11224
11225     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11226     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11227                        DAG.getConstant(5, MVT::i32));
11228     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11229                                 MachinePointerInfo(TrmpAddr, 5),
11230                                 false, false, 1);
11231
11232     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11233                        DAG.getConstant(6, MVT::i32));
11234     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11235                                 MachinePointerInfo(TrmpAddr, 6),
11236                                 false, false, 1);
11237
11238     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11239   }
11240 }
11241
11242 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11243                                             SelectionDAG &DAG) const {
11244   /*
11245    The rounding mode is in bits 11:10 of FPSR, and has the following
11246    settings:
11247      00 Round to nearest
11248      01 Round to -inf
11249      10 Round to +inf
11250      11 Round to 0
11251
11252   FLT_ROUNDS, on the other hand, expects the following:
11253     -1 Undefined
11254      0 Round to 0
11255      1 Round to nearest
11256      2 Round to +inf
11257      3 Round to -inf
11258
11259   To perform the conversion, we do:
11260     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11261   */
11262
11263   MachineFunction &MF = DAG.getMachineFunction();
11264   const TargetMachine &TM = MF.getTarget();
11265   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11266   unsigned StackAlignment = TFI.getStackAlignment();
11267   EVT VT = Op.getValueType();
11268   DebugLoc DL = Op.getDebugLoc();
11269
11270   // Save FP Control Word to stack slot
11271   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11272   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11273
11274   MachineMemOperand *MMO =
11275    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11276                            MachineMemOperand::MOStore, 2, 2);
11277
11278   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11279   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11280                                           DAG.getVTList(MVT::Other),
11281                                           Ops, 2, MVT::i16, MMO);
11282
11283   // Load FP Control Word from stack slot
11284   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11285                             MachinePointerInfo(), false, false, false, 0);
11286
11287   // Transform as necessary
11288   SDValue CWD1 =
11289     DAG.getNode(ISD::SRL, DL, MVT::i16,
11290                 DAG.getNode(ISD::AND, DL, MVT::i16,
11291                             CWD, DAG.getConstant(0x800, MVT::i16)),
11292                 DAG.getConstant(11, MVT::i8));
11293   SDValue CWD2 =
11294     DAG.getNode(ISD::SRL, DL, MVT::i16,
11295                 DAG.getNode(ISD::AND, DL, MVT::i16,
11296                             CWD, DAG.getConstant(0x400, MVT::i16)),
11297                 DAG.getConstant(9, MVT::i8));
11298
11299   SDValue RetVal =
11300     DAG.getNode(ISD::AND, DL, MVT::i16,
11301                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11302                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11303                             DAG.getConstant(1, MVT::i16)),
11304                 DAG.getConstant(3, MVT::i16));
11305
11306   return DAG.getNode((VT.getSizeInBits() < 16 ?
11307                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11308 }
11309
11310 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11311   EVT VT = Op.getValueType();
11312   EVT OpVT = VT;
11313   unsigned NumBits = VT.getSizeInBits();
11314   DebugLoc dl = Op.getDebugLoc();
11315
11316   Op = Op.getOperand(0);
11317   if (VT == MVT::i8) {
11318     // Zero extend to i32 since there is not an i8 bsr.
11319     OpVT = MVT::i32;
11320     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11321   }
11322
11323   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11324   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11325   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11326
11327   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11328   SDValue Ops[] = {
11329     Op,
11330     DAG.getConstant(NumBits+NumBits-1, OpVT),
11331     DAG.getConstant(X86::COND_E, MVT::i8),
11332     Op.getValue(1)
11333   };
11334   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11335
11336   // Finally xor with NumBits-1.
11337   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11338
11339   if (VT == MVT::i8)
11340     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11341   return Op;
11342 }
11343
11344 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11345   EVT VT = Op.getValueType();
11346   EVT OpVT = VT;
11347   unsigned NumBits = VT.getSizeInBits();
11348   DebugLoc dl = Op.getDebugLoc();
11349
11350   Op = Op.getOperand(0);
11351   if (VT == MVT::i8) {
11352     // Zero extend to i32 since there is not an i8 bsr.
11353     OpVT = MVT::i32;
11354     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11355   }
11356
11357   // Issue a bsr (scan bits in reverse).
11358   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11359   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11360
11361   // And xor with NumBits-1.
11362   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11363
11364   if (VT == MVT::i8)
11365     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11366   return Op;
11367 }
11368
11369 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11370   EVT VT = Op.getValueType();
11371   unsigned NumBits = VT.getSizeInBits();
11372   DebugLoc dl = Op.getDebugLoc();
11373   Op = Op.getOperand(0);
11374
11375   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11376   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11377   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11378
11379   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11380   SDValue Ops[] = {
11381     Op,
11382     DAG.getConstant(NumBits, VT),
11383     DAG.getConstant(X86::COND_E, MVT::i8),
11384     Op.getValue(1)
11385   };
11386   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11387 }
11388
11389 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11390 // ones, and then concatenate the result back.
11391 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11392   EVT VT = Op.getValueType();
11393
11394   assert(VT.is256BitVector() && VT.isInteger() &&
11395          "Unsupported value type for operation");
11396
11397   unsigned NumElems = VT.getVectorNumElements();
11398   DebugLoc dl = Op.getDebugLoc();
11399
11400   // Extract the LHS vectors
11401   SDValue LHS = Op.getOperand(0);
11402   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11403   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11404
11405   // Extract the RHS vectors
11406   SDValue RHS = Op.getOperand(1);
11407   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11408   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11409
11410   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11411   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11412
11413   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11414                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11415                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11416 }
11417
11418 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11419   assert(Op.getValueType().is256BitVector() &&
11420          Op.getValueType().isInteger() &&
11421          "Only handle AVX 256-bit vector integer operation");
11422   return Lower256IntArith(Op, DAG);
11423 }
11424
11425 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11426   assert(Op.getValueType().is256BitVector() &&
11427          Op.getValueType().isInteger() &&
11428          "Only handle AVX 256-bit vector integer operation");
11429   return Lower256IntArith(Op, DAG);
11430 }
11431
11432 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11433                         SelectionDAG &DAG) {
11434   DebugLoc dl = Op.getDebugLoc();
11435   EVT VT = Op.getValueType();
11436
11437   // Decompose 256-bit ops into smaller 128-bit ops.
11438   if (VT.is256BitVector() && !Subtarget->hasInt256())
11439     return Lower256IntArith(Op, DAG);
11440
11441   SDValue A = Op.getOperand(0);
11442   SDValue B = Op.getOperand(1);
11443
11444   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11445   if (VT == MVT::v4i32) {
11446     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11447            "Should not custom lower when pmuldq is available!");
11448
11449     // Extract the odd parts.
11450     const int UnpackMask[] = { 1, -1, 3, -1 };
11451     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11452     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11453
11454     // Multiply the even parts.
11455     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11456     // Now multiply odd parts.
11457     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11458
11459     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11460     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11461
11462     // Merge the two vectors back together with a shuffle. This expands into 2
11463     // shuffles.
11464     const int ShufMask[] = { 0, 4, 2, 6 };
11465     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11466   }
11467
11468   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11469          "Only know how to lower V2I64/V4I64 multiply");
11470
11471   //  Ahi = psrlqi(a, 32);
11472   //  Bhi = psrlqi(b, 32);
11473   //
11474   //  AloBlo = pmuludq(a, b);
11475   //  AloBhi = pmuludq(a, Bhi);
11476   //  AhiBlo = pmuludq(Ahi, b);
11477
11478   //  AloBhi = psllqi(AloBhi, 32);
11479   //  AhiBlo = psllqi(AhiBlo, 32);
11480   //  return AloBlo + AloBhi + AhiBlo;
11481
11482   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11483
11484   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11485   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11486
11487   // Bit cast to 32-bit vectors for MULUDQ
11488   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11489   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11490   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11491   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11492   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11493
11494   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11495   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11496   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11497
11498   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11499   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11500
11501   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11502   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11503 }
11504
11505 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11506   EVT VT = Op.getValueType();
11507   EVT EltTy = VT.getVectorElementType();
11508   unsigned NumElts = VT.getVectorNumElements();
11509   SDValue N0 = Op.getOperand(0);
11510   DebugLoc dl = Op.getDebugLoc();
11511
11512   // Lower sdiv X, pow2-const.
11513   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11514   if (!C)
11515     return SDValue();
11516
11517   APInt SplatValue, SplatUndef;
11518   unsigned MinSplatBits;
11519   bool HasAnyUndefs;
11520   if (!C->isConstantSplat(SplatValue, SplatUndef, MinSplatBits, HasAnyUndefs))
11521     return SDValue();
11522
11523   if ((SplatValue != 0) &&
11524       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11525     unsigned lg2 = SplatValue.countTrailingZeros();
11526     // Splat the sign bit.
11527     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11528     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11529     // Add (N0 < 0) ? abs2 - 1 : 0;
11530     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11531     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11532     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11533     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11534     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11535
11536     // If we're dividing by a positive value, we're done.  Otherwise, we must
11537     // negate the result.
11538     if (SplatValue.isNonNegative())
11539       return SRA;
11540
11541     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11542     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11543     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11544   }
11545   return SDValue();
11546 }
11547
11548 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11549                                          const X86Subtarget *Subtarget) {
11550   EVT VT = Op.getValueType();
11551   DebugLoc dl = Op.getDebugLoc();
11552   SDValue R = Op.getOperand(0);
11553   SDValue Amt = Op.getOperand(1);
11554
11555   // Optimize shl/srl/sra with constant shift amount.
11556   if (isSplatVector(Amt.getNode())) {
11557     SDValue SclrAmt = Amt->getOperand(0);
11558     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11559       uint64_t ShiftAmt = C->getZExtValue();
11560
11561       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11562           (Subtarget->hasInt256() &&
11563            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11564         if (Op.getOpcode() == ISD::SHL)
11565           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11566                              DAG.getConstant(ShiftAmt, MVT::i32));
11567         if (Op.getOpcode() == ISD::SRL)
11568           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11569                              DAG.getConstant(ShiftAmt, MVT::i32));
11570         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11571           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11572                              DAG.getConstant(ShiftAmt, MVT::i32));
11573       }
11574
11575       if (VT == MVT::v16i8) {
11576         if (Op.getOpcode() == ISD::SHL) {
11577           // Make a large shift.
11578           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11579                                     DAG.getConstant(ShiftAmt, MVT::i32));
11580           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11581           // Zero out the rightmost bits.
11582           SmallVector<SDValue, 16> V(16,
11583                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11584                                                      MVT::i8));
11585           return DAG.getNode(ISD::AND, dl, VT, SHL,
11586                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11587         }
11588         if (Op.getOpcode() == ISD::SRL) {
11589           // Make a large shift.
11590           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11591                                     DAG.getConstant(ShiftAmt, MVT::i32));
11592           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11593           // Zero out the leftmost bits.
11594           SmallVector<SDValue, 16> V(16,
11595                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11596                                                      MVT::i8));
11597           return DAG.getNode(ISD::AND, dl, VT, SRL,
11598                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11599         }
11600         if (Op.getOpcode() == ISD::SRA) {
11601           if (ShiftAmt == 7) {
11602             // R s>> 7  ===  R s< 0
11603             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11604             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11605           }
11606
11607           // R s>> a === ((R u>> a) ^ m) - m
11608           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11609           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11610                                                          MVT::i8));
11611           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11612           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11613           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11614           return Res;
11615         }
11616         llvm_unreachable("Unknown shift opcode.");
11617       }
11618
11619       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11620         if (Op.getOpcode() == ISD::SHL) {
11621           // Make a large shift.
11622           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11623                                     DAG.getConstant(ShiftAmt, MVT::i32));
11624           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11625           // Zero out the rightmost bits.
11626           SmallVector<SDValue, 32> V(32,
11627                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11628                                                      MVT::i8));
11629           return DAG.getNode(ISD::AND, dl, VT, SHL,
11630                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11631         }
11632         if (Op.getOpcode() == ISD::SRL) {
11633           // Make a large shift.
11634           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11635                                     DAG.getConstant(ShiftAmt, MVT::i32));
11636           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11637           // Zero out the leftmost bits.
11638           SmallVector<SDValue, 32> V(32,
11639                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11640                                                      MVT::i8));
11641           return DAG.getNode(ISD::AND, dl, VT, SRL,
11642                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11643         }
11644         if (Op.getOpcode() == ISD::SRA) {
11645           if (ShiftAmt == 7) {
11646             // R s>> 7  ===  R s< 0
11647             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11648             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11649           }
11650
11651           // R s>> a === ((R u>> a) ^ m) - m
11652           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11653           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11654                                                          MVT::i8));
11655           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11656           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11657           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11658           return Res;
11659         }
11660         llvm_unreachable("Unknown shift opcode.");
11661       }
11662     }
11663   }
11664
11665   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11666   if (!Subtarget->is64Bit() &&
11667       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11668       Amt.getOpcode() == ISD::BITCAST &&
11669       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11670     Amt = Amt.getOperand(0);
11671     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11672                      VT.getVectorNumElements();
11673     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11674     uint64_t ShiftAmt = 0;
11675     for (unsigned i = 0; i != Ratio; ++i) {
11676       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11677       if (C == 0)
11678         return SDValue();
11679       // 6 == Log2(64)
11680       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11681     }
11682     // Check remaining shift amounts.
11683     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11684       uint64_t ShAmt = 0;
11685       for (unsigned j = 0; j != Ratio; ++j) {
11686         ConstantSDNode *C =
11687           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11688         if (C == 0)
11689           return SDValue();
11690         // 6 == Log2(64)
11691         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11692       }
11693       if (ShAmt != ShiftAmt)
11694         return SDValue();
11695     }
11696     switch (Op.getOpcode()) {
11697     default:
11698       llvm_unreachable("Unknown shift opcode!");
11699     case ISD::SHL:
11700       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11701                          DAG.getConstant(ShiftAmt, MVT::i32));
11702     case ISD::SRL:
11703       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11704                          DAG.getConstant(ShiftAmt, MVT::i32));
11705     case ISD::SRA:
11706       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11707                          DAG.getConstant(ShiftAmt, MVT::i32));
11708     }
11709   }
11710
11711   return SDValue();
11712 }
11713
11714 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11715                                         const X86Subtarget* Subtarget) {
11716   EVT VT = Op.getValueType();
11717   DebugLoc dl = Op.getDebugLoc();
11718   SDValue R = Op.getOperand(0);
11719   SDValue Amt = Op.getOperand(1);
11720
11721   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11722       VT == MVT::v4i32 || VT == MVT::v8i16 ||
11723       (Subtarget->hasInt256() &&
11724        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11725         VT == MVT::v8i32 || VT == MVT::v16i16))) {
11726     SDValue BaseShAmt;
11727     EVT EltVT = VT.getVectorElementType();
11728
11729     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11730       unsigned NumElts = VT.getVectorNumElements();
11731       unsigned i, j;
11732       for (i = 0; i != NumElts; ++i) {
11733         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11734           continue;
11735         break;
11736       }
11737       for (j = i; j != NumElts; ++j) {
11738         SDValue Arg = Amt.getOperand(j);
11739         if (Arg.getOpcode() == ISD::UNDEF) continue;
11740         if (Arg != Amt.getOperand(i))
11741           break;
11742       }
11743       if (i != NumElts && j == NumElts)
11744         BaseShAmt = Amt.getOperand(i);
11745     } else {
11746       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11747         Amt = Amt.getOperand(0);
11748       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11749                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11750         SDValue InVec = Amt.getOperand(0);
11751         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11752           unsigned NumElts = InVec.getValueType().getVectorNumElements();
11753           unsigned i = 0;
11754           for (; i != NumElts; ++i) {
11755             SDValue Arg = InVec.getOperand(i);
11756             if (Arg.getOpcode() == ISD::UNDEF) continue;
11757             BaseShAmt = Arg;
11758             break;
11759           }
11760         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11761            if (ConstantSDNode *C =
11762                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11763              unsigned SplatIdx =
11764                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11765              if (C->getZExtValue() == SplatIdx)
11766                BaseShAmt = InVec.getOperand(1);
11767            }
11768         }
11769         if (BaseShAmt.getNode() == 0)
11770           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11771                                   DAG.getIntPtrConstant(0));
11772       }
11773     }
11774
11775     if (BaseShAmt.getNode()) {
11776       if (EltVT.bitsGT(MVT::i32))
11777         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11778       else if (EltVT.bitsLT(MVT::i32))
11779         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11780
11781       switch (Op.getOpcode()) {
11782       default:
11783         llvm_unreachable("Unknown shift opcode!");
11784       case ISD::SHL:
11785         switch (VT.getSimpleVT().SimpleTy) {
11786         default: return SDValue();
11787         case MVT::v2i64:
11788         case MVT::v4i32:
11789         case MVT::v8i16:
11790         case MVT::v4i64:
11791         case MVT::v8i32:
11792         case MVT::v16i16:
11793           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11794         }
11795       case ISD::SRA:
11796         switch (VT.getSimpleVT().SimpleTy) {
11797         default: return SDValue();
11798         case MVT::v4i32:
11799         case MVT::v8i16:
11800         case MVT::v8i32:
11801         case MVT::v16i16:
11802           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11803         }
11804       case ISD::SRL:
11805         switch (VT.getSimpleVT().SimpleTy) {
11806         default: return SDValue();
11807         case MVT::v2i64:
11808         case MVT::v4i32:
11809         case MVT::v8i16:
11810         case MVT::v4i64:
11811         case MVT::v8i32:
11812         case MVT::v16i16:
11813           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11814         }
11815       }
11816     }
11817   }
11818
11819   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11820   if (!Subtarget->is64Bit() &&
11821       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11822       Amt.getOpcode() == ISD::BITCAST &&
11823       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11824     Amt = Amt.getOperand(0);
11825     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11826                      VT.getVectorNumElements();
11827     std::vector<SDValue> Vals(Ratio);
11828     for (unsigned i = 0; i != Ratio; ++i)
11829       Vals[i] = Amt.getOperand(i);
11830     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11831       for (unsigned j = 0; j != Ratio; ++j)
11832         if (Vals[j] != Amt.getOperand(i + j))
11833           return SDValue();
11834     }
11835     switch (Op.getOpcode()) {
11836     default:
11837       llvm_unreachable("Unknown shift opcode!");
11838     case ISD::SHL:
11839       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11840     case ISD::SRL:
11841       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11842     case ISD::SRA:
11843       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11844     }
11845   }
11846
11847   return SDValue();
11848 }
11849
11850 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11851
11852   EVT VT = Op.getValueType();
11853   DebugLoc dl = Op.getDebugLoc();
11854   SDValue R = Op.getOperand(0);
11855   SDValue Amt = Op.getOperand(1);
11856   SDValue V;
11857
11858   if (!Subtarget->hasSSE2())
11859     return SDValue();
11860
11861   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11862   if (V.getNode())
11863     return V;
11864
11865   V = LowerScalarVariableShift(Op, DAG, Subtarget);
11866   if (V.getNode())
11867       return V;
11868
11869   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11870   if (Subtarget->hasInt256()) {
11871     if (Op.getOpcode() == ISD::SRL &&
11872         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11873          VT == MVT::v4i64 || VT == MVT::v8i32))
11874       return Op;
11875     if (Op.getOpcode() == ISD::SHL &&
11876         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11877          VT == MVT::v4i64 || VT == MVT::v8i32))
11878       return Op;
11879     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11880       return Op;
11881   }
11882
11883   // Lower SHL with variable shift amount.
11884   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11885     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11886
11887     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11888     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11889     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11890     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11891   }
11892   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11893     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11894
11895     // a = a << 5;
11896     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11897     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11898
11899     // Turn 'a' into a mask suitable for VSELECT
11900     SDValue VSelM = DAG.getConstant(0x80, VT);
11901     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11902     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11903
11904     SDValue CM1 = DAG.getConstant(0x0f, VT);
11905     SDValue CM2 = DAG.getConstant(0x3f, VT);
11906
11907     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11908     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11909     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11910                             DAG.getConstant(4, MVT::i32), DAG);
11911     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11912     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11913
11914     // a += a
11915     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11916     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11917     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11918
11919     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11920     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11921     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11922                             DAG.getConstant(2, MVT::i32), DAG);
11923     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11924     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11925
11926     // a += a
11927     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11928     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11929     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11930
11931     // return VSELECT(r, r+r, a);
11932     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11933                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11934     return R;
11935   }
11936
11937   // Decompose 256-bit shifts into smaller 128-bit shifts.
11938   if (VT.is256BitVector()) {
11939     unsigned NumElems = VT.getVectorNumElements();
11940     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11941     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11942
11943     // Extract the two vectors
11944     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11945     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11946
11947     // Recreate the shift amount vectors
11948     SDValue Amt1, Amt2;
11949     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11950       // Constant shift amount
11951       SmallVector<SDValue, 4> Amt1Csts;
11952       SmallVector<SDValue, 4> Amt2Csts;
11953       for (unsigned i = 0; i != NumElems/2; ++i)
11954         Amt1Csts.push_back(Amt->getOperand(i));
11955       for (unsigned i = NumElems/2; i != NumElems; ++i)
11956         Amt2Csts.push_back(Amt->getOperand(i));
11957
11958       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11959                                  &Amt1Csts[0], NumElems/2);
11960       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
11961                                  &Amt2Csts[0], NumElems/2);
11962     } else {
11963       // Variable shift amount
11964       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
11965       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
11966     }
11967
11968     // Issue new vector shifts for the smaller types
11969     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
11970     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
11971
11972     // Concatenate the result back
11973     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
11974   }
11975
11976   return SDValue();
11977 }
11978
11979 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
11980   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
11981   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
11982   // looks for this combo and may remove the "setcc" instruction if the "setcc"
11983   // has only one use.
11984   SDNode *N = Op.getNode();
11985   SDValue LHS = N->getOperand(0);
11986   SDValue RHS = N->getOperand(1);
11987   unsigned BaseOp = 0;
11988   unsigned Cond = 0;
11989   DebugLoc DL = Op.getDebugLoc();
11990   switch (Op.getOpcode()) {
11991   default: llvm_unreachable("Unknown ovf instruction!");
11992   case ISD::SADDO:
11993     // A subtract of one will be selected as a INC. Note that INC doesn't
11994     // set CF, so we can't do this for UADDO.
11995     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11996       if (C->isOne()) {
11997         BaseOp = X86ISD::INC;
11998         Cond = X86::COND_O;
11999         break;
12000       }
12001     BaseOp = X86ISD::ADD;
12002     Cond = X86::COND_O;
12003     break;
12004   case ISD::UADDO:
12005     BaseOp = X86ISD::ADD;
12006     Cond = X86::COND_B;
12007     break;
12008   case ISD::SSUBO:
12009     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12010     // set CF, so we can't do this for USUBO.
12011     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12012       if (C->isOne()) {
12013         BaseOp = X86ISD::DEC;
12014         Cond = X86::COND_O;
12015         break;
12016       }
12017     BaseOp = X86ISD::SUB;
12018     Cond = X86::COND_O;
12019     break;
12020   case ISD::USUBO:
12021     BaseOp = X86ISD::SUB;
12022     Cond = X86::COND_B;
12023     break;
12024   case ISD::SMULO:
12025     BaseOp = X86ISD::SMUL;
12026     Cond = X86::COND_O;
12027     break;
12028   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12029     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12030                                  MVT::i32);
12031     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12032
12033     SDValue SetCC =
12034       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12035                   DAG.getConstant(X86::COND_O, MVT::i32),
12036                   SDValue(Sum.getNode(), 2));
12037
12038     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12039   }
12040   }
12041
12042   // Also sets EFLAGS.
12043   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12044   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12045
12046   SDValue SetCC =
12047     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12048                 DAG.getConstant(Cond, MVT::i32),
12049                 SDValue(Sum.getNode(), 1));
12050
12051   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12052 }
12053
12054 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12055                                                   SelectionDAG &DAG) const {
12056   DebugLoc dl = Op.getDebugLoc();
12057   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12058   EVT VT = Op.getValueType();
12059
12060   if (!Subtarget->hasSSE2() || !VT.isVector())
12061     return SDValue();
12062
12063   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12064                       ExtraVT.getScalarType().getSizeInBits();
12065   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12066
12067   switch (VT.getSimpleVT().SimpleTy) {
12068     default: return SDValue();
12069     case MVT::v8i32:
12070     case MVT::v16i16:
12071       if (!Subtarget->hasFp256())
12072         return SDValue();
12073       if (!Subtarget->hasInt256()) {
12074         // needs to be split
12075         unsigned NumElems = VT.getVectorNumElements();
12076
12077         // Extract the LHS vectors
12078         SDValue LHS = Op.getOperand(0);
12079         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12080         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12081
12082         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12083         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12084
12085         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12086         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12087         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12088                                    ExtraNumElems/2);
12089         SDValue Extra = DAG.getValueType(ExtraVT);
12090
12091         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12092         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12093
12094         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12095       }
12096       // fall through
12097     case MVT::v4i32:
12098     case MVT::v8i16: {
12099       // (sext (vzext x)) -> (vsext x)
12100       SDValue Op0 = Op.getOperand(0);
12101       SDValue Op00 = Op0.getOperand(0);
12102       SDValue Tmp1;
12103       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12104       if (Op0.getOpcode() == ISD::BITCAST &&
12105           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12106         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12107       if (Tmp1.getNode()) {
12108         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12109         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12110                "This optimization is invalid without a VZEXT.");
12111         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12112       }
12113
12114       // If the above didn't work, then just use Shift-Left + Shift-Right.
12115       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12116       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12117     }
12118   }
12119 }
12120
12121 static SDValue LowerMEMBARRIER(SDValue Op, const X86Subtarget *Subtarget,
12122                               SelectionDAG &DAG) {
12123   DebugLoc dl = Op.getDebugLoc();
12124
12125   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
12126   // There isn't any reason to disable it if the target processor supports it.
12127   if (!Subtarget->hasSSE2() && !Subtarget->is64Bit()) {
12128     SDValue Chain = Op.getOperand(0);
12129     SDValue Zero = DAG.getConstant(0, MVT::i32);
12130     SDValue Ops[] = {
12131       DAG.getRegister(X86::ESP, MVT::i32), // Base
12132       DAG.getTargetConstant(1, MVT::i8),   // Scale
12133       DAG.getRegister(0, MVT::i32),        // Index
12134       DAG.getTargetConstant(0, MVT::i32),  // Disp
12135       DAG.getRegister(0, MVT::i32),        // Segment.
12136       Zero,
12137       Chain
12138     };
12139     SDNode *Res =
12140       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12141                           array_lengthof(Ops));
12142     return SDValue(Res, 0);
12143   }
12144
12145   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
12146   if (!isDev)
12147     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12148
12149   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12150   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12151   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
12152   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
12153
12154   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
12155   if (!Op1 && !Op2 && !Op3 && Op4)
12156     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
12157
12158   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
12159   if (Op1 && !Op2 && !Op3 && !Op4)
12160     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
12161
12162   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
12163   //           (MFENCE)>;
12164   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12165 }
12166
12167 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12168                                  SelectionDAG &DAG) {
12169   DebugLoc dl = Op.getDebugLoc();
12170   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12171     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12172   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12173     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12174
12175   // The only fence that needs an instruction is a sequentially-consistent
12176   // cross-thread fence.
12177   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12178     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12179     // no-sse2). There isn't any reason to disable it if the target processor
12180     // supports it.
12181     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12182       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12183
12184     SDValue Chain = Op.getOperand(0);
12185     SDValue Zero = DAG.getConstant(0, MVT::i32);
12186     SDValue Ops[] = {
12187       DAG.getRegister(X86::ESP, MVT::i32), // Base
12188       DAG.getTargetConstant(1, MVT::i8),   // Scale
12189       DAG.getRegister(0, MVT::i32),        // Index
12190       DAG.getTargetConstant(0, MVT::i32),  // Disp
12191       DAG.getRegister(0, MVT::i32),        // Segment.
12192       Zero,
12193       Chain
12194     };
12195     SDNode *Res =
12196       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
12197                          array_lengthof(Ops));
12198     return SDValue(Res, 0);
12199   }
12200
12201   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12202   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12203 }
12204
12205 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12206                              SelectionDAG &DAG) {
12207   EVT T = Op.getValueType();
12208   DebugLoc DL = Op.getDebugLoc();
12209   unsigned Reg = 0;
12210   unsigned size = 0;
12211   switch(T.getSimpleVT().SimpleTy) {
12212   default: llvm_unreachable("Invalid value type!");
12213   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12214   case MVT::i16: Reg = X86::AX;  size = 2; break;
12215   case MVT::i32: Reg = X86::EAX; size = 4; break;
12216   case MVT::i64:
12217     assert(Subtarget->is64Bit() && "Node not type legal!");
12218     Reg = X86::RAX; size = 8;
12219     break;
12220   }
12221   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12222                                     Op.getOperand(2), SDValue());
12223   SDValue Ops[] = { cpIn.getValue(0),
12224                     Op.getOperand(1),
12225                     Op.getOperand(3),
12226                     DAG.getTargetConstant(size, MVT::i8),
12227                     cpIn.getValue(1) };
12228   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12229   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12230   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12231                                            Ops, 5, T, MMO);
12232   SDValue cpOut =
12233     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12234   return cpOut;
12235 }
12236
12237 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12238                                      SelectionDAG &DAG) {
12239   assert(Subtarget->is64Bit() && "Result not type legalized?");
12240   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12241   SDValue TheChain = Op.getOperand(0);
12242   DebugLoc dl = Op.getDebugLoc();
12243   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12244   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12245   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12246                                    rax.getValue(2));
12247   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12248                             DAG.getConstant(32, MVT::i8));
12249   SDValue Ops[] = {
12250     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12251     rdx.getValue(1)
12252   };
12253   return DAG.getMergeValues(Ops, 2, dl);
12254 }
12255
12256 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12257   EVT SrcVT = Op.getOperand(0).getValueType();
12258   EVT DstVT = Op.getValueType();
12259   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12260          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12261   assert((DstVT == MVT::i64 ||
12262           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12263          "Unexpected custom BITCAST");
12264   // i64 <=> MMX conversions are Legal.
12265   if (SrcVT==MVT::i64 && DstVT.isVector())
12266     return Op;
12267   if (DstVT==MVT::i64 && SrcVT.isVector())
12268     return Op;
12269   // MMX <=> MMX conversions are Legal.
12270   if (SrcVT.isVector() && DstVT.isVector())
12271     return Op;
12272   // All other conversions need to be expanded.
12273   return SDValue();
12274 }
12275
12276 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12277   SDNode *Node = Op.getNode();
12278   DebugLoc dl = Node->getDebugLoc();
12279   EVT T = Node->getValueType(0);
12280   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12281                               DAG.getConstant(0, T), Node->getOperand(2));
12282   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12283                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12284                        Node->getOperand(0),
12285                        Node->getOperand(1), negOp,
12286                        cast<AtomicSDNode>(Node)->getSrcValue(),
12287                        cast<AtomicSDNode>(Node)->getAlignment(),
12288                        cast<AtomicSDNode>(Node)->getOrdering(),
12289                        cast<AtomicSDNode>(Node)->getSynchScope());
12290 }
12291
12292 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12293   SDNode *Node = Op.getNode();
12294   DebugLoc dl = Node->getDebugLoc();
12295   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12296
12297   // Convert seq_cst store -> xchg
12298   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12299   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12300   //        (The only way to get a 16-byte store is cmpxchg16b)
12301   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12302   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12303       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12304     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12305                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12306                                  Node->getOperand(0),
12307                                  Node->getOperand(1), Node->getOperand(2),
12308                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12309                                  cast<AtomicSDNode>(Node)->getOrdering(),
12310                                  cast<AtomicSDNode>(Node)->getSynchScope());
12311     return Swap.getValue(1);
12312   }
12313   // Other atomic stores have a simple pattern.
12314   return Op;
12315 }
12316
12317 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12318   EVT VT = Op.getNode()->getValueType(0);
12319
12320   // Let legalize expand this if it isn't a legal type yet.
12321   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12322     return SDValue();
12323
12324   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12325
12326   unsigned Opc;
12327   bool ExtraOp = false;
12328   switch (Op.getOpcode()) {
12329   default: llvm_unreachable("Invalid code");
12330   case ISD::ADDC: Opc = X86ISD::ADD; break;
12331   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12332   case ISD::SUBC: Opc = X86ISD::SUB; break;
12333   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12334   }
12335
12336   if (!ExtraOp)
12337     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12338                        Op.getOperand(1));
12339   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
12340                      Op.getOperand(1), Op.getOperand(2));
12341 }
12342
12343 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12344   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12345
12346   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12347   // which returns the values as { float, float } (in XMM0) or
12348   // { double, double } (which is returned in XMM0, XMM1).
12349   DebugLoc dl = Op.getDebugLoc();
12350   SDValue Arg = Op.getOperand(0);
12351   EVT ArgVT = Arg.getValueType();
12352   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12353
12354   ArgListTy Args;
12355   ArgListEntry Entry;
12356
12357   Entry.Node = Arg;
12358   Entry.Ty = ArgTy;
12359   Entry.isSExt = false;
12360   Entry.isZExt = false;
12361   Args.push_back(Entry);
12362
12363   bool isF64 = ArgVT == MVT::f64;
12364   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12365   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12366   // the results are returned via SRet in memory.
12367   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12368   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12369
12370   Type *RetTy = isF64
12371     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12372     : (Type*)VectorType::get(ArgTy, 4);
12373   TargetLowering::
12374     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12375                          false, false, false, false, 0,
12376                          CallingConv::C, /*isTaillCall=*/false,
12377                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12378                          Callee, Args, DAG, dl);
12379   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12380
12381   if (isF64)
12382     // Returned in xmm0 and xmm1.
12383     return CallResult.first;
12384
12385   // Returned in bits 0:31 and 32:64 xmm0.
12386   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12387                                CallResult.first, DAG.getIntPtrConstant(0));
12388   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12389                                CallResult.first, DAG.getIntPtrConstant(1));
12390   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12391   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12392 }
12393
12394 /// LowerOperation - Provide custom lowering hooks for some operations.
12395 ///
12396 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12397   switch (Op.getOpcode()) {
12398   default: llvm_unreachable("Should not custom lower this!");
12399   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12400   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, Subtarget, DAG);
12401   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12402   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12403   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12404   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12405   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12406   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12407   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12408   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12409   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12410   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12411   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12412   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12413   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12414   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12415   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12416   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12417   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12418   case ISD::SHL_PARTS:
12419   case ISD::SRA_PARTS:
12420   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12421   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12422   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12423   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12424   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12425   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12426   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12427   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12428   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12429   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12430   case ISD::FABS:               return LowerFABS(Op, DAG);
12431   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12432   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12433   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12434   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12435   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12436   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12437   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12438   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12439   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12440   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12441   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12442   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12443   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12444   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12445   case ISD::FRAME_TO_ARGS_OFFSET:
12446                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12447   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12448   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12449   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12450   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12451   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12452   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12453   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12454   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12455   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12456   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12457   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12458   case ISD::SRA:
12459   case ISD::SRL:
12460   case ISD::SHL:                return LowerShift(Op, DAG);
12461   case ISD::SADDO:
12462   case ISD::UADDO:
12463   case ISD::SSUBO:
12464   case ISD::USUBO:
12465   case ISD::SMULO:
12466   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12467   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12468   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12469   case ISD::ADDC:
12470   case ISD::ADDE:
12471   case ISD::SUBC:
12472   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12473   case ISD::ADD:                return LowerADD(Op, DAG);
12474   case ISD::SUB:                return LowerSUB(Op, DAG);
12475   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12476   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12477   }
12478 }
12479
12480 static void ReplaceATOMIC_LOAD(SDNode *Node,
12481                                   SmallVectorImpl<SDValue> &Results,
12482                                   SelectionDAG &DAG) {
12483   DebugLoc dl = Node->getDebugLoc();
12484   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12485
12486   // Convert wide load -> cmpxchg8b/cmpxchg16b
12487   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12488   //        (The only way to get a 16-byte load is cmpxchg16b)
12489   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12490   SDValue Zero = DAG.getConstant(0, VT);
12491   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12492                                Node->getOperand(0),
12493                                Node->getOperand(1), Zero, Zero,
12494                                cast<AtomicSDNode>(Node)->getMemOperand(),
12495                                cast<AtomicSDNode>(Node)->getOrdering(),
12496                                cast<AtomicSDNode>(Node)->getSynchScope());
12497   Results.push_back(Swap.getValue(0));
12498   Results.push_back(Swap.getValue(1));
12499 }
12500
12501 static void
12502 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12503                         SelectionDAG &DAG, unsigned NewOp) {
12504   DebugLoc dl = Node->getDebugLoc();
12505   assert (Node->getValueType(0) == MVT::i64 &&
12506           "Only know how to expand i64 atomics");
12507
12508   SDValue Chain = Node->getOperand(0);
12509   SDValue In1 = Node->getOperand(1);
12510   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12511                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12512   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12513                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12514   SDValue Ops[] = { Chain, In1, In2L, In2H };
12515   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12516   SDValue Result =
12517     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
12518                             cast<MemSDNode>(Node)->getMemOperand());
12519   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12520   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12521   Results.push_back(Result.getValue(2));
12522 }
12523
12524 /// ReplaceNodeResults - Replace a node with an illegal result type
12525 /// with a new node built out of custom code.
12526 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12527                                            SmallVectorImpl<SDValue>&Results,
12528                                            SelectionDAG &DAG) const {
12529   DebugLoc dl = N->getDebugLoc();
12530   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12531   switch (N->getOpcode()) {
12532   default:
12533     llvm_unreachable("Do not know how to custom type legalize this operation!");
12534   case ISD::SIGN_EXTEND_INREG:
12535   case ISD::ADDC:
12536   case ISD::ADDE:
12537   case ISD::SUBC:
12538   case ISD::SUBE:
12539     // We don't want to expand or promote these.
12540     return;
12541   case ISD::FP_TO_SINT:
12542   case ISD::FP_TO_UINT: {
12543     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12544
12545     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12546       return;
12547
12548     std::pair<SDValue,SDValue> Vals =
12549         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12550     SDValue FIST = Vals.first, StackSlot = Vals.second;
12551     if (FIST.getNode() != 0) {
12552       EVT VT = N->getValueType(0);
12553       // Return a load from the stack slot.
12554       if (StackSlot.getNode() != 0)
12555         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12556                                       MachinePointerInfo(),
12557                                       false, false, false, 0));
12558       else
12559         Results.push_back(FIST);
12560     }
12561     return;
12562   }
12563   case ISD::UINT_TO_FP: {
12564     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12565     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12566         N->getValueType(0) != MVT::v2f32)
12567       return;
12568     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12569                                  N->getOperand(0));
12570     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12571                                      MVT::f64);
12572     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12573     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12574                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12575     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12576     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12577     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12578     return;
12579   }
12580   case ISD::FP_ROUND: {
12581     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12582         return;
12583     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12584     Results.push_back(V);
12585     return;
12586   }
12587   case ISD::READCYCLECOUNTER: {
12588     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12589     SDValue TheChain = N->getOperand(0);
12590     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12591     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12592                                      rd.getValue(1));
12593     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12594                                      eax.getValue(2));
12595     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12596     SDValue Ops[] = { eax, edx };
12597     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
12598     Results.push_back(edx.getValue(1));
12599     return;
12600   }
12601   case ISD::ATOMIC_CMP_SWAP: {
12602     EVT T = N->getValueType(0);
12603     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12604     bool Regs64bit = T == MVT::i128;
12605     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12606     SDValue cpInL, cpInH;
12607     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12608                         DAG.getConstant(0, HalfT));
12609     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12610                         DAG.getConstant(1, HalfT));
12611     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12612                              Regs64bit ? X86::RAX : X86::EAX,
12613                              cpInL, SDValue());
12614     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12615                              Regs64bit ? X86::RDX : X86::EDX,
12616                              cpInH, cpInL.getValue(1));
12617     SDValue swapInL, swapInH;
12618     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12619                           DAG.getConstant(0, HalfT));
12620     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12621                           DAG.getConstant(1, HalfT));
12622     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12623                                Regs64bit ? X86::RBX : X86::EBX,
12624                                swapInL, cpInH.getValue(1));
12625     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12626                                Regs64bit ? X86::RCX : X86::ECX,
12627                                swapInH, swapInL.getValue(1));
12628     SDValue Ops[] = { swapInH.getValue(0),
12629                       N->getOperand(1),
12630                       swapInH.getValue(1) };
12631     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12632     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12633     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12634                                   X86ISD::LCMPXCHG8_DAG;
12635     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12636                                              Ops, 3, T, MMO);
12637     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12638                                         Regs64bit ? X86::RAX : X86::EAX,
12639                                         HalfT, Result.getValue(1));
12640     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12641                                         Regs64bit ? X86::RDX : X86::EDX,
12642                                         HalfT, cpOutL.getValue(2));
12643     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12644     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12645     Results.push_back(cpOutH.getValue(1));
12646     return;
12647   }
12648   case ISD::ATOMIC_LOAD_ADD:
12649   case ISD::ATOMIC_LOAD_AND:
12650   case ISD::ATOMIC_LOAD_NAND:
12651   case ISD::ATOMIC_LOAD_OR:
12652   case ISD::ATOMIC_LOAD_SUB:
12653   case ISD::ATOMIC_LOAD_XOR:
12654   case ISD::ATOMIC_LOAD_MAX:
12655   case ISD::ATOMIC_LOAD_MIN:
12656   case ISD::ATOMIC_LOAD_UMAX:
12657   case ISD::ATOMIC_LOAD_UMIN:
12658   case ISD::ATOMIC_SWAP: {
12659     unsigned Opc;
12660     switch (N->getOpcode()) {
12661     default: llvm_unreachable("Unexpected opcode");
12662     case ISD::ATOMIC_LOAD_ADD:
12663       Opc = X86ISD::ATOMADD64_DAG;
12664       break;
12665     case ISD::ATOMIC_LOAD_AND:
12666       Opc = X86ISD::ATOMAND64_DAG;
12667       break;
12668     case ISD::ATOMIC_LOAD_NAND:
12669       Opc = X86ISD::ATOMNAND64_DAG;
12670       break;
12671     case ISD::ATOMIC_LOAD_OR:
12672       Opc = X86ISD::ATOMOR64_DAG;
12673       break;
12674     case ISD::ATOMIC_LOAD_SUB:
12675       Opc = X86ISD::ATOMSUB64_DAG;
12676       break;
12677     case ISD::ATOMIC_LOAD_XOR:
12678       Opc = X86ISD::ATOMXOR64_DAG;
12679       break;
12680     case ISD::ATOMIC_LOAD_MAX:
12681       Opc = X86ISD::ATOMMAX64_DAG;
12682       break;
12683     case ISD::ATOMIC_LOAD_MIN:
12684       Opc = X86ISD::ATOMMIN64_DAG;
12685       break;
12686     case ISD::ATOMIC_LOAD_UMAX:
12687       Opc = X86ISD::ATOMUMAX64_DAG;
12688       break;
12689     case ISD::ATOMIC_LOAD_UMIN:
12690       Opc = X86ISD::ATOMUMIN64_DAG;
12691       break;
12692     case ISD::ATOMIC_SWAP:
12693       Opc = X86ISD::ATOMSWAP64_DAG;
12694       break;
12695     }
12696     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12697     return;
12698   }
12699   case ISD::ATOMIC_LOAD:
12700     ReplaceATOMIC_LOAD(N, Results, DAG);
12701   }
12702 }
12703
12704 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12705   switch (Opcode) {
12706   default: return NULL;
12707   case X86ISD::BSF:                return "X86ISD::BSF";
12708   case X86ISD::BSR:                return "X86ISD::BSR";
12709   case X86ISD::SHLD:               return "X86ISD::SHLD";
12710   case X86ISD::SHRD:               return "X86ISD::SHRD";
12711   case X86ISD::FAND:               return "X86ISD::FAND";
12712   case X86ISD::FOR:                return "X86ISD::FOR";
12713   case X86ISD::FXOR:               return "X86ISD::FXOR";
12714   case X86ISD::FSRL:               return "X86ISD::FSRL";
12715   case X86ISD::FILD:               return "X86ISD::FILD";
12716   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12717   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12718   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12719   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12720   case X86ISD::FLD:                return "X86ISD::FLD";
12721   case X86ISD::FST:                return "X86ISD::FST";
12722   case X86ISD::CALL:               return "X86ISD::CALL";
12723   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12724   case X86ISD::BT:                 return "X86ISD::BT";
12725   case X86ISD::CMP:                return "X86ISD::CMP";
12726   case X86ISD::COMI:               return "X86ISD::COMI";
12727   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12728   case X86ISD::SETCC:              return "X86ISD::SETCC";
12729   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12730   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12731   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12732   case X86ISD::CMOV:               return "X86ISD::CMOV";
12733   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12734   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12735   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12736   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12737   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12738   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12739   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12740   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12741   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12742   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12743   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12744   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12745   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12746   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12747   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12748   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12749   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12750   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12751   case X86ISD::HADD:               return "X86ISD::HADD";
12752   case X86ISD::HSUB:               return "X86ISD::HSUB";
12753   case X86ISD::FHADD:              return "X86ISD::FHADD";
12754   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12755   case X86ISD::UMAX:               return "X86ISD::UMAX";
12756   case X86ISD::UMIN:               return "X86ISD::UMIN";
12757   case X86ISD::SMAX:               return "X86ISD::SMAX";
12758   case X86ISD::SMIN:               return "X86ISD::SMIN";
12759   case X86ISD::FMAX:               return "X86ISD::FMAX";
12760   case X86ISD::FMIN:               return "X86ISD::FMIN";
12761   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12762   case X86ISD::FMINC:              return "X86ISD::FMINC";
12763   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12764   case X86ISD::FRCP:               return "X86ISD::FRCP";
12765   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12766   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12767   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12768   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12769   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12770   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12771   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12772   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12773   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12774   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12775   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12776   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12777   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12778   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12779   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12780   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12781   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12782   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12783   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12784   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12785   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12786   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12787   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12788   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12789   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12790   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12791   case X86ISD::VSHL:               return "X86ISD::VSHL";
12792   case X86ISD::VSRL:               return "X86ISD::VSRL";
12793   case X86ISD::VSRA:               return "X86ISD::VSRA";
12794   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12795   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12796   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12797   case X86ISD::CMPP:               return "X86ISD::CMPP";
12798   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12799   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12800   case X86ISD::ADD:                return "X86ISD::ADD";
12801   case X86ISD::SUB:                return "X86ISD::SUB";
12802   case X86ISD::ADC:                return "X86ISD::ADC";
12803   case X86ISD::SBB:                return "X86ISD::SBB";
12804   case X86ISD::SMUL:               return "X86ISD::SMUL";
12805   case X86ISD::UMUL:               return "X86ISD::UMUL";
12806   case X86ISD::INC:                return "X86ISD::INC";
12807   case X86ISD::DEC:                return "X86ISD::DEC";
12808   case X86ISD::OR:                 return "X86ISD::OR";
12809   case X86ISD::XOR:                return "X86ISD::XOR";
12810   case X86ISD::AND:                return "X86ISD::AND";
12811   case X86ISD::BLSI:               return "X86ISD::BLSI";
12812   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12813   case X86ISD::BLSR:               return "X86ISD::BLSR";
12814   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12815   case X86ISD::PTEST:              return "X86ISD::PTEST";
12816   case X86ISD::TESTP:              return "X86ISD::TESTP";
12817   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12818   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12819   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12820   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12821   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12822   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12823   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12824   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12825   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12826   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12827   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12828   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12829   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12830   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12831   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12832   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12833   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12834   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12835   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12836   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12837   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12838   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12839   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12840   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12841   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12842   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12843   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12844   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12845   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12846   case X86ISD::SAHF:               return "X86ISD::SAHF";
12847   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12848   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12849   case X86ISD::FMADD:              return "X86ISD::FMADD";
12850   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12851   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12852   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12853   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12854   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12855   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12856   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12857   case X86ISD::XTEST:              return "X86ISD::XTEST";
12858   }
12859 }
12860
12861 // isLegalAddressingMode - Return true if the addressing mode represented
12862 // by AM is legal for this target, for a load/store of the specified type.
12863 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12864                                               Type *Ty) const {
12865   // X86 supports extremely general addressing modes.
12866   CodeModel::Model M = getTargetMachine().getCodeModel();
12867   Reloc::Model R = getTargetMachine().getRelocationModel();
12868
12869   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12870   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12871     return false;
12872
12873   if (AM.BaseGV) {
12874     unsigned GVFlags =
12875       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12876
12877     // If a reference to this global requires an extra load, we can't fold it.
12878     if (isGlobalStubReference(GVFlags))
12879       return false;
12880
12881     // If BaseGV requires a register for the PIC base, we cannot also have a
12882     // BaseReg specified.
12883     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12884       return false;
12885
12886     // If lower 4G is not available, then we must use rip-relative addressing.
12887     if ((M != CodeModel::Small || R != Reloc::Static) &&
12888         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12889       return false;
12890   }
12891
12892   switch (AM.Scale) {
12893   case 0:
12894   case 1:
12895   case 2:
12896   case 4:
12897   case 8:
12898     // These scales always work.
12899     break;
12900   case 3:
12901   case 5:
12902   case 9:
12903     // These scales are formed with basereg+scalereg.  Only accept if there is
12904     // no basereg yet.
12905     if (AM.HasBaseReg)
12906       return false;
12907     break;
12908   default:  // Other stuff never works.
12909     return false;
12910   }
12911
12912   return true;
12913 }
12914
12915 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12916   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12917     return false;
12918   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12919   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12920   return NumBits1 > NumBits2;
12921 }
12922
12923 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12924   return isInt<32>(Imm);
12925 }
12926
12927 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12928   // Can also use sub to handle negated immediates.
12929   return isInt<32>(Imm);
12930 }
12931
12932 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12933   if (!VT1.isInteger() || !VT2.isInteger())
12934     return false;
12935   unsigned NumBits1 = VT1.getSizeInBits();
12936   unsigned NumBits2 = VT2.getSizeInBits();
12937   return NumBits1 > NumBits2;
12938 }
12939
12940 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12941   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12942   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12943 }
12944
12945 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12946   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12947   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12948 }
12949
12950 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12951   EVT VT1 = Val.getValueType();
12952   if (isZExtFree(VT1, VT2))
12953     return true;
12954
12955   if (Val.getOpcode() != ISD::LOAD)
12956     return false;
12957
12958   if (!VT1.isSimple() || !VT1.isInteger() ||
12959       !VT2.isSimple() || !VT2.isInteger())
12960     return false;
12961
12962   switch (VT1.getSimpleVT().SimpleTy) {
12963   default: break;
12964   case MVT::i8:
12965   case MVT::i16:
12966   case MVT::i32:
12967     // X86 has 8, 16, and 32-bit zero-extending loads.
12968     return true;
12969   }
12970
12971   return false;
12972 }
12973
12974 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12975   // i16 instructions are longer (0x66 prefix) and potentially slower.
12976   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12977 }
12978
12979 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12980 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12981 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12982 /// are assumed to be legal.
12983 bool
12984 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12985                                       EVT VT) const {
12986   // Very little shuffling can be done for 64-bit vectors right now.
12987   if (VT.getSizeInBits() == 64)
12988     return false;
12989
12990   // FIXME: pshufb, blends, shifts.
12991   return (VT.getVectorNumElements() == 2 ||
12992           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12993           isMOVLMask(M, VT) ||
12994           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12995           isPSHUFDMask(M, VT) ||
12996           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12997           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12998           isPALIGNRMask(M, VT, Subtarget) ||
12999           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
13000           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
13001           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
13002           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13003 }
13004
13005 bool
13006 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13007                                           EVT VT) const {
13008   unsigned NumElts = VT.getVectorNumElements();
13009   // FIXME: This collection of masks seems suspect.
13010   if (NumElts == 2)
13011     return true;
13012   if (NumElts == 4 && VT.is128BitVector()) {
13013     return (isMOVLMask(Mask, VT)  ||
13014             isCommutedMOVLMask(Mask, VT, true) ||
13015             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13016             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13017   }
13018   return false;
13019 }
13020
13021 //===----------------------------------------------------------------------===//
13022 //                           X86 Scheduler Hooks
13023 //===----------------------------------------------------------------------===//
13024
13025 /// Utility function to emit xbegin specifying the start of an RTM region.
13026 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13027                                      const TargetInstrInfo *TII) {
13028   DebugLoc DL = MI->getDebugLoc();
13029
13030   const BasicBlock *BB = MBB->getBasicBlock();
13031   MachineFunction::iterator I = MBB;
13032   ++I;
13033
13034   // For the v = xbegin(), we generate
13035   //
13036   // thisMBB:
13037   //  xbegin sinkMBB
13038   //
13039   // mainMBB:
13040   //  eax = -1
13041   //
13042   // sinkMBB:
13043   //  v = eax
13044
13045   MachineBasicBlock *thisMBB = MBB;
13046   MachineFunction *MF = MBB->getParent();
13047   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13048   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13049   MF->insert(I, mainMBB);
13050   MF->insert(I, sinkMBB);
13051
13052   // Transfer the remainder of BB and its successor edges to sinkMBB.
13053   sinkMBB->splice(sinkMBB->begin(), MBB,
13054                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13055   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13056
13057   // thisMBB:
13058   //  xbegin sinkMBB
13059   //  # fallthrough to mainMBB
13060   //  # abortion to sinkMBB
13061   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13062   thisMBB->addSuccessor(mainMBB);
13063   thisMBB->addSuccessor(sinkMBB);
13064
13065   // mainMBB:
13066   //  EAX = -1
13067   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13068   mainMBB->addSuccessor(sinkMBB);
13069
13070   // sinkMBB:
13071   // EAX is live into the sinkMBB
13072   sinkMBB->addLiveIn(X86::EAX);
13073   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13074           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13075     .addReg(X86::EAX);
13076
13077   MI->eraseFromParent();
13078   return sinkMBB;
13079 }
13080
13081 // Get CMPXCHG opcode for the specified data type.
13082 static unsigned getCmpXChgOpcode(EVT VT) {
13083   switch (VT.getSimpleVT().SimpleTy) {
13084   case MVT::i8:  return X86::LCMPXCHG8;
13085   case MVT::i16: return X86::LCMPXCHG16;
13086   case MVT::i32: return X86::LCMPXCHG32;
13087   case MVT::i64: return X86::LCMPXCHG64;
13088   default:
13089     break;
13090   }
13091   llvm_unreachable("Invalid operand size!");
13092 }
13093
13094 // Get LOAD opcode for the specified data type.
13095 static unsigned getLoadOpcode(EVT VT) {
13096   switch (VT.getSimpleVT().SimpleTy) {
13097   case MVT::i8:  return X86::MOV8rm;
13098   case MVT::i16: return X86::MOV16rm;
13099   case MVT::i32: return X86::MOV32rm;
13100   case MVT::i64: return X86::MOV64rm;
13101   default:
13102     break;
13103   }
13104   llvm_unreachable("Invalid operand size!");
13105 }
13106
13107 // Get opcode of the non-atomic one from the specified atomic instruction.
13108 static unsigned getNonAtomicOpcode(unsigned Opc) {
13109   switch (Opc) {
13110   case X86::ATOMAND8:  return X86::AND8rr;
13111   case X86::ATOMAND16: return X86::AND16rr;
13112   case X86::ATOMAND32: return X86::AND32rr;
13113   case X86::ATOMAND64: return X86::AND64rr;
13114   case X86::ATOMOR8:   return X86::OR8rr;
13115   case X86::ATOMOR16:  return X86::OR16rr;
13116   case X86::ATOMOR32:  return X86::OR32rr;
13117   case X86::ATOMOR64:  return X86::OR64rr;
13118   case X86::ATOMXOR8:  return X86::XOR8rr;
13119   case X86::ATOMXOR16: return X86::XOR16rr;
13120   case X86::ATOMXOR32: return X86::XOR32rr;
13121   case X86::ATOMXOR64: return X86::XOR64rr;
13122   }
13123   llvm_unreachable("Unhandled atomic-load-op opcode!");
13124 }
13125
13126 // Get opcode of the non-atomic one from the specified atomic instruction with
13127 // extra opcode.
13128 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13129                                                unsigned &ExtraOpc) {
13130   switch (Opc) {
13131   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13132   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13133   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13134   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13135   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13136   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13137   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13138   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13139   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13140   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13141   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13142   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13143   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13144   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13145   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13146   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13147   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13148   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13149   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13150   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13151   }
13152   llvm_unreachable("Unhandled atomic-load-op opcode!");
13153 }
13154
13155 // Get opcode of the non-atomic one from the specified atomic instruction for
13156 // 64-bit data type on 32-bit target.
13157 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13158   switch (Opc) {
13159   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13160   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13161   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13162   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13163   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13164   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13165   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13166   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13167   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13168   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13169   }
13170   llvm_unreachable("Unhandled atomic-load-op opcode!");
13171 }
13172
13173 // Get opcode of the non-atomic one from the specified atomic instruction for
13174 // 64-bit data type on 32-bit target with extra opcode.
13175 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13176                                                    unsigned &HiOpc,
13177                                                    unsigned &ExtraOpc) {
13178   switch (Opc) {
13179   case X86::ATOMNAND6432:
13180     ExtraOpc = X86::NOT32r;
13181     HiOpc = X86::AND32rr;
13182     return X86::AND32rr;
13183   }
13184   llvm_unreachable("Unhandled atomic-load-op opcode!");
13185 }
13186
13187 // Get pseudo CMOV opcode from the specified data type.
13188 static unsigned getPseudoCMOVOpc(EVT VT) {
13189   switch (VT.getSimpleVT().SimpleTy) {
13190   case MVT::i8:  return X86::CMOV_GR8;
13191   case MVT::i16: return X86::CMOV_GR16;
13192   case MVT::i32: return X86::CMOV_GR32;
13193   default:
13194     break;
13195   }
13196   llvm_unreachable("Unknown CMOV opcode!");
13197 }
13198
13199 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13200 // They will be translated into a spin-loop or compare-exchange loop from
13201 //
13202 //    ...
13203 //    dst = atomic-fetch-op MI.addr, MI.val
13204 //    ...
13205 //
13206 // to
13207 //
13208 //    ...
13209 //    t1 = LOAD MI.addr
13210 // loop:
13211 //    t4 = phi(t1, t3 / loop)
13212 //    t2 = OP MI.val, t4
13213 //    EAX = t4
13214 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13215 //    t3 = EAX
13216 //    JNE loop
13217 // sink:
13218 //    dst = t3
13219 //    ...
13220 MachineBasicBlock *
13221 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13222                                        MachineBasicBlock *MBB) const {
13223   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13224   DebugLoc DL = MI->getDebugLoc();
13225
13226   MachineFunction *MF = MBB->getParent();
13227   MachineRegisterInfo &MRI = MF->getRegInfo();
13228
13229   const BasicBlock *BB = MBB->getBasicBlock();
13230   MachineFunction::iterator I = MBB;
13231   ++I;
13232
13233   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13234          "Unexpected number of operands");
13235
13236   assert(MI->hasOneMemOperand() &&
13237          "Expected atomic-load-op to have one memoperand");
13238
13239   // Memory Reference
13240   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13241   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13242
13243   unsigned DstReg, SrcReg;
13244   unsigned MemOpndSlot;
13245
13246   unsigned CurOp = 0;
13247
13248   DstReg = MI->getOperand(CurOp++).getReg();
13249   MemOpndSlot = CurOp;
13250   CurOp += X86::AddrNumOperands;
13251   SrcReg = MI->getOperand(CurOp++).getReg();
13252
13253   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13254   MVT::SimpleValueType VT = *RC->vt_begin();
13255   unsigned t1 = MRI.createVirtualRegister(RC);
13256   unsigned t2 = MRI.createVirtualRegister(RC);
13257   unsigned t3 = MRI.createVirtualRegister(RC);
13258   unsigned t4 = MRI.createVirtualRegister(RC);
13259   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13260
13261   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13262   unsigned LOADOpc = getLoadOpcode(VT);
13263
13264   // For the atomic load-arith operator, we generate
13265   //
13266   //  thisMBB:
13267   //    t1 = LOAD [MI.addr]
13268   //  mainMBB:
13269   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13270   //    t1 = OP MI.val, EAX
13271   //    EAX = t4
13272   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13273   //    t3 = EAX
13274   //    JNE mainMBB
13275   //  sinkMBB:
13276   //    dst = t3
13277
13278   MachineBasicBlock *thisMBB = MBB;
13279   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13280   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13281   MF->insert(I, mainMBB);
13282   MF->insert(I, sinkMBB);
13283
13284   MachineInstrBuilder MIB;
13285
13286   // Transfer the remainder of BB and its successor edges to sinkMBB.
13287   sinkMBB->splice(sinkMBB->begin(), MBB,
13288                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13289   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13290
13291   // thisMBB:
13292   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13293   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13294     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13295     if (NewMO.isReg())
13296       NewMO.setIsKill(false);
13297     MIB.addOperand(NewMO);
13298   }
13299   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13300     unsigned flags = (*MMOI)->getFlags();
13301     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13302     MachineMemOperand *MMO =
13303       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13304                                (*MMOI)->getSize(),
13305                                (*MMOI)->getBaseAlignment(),
13306                                (*MMOI)->getTBAAInfo(),
13307                                (*MMOI)->getRanges());
13308     MIB.addMemOperand(MMO);
13309   }
13310
13311   thisMBB->addSuccessor(mainMBB);
13312
13313   // mainMBB:
13314   MachineBasicBlock *origMainMBB = mainMBB;
13315
13316   // Add a PHI.
13317   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13318                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13319
13320   unsigned Opc = MI->getOpcode();
13321   switch (Opc) {
13322   default:
13323     llvm_unreachable("Unhandled atomic-load-op opcode!");
13324   case X86::ATOMAND8:
13325   case X86::ATOMAND16:
13326   case X86::ATOMAND32:
13327   case X86::ATOMAND64:
13328   case X86::ATOMOR8:
13329   case X86::ATOMOR16:
13330   case X86::ATOMOR32:
13331   case X86::ATOMOR64:
13332   case X86::ATOMXOR8:
13333   case X86::ATOMXOR16:
13334   case X86::ATOMXOR32:
13335   case X86::ATOMXOR64: {
13336     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13337     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13338       .addReg(t4);
13339     break;
13340   }
13341   case X86::ATOMNAND8:
13342   case X86::ATOMNAND16:
13343   case X86::ATOMNAND32:
13344   case X86::ATOMNAND64: {
13345     unsigned Tmp = MRI.createVirtualRegister(RC);
13346     unsigned NOTOpc;
13347     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13348     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13349       .addReg(t4);
13350     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13351     break;
13352   }
13353   case X86::ATOMMAX8:
13354   case X86::ATOMMAX16:
13355   case X86::ATOMMAX32:
13356   case X86::ATOMMAX64:
13357   case X86::ATOMMIN8:
13358   case X86::ATOMMIN16:
13359   case X86::ATOMMIN32:
13360   case X86::ATOMMIN64:
13361   case X86::ATOMUMAX8:
13362   case X86::ATOMUMAX16:
13363   case X86::ATOMUMAX32:
13364   case X86::ATOMUMAX64:
13365   case X86::ATOMUMIN8:
13366   case X86::ATOMUMIN16:
13367   case X86::ATOMUMIN32:
13368   case X86::ATOMUMIN64: {
13369     unsigned CMPOpc;
13370     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13371
13372     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13373       .addReg(SrcReg)
13374       .addReg(t4);
13375
13376     if (Subtarget->hasCMov()) {
13377       if (VT != MVT::i8) {
13378         // Native support
13379         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13380           .addReg(SrcReg)
13381           .addReg(t4);
13382       } else {
13383         // Promote i8 to i32 to use CMOV32
13384         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13385         const TargetRegisterClass *RC32 =
13386           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13387         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13388         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13389         unsigned Tmp = MRI.createVirtualRegister(RC32);
13390
13391         unsigned Undef = MRI.createVirtualRegister(RC32);
13392         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13393
13394         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13395           .addReg(Undef)
13396           .addReg(SrcReg)
13397           .addImm(X86::sub_8bit);
13398         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13399           .addReg(Undef)
13400           .addReg(t4)
13401           .addImm(X86::sub_8bit);
13402
13403         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13404           .addReg(SrcReg32)
13405           .addReg(AccReg32);
13406
13407         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13408           .addReg(Tmp, 0, X86::sub_8bit);
13409       }
13410     } else {
13411       // Use pseudo select and lower them.
13412       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13413              "Invalid atomic-load-op transformation!");
13414       unsigned SelOpc = getPseudoCMOVOpc(VT);
13415       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13416       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13417       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13418               .addReg(SrcReg).addReg(t4)
13419               .addImm(CC);
13420       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13421       // Replace the original PHI node as mainMBB is changed after CMOV
13422       // lowering.
13423       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13424         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13425       Phi->eraseFromParent();
13426     }
13427     break;
13428   }
13429   }
13430
13431   // Copy PhyReg back from virtual register.
13432   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13433     .addReg(t4);
13434
13435   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13436   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13437     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13438     if (NewMO.isReg())
13439       NewMO.setIsKill(false);
13440     MIB.addOperand(NewMO);
13441   }
13442   MIB.addReg(t2);
13443   MIB.setMemRefs(MMOBegin, MMOEnd);
13444
13445   // Copy PhyReg back to virtual register.
13446   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13447     .addReg(PhyReg);
13448
13449   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13450
13451   mainMBB->addSuccessor(origMainMBB);
13452   mainMBB->addSuccessor(sinkMBB);
13453
13454   // sinkMBB:
13455   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13456           TII->get(TargetOpcode::COPY), DstReg)
13457     .addReg(t3);
13458
13459   MI->eraseFromParent();
13460   return sinkMBB;
13461 }
13462
13463 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13464 // instructions. They will be translated into a spin-loop or compare-exchange
13465 // loop from
13466 //
13467 //    ...
13468 //    dst = atomic-fetch-op MI.addr, MI.val
13469 //    ...
13470 //
13471 // to
13472 //
13473 //    ...
13474 //    t1L = LOAD [MI.addr + 0]
13475 //    t1H = LOAD [MI.addr + 4]
13476 // loop:
13477 //    t4L = phi(t1L, t3L / loop)
13478 //    t4H = phi(t1H, t3H / loop)
13479 //    t2L = OP MI.val.lo, t4L
13480 //    t2H = OP MI.val.hi, t4H
13481 //    EAX = t4L
13482 //    EDX = t4H
13483 //    EBX = t2L
13484 //    ECX = t2H
13485 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13486 //    t3L = EAX
13487 //    t3H = EDX
13488 //    JNE loop
13489 // sink:
13490 //    dstL = t3L
13491 //    dstH = t3H
13492 //    ...
13493 MachineBasicBlock *
13494 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13495                                            MachineBasicBlock *MBB) const {
13496   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13497   DebugLoc DL = MI->getDebugLoc();
13498
13499   MachineFunction *MF = MBB->getParent();
13500   MachineRegisterInfo &MRI = MF->getRegInfo();
13501
13502   const BasicBlock *BB = MBB->getBasicBlock();
13503   MachineFunction::iterator I = MBB;
13504   ++I;
13505
13506   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13507          "Unexpected number of operands");
13508
13509   assert(MI->hasOneMemOperand() &&
13510          "Expected atomic-load-op32 to have one memoperand");
13511
13512   // Memory Reference
13513   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13514   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13515
13516   unsigned DstLoReg, DstHiReg;
13517   unsigned SrcLoReg, SrcHiReg;
13518   unsigned MemOpndSlot;
13519
13520   unsigned CurOp = 0;
13521
13522   DstLoReg = MI->getOperand(CurOp++).getReg();
13523   DstHiReg = MI->getOperand(CurOp++).getReg();
13524   MemOpndSlot = CurOp;
13525   CurOp += X86::AddrNumOperands;
13526   SrcLoReg = MI->getOperand(CurOp++).getReg();
13527   SrcHiReg = MI->getOperand(CurOp++).getReg();
13528
13529   const TargetRegisterClass *RC = &X86::GR32RegClass;
13530   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13531
13532   unsigned t1L = MRI.createVirtualRegister(RC);
13533   unsigned t1H = MRI.createVirtualRegister(RC);
13534   unsigned t2L = MRI.createVirtualRegister(RC);
13535   unsigned t2H = MRI.createVirtualRegister(RC);
13536   unsigned t3L = MRI.createVirtualRegister(RC);
13537   unsigned t3H = MRI.createVirtualRegister(RC);
13538   unsigned t4L = MRI.createVirtualRegister(RC);
13539   unsigned t4H = MRI.createVirtualRegister(RC);
13540
13541   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13542   unsigned LOADOpc = X86::MOV32rm;
13543
13544   // For the atomic load-arith operator, we generate
13545   //
13546   //  thisMBB:
13547   //    t1L = LOAD [MI.addr + 0]
13548   //    t1H = LOAD [MI.addr + 4]
13549   //  mainMBB:
13550   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13551   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13552   //    t2L = OP MI.val.lo, t4L
13553   //    t2H = OP MI.val.hi, t4H
13554   //    EBX = t2L
13555   //    ECX = t2H
13556   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13557   //    t3L = EAX
13558   //    t3H = EDX
13559   //    JNE loop
13560   //  sinkMBB:
13561   //    dstL = t3L
13562   //    dstH = t3H
13563
13564   MachineBasicBlock *thisMBB = MBB;
13565   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13566   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13567   MF->insert(I, mainMBB);
13568   MF->insert(I, sinkMBB);
13569
13570   MachineInstrBuilder MIB;
13571
13572   // Transfer the remainder of BB and its successor edges to sinkMBB.
13573   sinkMBB->splice(sinkMBB->begin(), MBB,
13574                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13575   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13576
13577   // thisMBB:
13578   // Lo
13579   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13580   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13581     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13582     if (NewMO.isReg())
13583       NewMO.setIsKill(false);
13584     MIB.addOperand(NewMO);
13585   }
13586   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13587     unsigned flags = (*MMOI)->getFlags();
13588     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13589     MachineMemOperand *MMO =
13590       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13591                                (*MMOI)->getSize(),
13592                                (*MMOI)->getBaseAlignment(),
13593                                (*MMOI)->getTBAAInfo(),
13594                                (*MMOI)->getRanges());
13595     MIB.addMemOperand(MMO);
13596   };
13597   MachineInstr *LowMI = MIB;
13598
13599   // Hi
13600   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13601   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13602     if (i == X86::AddrDisp) {
13603       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13604     } else {
13605       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13606       if (NewMO.isReg())
13607         NewMO.setIsKill(false);
13608       MIB.addOperand(NewMO);
13609     }
13610   }
13611   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13612
13613   thisMBB->addSuccessor(mainMBB);
13614
13615   // mainMBB:
13616   MachineBasicBlock *origMainMBB = mainMBB;
13617
13618   // Add PHIs.
13619   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13620                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13621   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13622                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13623
13624   unsigned Opc = MI->getOpcode();
13625   switch (Opc) {
13626   default:
13627     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13628   case X86::ATOMAND6432:
13629   case X86::ATOMOR6432:
13630   case X86::ATOMXOR6432:
13631   case X86::ATOMADD6432:
13632   case X86::ATOMSUB6432: {
13633     unsigned HiOpc;
13634     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13635     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13636       .addReg(SrcLoReg);
13637     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13638       .addReg(SrcHiReg);
13639     break;
13640   }
13641   case X86::ATOMNAND6432: {
13642     unsigned HiOpc, NOTOpc;
13643     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13644     unsigned TmpL = MRI.createVirtualRegister(RC);
13645     unsigned TmpH = MRI.createVirtualRegister(RC);
13646     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13647       .addReg(t4L);
13648     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13649       .addReg(t4H);
13650     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13651     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13652     break;
13653   }
13654   case X86::ATOMMAX6432:
13655   case X86::ATOMMIN6432:
13656   case X86::ATOMUMAX6432:
13657   case X86::ATOMUMIN6432: {
13658     unsigned HiOpc;
13659     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13660     unsigned cL = MRI.createVirtualRegister(RC8);
13661     unsigned cH = MRI.createVirtualRegister(RC8);
13662     unsigned cL32 = MRI.createVirtualRegister(RC);
13663     unsigned cH32 = MRI.createVirtualRegister(RC);
13664     unsigned cc = MRI.createVirtualRegister(RC);
13665     // cl := cmp src_lo, lo
13666     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13667       .addReg(SrcLoReg).addReg(t4L);
13668     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13669     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13670     // ch := cmp src_hi, hi
13671     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13672       .addReg(SrcHiReg).addReg(t4H);
13673     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13674     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13675     // cc := if (src_hi == hi) ? cl : ch;
13676     if (Subtarget->hasCMov()) {
13677       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13678         .addReg(cH32).addReg(cL32);
13679     } else {
13680       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13681               .addReg(cH32).addReg(cL32)
13682               .addImm(X86::COND_E);
13683       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13684     }
13685     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13686     if (Subtarget->hasCMov()) {
13687       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13688         .addReg(SrcLoReg).addReg(t4L);
13689       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13690         .addReg(SrcHiReg).addReg(t4H);
13691     } else {
13692       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13693               .addReg(SrcLoReg).addReg(t4L)
13694               .addImm(X86::COND_NE);
13695       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13696       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13697       // 2nd CMOV lowering.
13698       mainMBB->addLiveIn(X86::EFLAGS);
13699       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13700               .addReg(SrcHiReg).addReg(t4H)
13701               .addImm(X86::COND_NE);
13702       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13703       // Replace the original PHI node as mainMBB is changed after CMOV
13704       // lowering.
13705       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13706         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13707       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13708         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13709       PhiL->eraseFromParent();
13710       PhiH->eraseFromParent();
13711     }
13712     break;
13713   }
13714   case X86::ATOMSWAP6432: {
13715     unsigned HiOpc;
13716     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13717     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13718     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13719     break;
13720   }
13721   }
13722
13723   // Copy EDX:EAX back from HiReg:LoReg
13724   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13725   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13726   // Copy ECX:EBX from t1H:t1L
13727   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13728   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13729
13730   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13731   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13732     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13733     if (NewMO.isReg())
13734       NewMO.setIsKill(false);
13735     MIB.addOperand(NewMO);
13736   }
13737   MIB.setMemRefs(MMOBegin, MMOEnd);
13738
13739   // Copy EDX:EAX back to t3H:t3L
13740   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13741   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13742
13743   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13744
13745   mainMBB->addSuccessor(origMainMBB);
13746   mainMBB->addSuccessor(sinkMBB);
13747
13748   // sinkMBB:
13749   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13750           TII->get(TargetOpcode::COPY), DstLoReg)
13751     .addReg(t3L);
13752   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13753           TII->get(TargetOpcode::COPY), DstHiReg)
13754     .addReg(t3H);
13755
13756   MI->eraseFromParent();
13757   return sinkMBB;
13758 }
13759
13760 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13761 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13762 // in the .td file.
13763 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13764                                        const TargetInstrInfo *TII) {
13765   unsigned Opc;
13766   switch (MI->getOpcode()) {
13767   default: llvm_unreachable("illegal opcode!");
13768   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13769   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13770   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13771   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13772   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13773   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13774   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13775   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13776   }
13777
13778   DebugLoc dl = MI->getDebugLoc();
13779   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13780
13781   unsigned NumArgs = MI->getNumOperands();
13782   for (unsigned i = 1; i < NumArgs; ++i) {
13783     MachineOperand &Op = MI->getOperand(i);
13784     if (!(Op.isReg() && Op.isImplicit()))
13785       MIB.addOperand(Op);
13786   }
13787   if (MI->hasOneMemOperand())
13788     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13789
13790   BuildMI(*BB, MI, dl,
13791     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13792     .addReg(X86::XMM0);
13793
13794   MI->eraseFromParent();
13795   return BB;
13796 }
13797
13798 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13799 // defs in an instruction pattern
13800 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13801                                        const TargetInstrInfo *TII) {
13802   unsigned Opc;
13803   switch (MI->getOpcode()) {
13804   default: llvm_unreachable("illegal opcode!");
13805   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13806   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13807   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13808   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13809   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13810   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13811   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13812   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13813   }
13814
13815   DebugLoc dl = MI->getDebugLoc();
13816   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13817
13818   unsigned NumArgs = MI->getNumOperands(); // remove the results
13819   for (unsigned i = 1; i < NumArgs; ++i) {
13820     MachineOperand &Op = MI->getOperand(i);
13821     if (!(Op.isReg() && Op.isImplicit()))
13822       MIB.addOperand(Op);
13823   }
13824   if (MI->hasOneMemOperand())
13825     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13826
13827   BuildMI(*BB, MI, dl,
13828     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13829     .addReg(X86::ECX);
13830
13831   MI->eraseFromParent();
13832   return BB;
13833 }
13834
13835 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13836                                        const TargetInstrInfo *TII,
13837                                        const X86Subtarget* Subtarget) {
13838   DebugLoc dl = MI->getDebugLoc();
13839
13840   // Address into RAX/EAX, other two args into ECX, EDX.
13841   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13842   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13843   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13844   for (int i = 0; i < X86::AddrNumOperands; ++i)
13845     MIB.addOperand(MI->getOperand(i));
13846
13847   unsigned ValOps = X86::AddrNumOperands;
13848   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13849     .addReg(MI->getOperand(ValOps).getReg());
13850   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13851     .addReg(MI->getOperand(ValOps+1).getReg());
13852
13853   // The instruction doesn't actually take any operands though.
13854   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13855
13856   MI->eraseFromParent(); // The pseudo is gone now.
13857   return BB;
13858 }
13859
13860 MachineBasicBlock *
13861 X86TargetLowering::EmitVAARG64WithCustomInserter(
13862                    MachineInstr *MI,
13863                    MachineBasicBlock *MBB) const {
13864   // Emit va_arg instruction on X86-64.
13865
13866   // Operands to this pseudo-instruction:
13867   // 0  ) Output        : destination address (reg)
13868   // 1-5) Input         : va_list address (addr, i64mem)
13869   // 6  ) ArgSize       : Size (in bytes) of vararg type
13870   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13871   // 8  ) Align         : Alignment of type
13872   // 9  ) EFLAGS (implicit-def)
13873
13874   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13875   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13876
13877   unsigned DestReg = MI->getOperand(0).getReg();
13878   MachineOperand &Base = MI->getOperand(1);
13879   MachineOperand &Scale = MI->getOperand(2);
13880   MachineOperand &Index = MI->getOperand(3);
13881   MachineOperand &Disp = MI->getOperand(4);
13882   MachineOperand &Segment = MI->getOperand(5);
13883   unsigned ArgSize = MI->getOperand(6).getImm();
13884   unsigned ArgMode = MI->getOperand(7).getImm();
13885   unsigned Align = MI->getOperand(8).getImm();
13886
13887   // Memory Reference
13888   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13889   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13890   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13891
13892   // Machine Information
13893   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13894   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13895   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13896   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13897   DebugLoc DL = MI->getDebugLoc();
13898
13899   // struct va_list {
13900   //   i32   gp_offset
13901   //   i32   fp_offset
13902   //   i64   overflow_area (address)
13903   //   i64   reg_save_area (address)
13904   // }
13905   // sizeof(va_list) = 24
13906   // alignment(va_list) = 8
13907
13908   unsigned TotalNumIntRegs = 6;
13909   unsigned TotalNumXMMRegs = 8;
13910   bool UseGPOffset = (ArgMode == 1);
13911   bool UseFPOffset = (ArgMode == 2);
13912   unsigned MaxOffset = TotalNumIntRegs * 8 +
13913                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13914
13915   /* Align ArgSize to a multiple of 8 */
13916   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13917   bool NeedsAlign = (Align > 8);
13918
13919   MachineBasicBlock *thisMBB = MBB;
13920   MachineBasicBlock *overflowMBB;
13921   MachineBasicBlock *offsetMBB;
13922   MachineBasicBlock *endMBB;
13923
13924   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13925   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13926   unsigned OffsetReg = 0;
13927
13928   if (!UseGPOffset && !UseFPOffset) {
13929     // If we only pull from the overflow region, we don't create a branch.
13930     // We don't need to alter control flow.
13931     OffsetDestReg = 0; // unused
13932     OverflowDestReg = DestReg;
13933
13934     offsetMBB = NULL;
13935     overflowMBB = thisMBB;
13936     endMBB = thisMBB;
13937   } else {
13938     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13939     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13940     // If not, pull from overflow_area. (branch to overflowMBB)
13941     //
13942     //       thisMBB
13943     //         |     .
13944     //         |        .
13945     //     offsetMBB   overflowMBB
13946     //         |        .
13947     //         |     .
13948     //        endMBB
13949
13950     // Registers for the PHI in endMBB
13951     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13952     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13953
13954     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13955     MachineFunction *MF = MBB->getParent();
13956     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13957     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13958     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13959
13960     MachineFunction::iterator MBBIter = MBB;
13961     ++MBBIter;
13962
13963     // Insert the new basic blocks
13964     MF->insert(MBBIter, offsetMBB);
13965     MF->insert(MBBIter, overflowMBB);
13966     MF->insert(MBBIter, endMBB);
13967
13968     // Transfer the remainder of MBB and its successor edges to endMBB.
13969     endMBB->splice(endMBB->begin(), thisMBB,
13970                     llvm::next(MachineBasicBlock::iterator(MI)),
13971                     thisMBB->end());
13972     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13973
13974     // Make offsetMBB and overflowMBB successors of thisMBB
13975     thisMBB->addSuccessor(offsetMBB);
13976     thisMBB->addSuccessor(overflowMBB);
13977
13978     // endMBB is a successor of both offsetMBB and overflowMBB
13979     offsetMBB->addSuccessor(endMBB);
13980     overflowMBB->addSuccessor(endMBB);
13981
13982     // Load the offset value into a register
13983     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13984     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13985       .addOperand(Base)
13986       .addOperand(Scale)
13987       .addOperand(Index)
13988       .addDisp(Disp, UseFPOffset ? 4 : 0)
13989       .addOperand(Segment)
13990       .setMemRefs(MMOBegin, MMOEnd);
13991
13992     // Check if there is enough room left to pull this argument.
13993     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13994       .addReg(OffsetReg)
13995       .addImm(MaxOffset + 8 - ArgSizeA8);
13996
13997     // Branch to "overflowMBB" if offset >= max
13998     // Fall through to "offsetMBB" otherwise
13999     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
14000       .addMBB(overflowMBB);
14001   }
14002
14003   // In offsetMBB, emit code to use the reg_save_area.
14004   if (offsetMBB) {
14005     assert(OffsetReg != 0);
14006
14007     // Read the reg_save_area address.
14008     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14009     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14010       .addOperand(Base)
14011       .addOperand(Scale)
14012       .addOperand(Index)
14013       .addDisp(Disp, 16)
14014       .addOperand(Segment)
14015       .setMemRefs(MMOBegin, MMOEnd);
14016
14017     // Zero-extend the offset
14018     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14019       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14020         .addImm(0)
14021         .addReg(OffsetReg)
14022         .addImm(X86::sub_32bit);
14023
14024     // Add the offset to the reg_save_area to get the final address.
14025     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14026       .addReg(OffsetReg64)
14027       .addReg(RegSaveReg);
14028
14029     // Compute the offset for the next argument
14030     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14031     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14032       .addReg(OffsetReg)
14033       .addImm(UseFPOffset ? 16 : 8);
14034
14035     // Store it back into the va_list.
14036     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14037       .addOperand(Base)
14038       .addOperand(Scale)
14039       .addOperand(Index)
14040       .addDisp(Disp, UseFPOffset ? 4 : 0)
14041       .addOperand(Segment)
14042       .addReg(NextOffsetReg)
14043       .setMemRefs(MMOBegin, MMOEnd);
14044
14045     // Jump to endMBB
14046     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14047       .addMBB(endMBB);
14048   }
14049
14050   //
14051   // Emit code to use overflow area
14052   //
14053
14054   // Load the overflow_area address into a register.
14055   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14056   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14057     .addOperand(Base)
14058     .addOperand(Scale)
14059     .addOperand(Index)
14060     .addDisp(Disp, 8)
14061     .addOperand(Segment)
14062     .setMemRefs(MMOBegin, MMOEnd);
14063
14064   // If we need to align it, do so. Otherwise, just copy the address
14065   // to OverflowDestReg.
14066   if (NeedsAlign) {
14067     // Align the overflow address
14068     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14069     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14070
14071     // aligned_addr = (addr + (align-1)) & ~(align-1)
14072     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14073       .addReg(OverflowAddrReg)
14074       .addImm(Align-1);
14075
14076     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14077       .addReg(TmpReg)
14078       .addImm(~(uint64_t)(Align-1));
14079   } else {
14080     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14081       .addReg(OverflowAddrReg);
14082   }
14083
14084   // Compute the next overflow address after this argument.
14085   // (the overflow address should be kept 8-byte aligned)
14086   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14087   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14088     .addReg(OverflowDestReg)
14089     .addImm(ArgSizeA8);
14090
14091   // Store the new overflow address.
14092   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14093     .addOperand(Base)
14094     .addOperand(Scale)
14095     .addOperand(Index)
14096     .addDisp(Disp, 8)
14097     .addOperand(Segment)
14098     .addReg(NextAddrReg)
14099     .setMemRefs(MMOBegin, MMOEnd);
14100
14101   // If we branched, emit the PHI to the front of endMBB.
14102   if (offsetMBB) {
14103     BuildMI(*endMBB, endMBB->begin(), DL,
14104             TII->get(X86::PHI), DestReg)
14105       .addReg(OffsetDestReg).addMBB(offsetMBB)
14106       .addReg(OverflowDestReg).addMBB(overflowMBB);
14107   }
14108
14109   // Erase the pseudo instruction
14110   MI->eraseFromParent();
14111
14112   return endMBB;
14113 }
14114
14115 MachineBasicBlock *
14116 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14117                                                  MachineInstr *MI,
14118                                                  MachineBasicBlock *MBB) const {
14119   // Emit code to save XMM registers to the stack. The ABI says that the
14120   // number of registers to save is given in %al, so it's theoretically
14121   // possible to do an indirect jump trick to avoid saving all of them,
14122   // however this code takes a simpler approach and just executes all
14123   // of the stores if %al is non-zero. It's less code, and it's probably
14124   // easier on the hardware branch predictor, and stores aren't all that
14125   // expensive anyway.
14126
14127   // Create the new basic blocks. One block contains all the XMM stores,
14128   // and one block is the final destination regardless of whether any
14129   // stores were performed.
14130   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14131   MachineFunction *F = MBB->getParent();
14132   MachineFunction::iterator MBBIter = MBB;
14133   ++MBBIter;
14134   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14135   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14136   F->insert(MBBIter, XMMSaveMBB);
14137   F->insert(MBBIter, EndMBB);
14138
14139   // Transfer the remainder of MBB and its successor edges to EndMBB.
14140   EndMBB->splice(EndMBB->begin(), MBB,
14141                  llvm::next(MachineBasicBlock::iterator(MI)),
14142                  MBB->end());
14143   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14144
14145   // The original block will now fall through to the XMM save block.
14146   MBB->addSuccessor(XMMSaveMBB);
14147   // The XMMSaveMBB will fall through to the end block.
14148   XMMSaveMBB->addSuccessor(EndMBB);
14149
14150   // Now add the instructions.
14151   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14152   DebugLoc DL = MI->getDebugLoc();
14153
14154   unsigned CountReg = MI->getOperand(0).getReg();
14155   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14156   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14157
14158   if (!Subtarget->isTargetWin64()) {
14159     // If %al is 0, branch around the XMM save block.
14160     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14161     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14162     MBB->addSuccessor(EndMBB);
14163   }
14164
14165   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14166   // In the XMM save block, save all the XMM argument registers.
14167   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14168     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14169     MachineMemOperand *MMO =
14170       F->getMachineMemOperand(
14171           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14172         MachineMemOperand::MOStore,
14173         /*Size=*/16, /*Align=*/16);
14174     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14175       .addFrameIndex(RegSaveFrameIndex)
14176       .addImm(/*Scale=*/1)
14177       .addReg(/*IndexReg=*/0)
14178       .addImm(/*Disp=*/Offset)
14179       .addReg(/*Segment=*/0)
14180       .addReg(MI->getOperand(i).getReg())
14181       .addMemOperand(MMO);
14182   }
14183
14184   MI->eraseFromParent();   // The pseudo instruction is gone now.
14185
14186   return EndMBB;
14187 }
14188
14189 // The EFLAGS operand of SelectItr might be missing a kill marker
14190 // because there were multiple uses of EFLAGS, and ISel didn't know
14191 // which to mark. Figure out whether SelectItr should have had a
14192 // kill marker, and set it if it should. Returns the correct kill
14193 // marker value.
14194 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14195                                      MachineBasicBlock* BB,
14196                                      const TargetRegisterInfo* TRI) {
14197   // Scan forward through BB for a use/def of EFLAGS.
14198   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14199   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14200     const MachineInstr& mi = *miI;
14201     if (mi.readsRegister(X86::EFLAGS))
14202       return false;
14203     if (mi.definesRegister(X86::EFLAGS))
14204       break; // Should have kill-flag - update below.
14205   }
14206
14207   // If we hit the end of the block, check whether EFLAGS is live into a
14208   // successor.
14209   if (miI == BB->end()) {
14210     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14211                                           sEnd = BB->succ_end();
14212          sItr != sEnd; ++sItr) {
14213       MachineBasicBlock* succ = *sItr;
14214       if (succ->isLiveIn(X86::EFLAGS))
14215         return false;
14216     }
14217   }
14218
14219   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14220   // out. SelectMI should have a kill flag on EFLAGS.
14221   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14222   return true;
14223 }
14224
14225 MachineBasicBlock *
14226 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14227                                      MachineBasicBlock *BB) const {
14228   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14229   DebugLoc DL = MI->getDebugLoc();
14230
14231   // To "insert" a SELECT_CC instruction, we actually have to insert the
14232   // diamond control-flow pattern.  The incoming instruction knows the
14233   // destination vreg to set, the condition code register to branch on, the
14234   // true/false values to select between, and a branch opcode to use.
14235   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14236   MachineFunction::iterator It = BB;
14237   ++It;
14238
14239   //  thisMBB:
14240   //  ...
14241   //   TrueVal = ...
14242   //   cmpTY ccX, r1, r2
14243   //   bCC copy1MBB
14244   //   fallthrough --> copy0MBB
14245   MachineBasicBlock *thisMBB = BB;
14246   MachineFunction *F = BB->getParent();
14247   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14248   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14249   F->insert(It, copy0MBB);
14250   F->insert(It, sinkMBB);
14251
14252   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14253   // live into the sink and copy blocks.
14254   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14255   if (!MI->killsRegister(X86::EFLAGS) &&
14256       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14257     copy0MBB->addLiveIn(X86::EFLAGS);
14258     sinkMBB->addLiveIn(X86::EFLAGS);
14259   }
14260
14261   // Transfer the remainder of BB and its successor edges to sinkMBB.
14262   sinkMBB->splice(sinkMBB->begin(), BB,
14263                   llvm::next(MachineBasicBlock::iterator(MI)),
14264                   BB->end());
14265   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14266
14267   // Add the true and fallthrough blocks as its successors.
14268   BB->addSuccessor(copy0MBB);
14269   BB->addSuccessor(sinkMBB);
14270
14271   // Create the conditional branch instruction.
14272   unsigned Opc =
14273     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14274   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14275
14276   //  copy0MBB:
14277   //   %FalseValue = ...
14278   //   # fallthrough to sinkMBB
14279   copy0MBB->addSuccessor(sinkMBB);
14280
14281   //  sinkMBB:
14282   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14283   //  ...
14284   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14285           TII->get(X86::PHI), MI->getOperand(0).getReg())
14286     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14287     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14288
14289   MI->eraseFromParent();   // The pseudo instruction is gone now.
14290   return sinkMBB;
14291 }
14292
14293 MachineBasicBlock *
14294 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14295                                         bool Is64Bit) const {
14296   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14297   DebugLoc DL = MI->getDebugLoc();
14298   MachineFunction *MF = BB->getParent();
14299   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14300
14301   assert(getTargetMachine().Options.EnableSegmentedStacks);
14302
14303   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14304   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14305
14306   // BB:
14307   //  ... [Till the alloca]
14308   // If stacklet is not large enough, jump to mallocMBB
14309   //
14310   // bumpMBB:
14311   //  Allocate by subtracting from RSP
14312   //  Jump to continueMBB
14313   //
14314   // mallocMBB:
14315   //  Allocate by call to runtime
14316   //
14317   // continueMBB:
14318   //  ...
14319   //  [rest of original BB]
14320   //
14321
14322   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14323   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14324   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14325
14326   MachineRegisterInfo &MRI = MF->getRegInfo();
14327   const TargetRegisterClass *AddrRegClass =
14328     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14329
14330   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14331     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14332     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14333     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14334     sizeVReg = MI->getOperand(1).getReg(),
14335     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14336
14337   MachineFunction::iterator MBBIter = BB;
14338   ++MBBIter;
14339
14340   MF->insert(MBBIter, bumpMBB);
14341   MF->insert(MBBIter, mallocMBB);
14342   MF->insert(MBBIter, continueMBB);
14343
14344   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14345                       (MachineBasicBlock::iterator(MI)), BB->end());
14346   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14347
14348   // Add code to the main basic block to check if the stack limit has been hit,
14349   // and if so, jump to mallocMBB otherwise to bumpMBB.
14350   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14351   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14352     .addReg(tmpSPVReg).addReg(sizeVReg);
14353   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14354     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14355     .addReg(SPLimitVReg);
14356   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14357
14358   // bumpMBB simply decreases the stack pointer, since we know the current
14359   // stacklet has enough space.
14360   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14361     .addReg(SPLimitVReg);
14362   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14363     .addReg(SPLimitVReg);
14364   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14365
14366   // Calls into a routine in libgcc to allocate more space from the heap.
14367   const uint32_t *RegMask =
14368     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14369   if (Is64Bit) {
14370     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14371       .addReg(sizeVReg);
14372     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14373       .addExternalSymbol("__morestack_allocate_stack_space")
14374       .addRegMask(RegMask)
14375       .addReg(X86::RDI, RegState::Implicit)
14376       .addReg(X86::RAX, RegState::ImplicitDefine);
14377   } else {
14378     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14379       .addImm(12);
14380     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14381     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14382       .addExternalSymbol("__morestack_allocate_stack_space")
14383       .addRegMask(RegMask)
14384       .addReg(X86::EAX, RegState::ImplicitDefine);
14385   }
14386
14387   if (!Is64Bit)
14388     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14389       .addImm(16);
14390
14391   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14392     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14393   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14394
14395   // Set up the CFG correctly.
14396   BB->addSuccessor(bumpMBB);
14397   BB->addSuccessor(mallocMBB);
14398   mallocMBB->addSuccessor(continueMBB);
14399   bumpMBB->addSuccessor(continueMBB);
14400
14401   // Take care of the PHI nodes.
14402   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14403           MI->getOperand(0).getReg())
14404     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14405     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14406
14407   // Delete the original pseudo instruction.
14408   MI->eraseFromParent();
14409
14410   // And we're done.
14411   return continueMBB;
14412 }
14413
14414 MachineBasicBlock *
14415 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14416                                           MachineBasicBlock *BB) const {
14417   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14418   DebugLoc DL = MI->getDebugLoc();
14419
14420   assert(!Subtarget->isTargetEnvMacho());
14421
14422   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14423   // non-trivial part is impdef of ESP.
14424
14425   if (Subtarget->isTargetWin64()) {
14426     if (Subtarget->isTargetCygMing()) {
14427       // ___chkstk(Mingw64):
14428       // Clobbers R10, R11, RAX and EFLAGS.
14429       // Updates RSP.
14430       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14431         .addExternalSymbol("___chkstk")
14432         .addReg(X86::RAX, RegState::Implicit)
14433         .addReg(X86::RSP, RegState::Implicit)
14434         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14435         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14436         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14437     } else {
14438       // __chkstk(MSVCRT): does not update stack pointer.
14439       // Clobbers R10, R11 and EFLAGS.
14440       // FIXME: RAX(allocated size) might be reused and not killed.
14441       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14442         .addExternalSymbol("__chkstk")
14443         .addReg(X86::RAX, RegState::Implicit)
14444         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14445       // RAX has the offset to subtracted from RSP.
14446       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14447         .addReg(X86::RSP)
14448         .addReg(X86::RAX);
14449     }
14450   } else {
14451     const char *StackProbeSymbol =
14452       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14453
14454     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14455       .addExternalSymbol(StackProbeSymbol)
14456       .addReg(X86::EAX, RegState::Implicit)
14457       .addReg(X86::ESP, RegState::Implicit)
14458       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14459       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14460       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14461   }
14462
14463   MI->eraseFromParent();   // The pseudo instruction is gone now.
14464   return BB;
14465 }
14466
14467 MachineBasicBlock *
14468 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14469                                       MachineBasicBlock *BB) const {
14470   // This is pretty easy.  We're taking the value that we received from
14471   // our load from the relocation, sticking it in either RDI (x86-64)
14472   // or EAX and doing an indirect call.  The return value will then
14473   // be in the normal return register.
14474   const X86InstrInfo *TII
14475     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14476   DebugLoc DL = MI->getDebugLoc();
14477   MachineFunction *F = BB->getParent();
14478
14479   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14480   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14481
14482   // Get a register mask for the lowered call.
14483   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14484   // proper register mask.
14485   const uint32_t *RegMask =
14486     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14487   if (Subtarget->is64Bit()) {
14488     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14489                                       TII->get(X86::MOV64rm), X86::RDI)
14490     .addReg(X86::RIP)
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::CALL64m));
14496     addDirectMem(MIB, X86::RDI);
14497     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14498   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14499     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14500                                       TII->get(X86::MOV32rm), X86::EAX)
14501     .addReg(0)
14502     .addImm(0).addReg(0)
14503     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14504                       MI->getOperand(3).getTargetFlags())
14505     .addReg(0);
14506     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14507     addDirectMem(MIB, X86::EAX);
14508     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14509   } else {
14510     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14511                                       TII->get(X86::MOV32rm), X86::EAX)
14512     .addReg(TII->getGlobalBaseReg(F))
14513     .addImm(0).addReg(0)
14514     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14515                       MI->getOperand(3).getTargetFlags())
14516     .addReg(0);
14517     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14518     addDirectMem(MIB, X86::EAX);
14519     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14520   }
14521
14522   MI->eraseFromParent(); // The pseudo instruction is gone now.
14523   return BB;
14524 }
14525
14526 MachineBasicBlock *
14527 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14528                                     MachineBasicBlock *MBB) const {
14529   DebugLoc DL = MI->getDebugLoc();
14530   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14531
14532   MachineFunction *MF = MBB->getParent();
14533   MachineRegisterInfo &MRI = MF->getRegInfo();
14534
14535   const BasicBlock *BB = MBB->getBasicBlock();
14536   MachineFunction::iterator I = MBB;
14537   ++I;
14538
14539   // Memory Reference
14540   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14541   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14542
14543   unsigned DstReg;
14544   unsigned MemOpndSlot = 0;
14545
14546   unsigned CurOp = 0;
14547
14548   DstReg = MI->getOperand(CurOp++).getReg();
14549   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14550   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14551   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14552   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14553
14554   MemOpndSlot = CurOp;
14555
14556   MVT PVT = getPointerTy();
14557   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14558          "Invalid Pointer Size!");
14559
14560   // For v = setjmp(buf), we generate
14561   //
14562   // thisMBB:
14563   //  buf[LabelOffset] = restoreMBB
14564   //  SjLjSetup restoreMBB
14565   //
14566   // mainMBB:
14567   //  v_main = 0
14568   //
14569   // sinkMBB:
14570   //  v = phi(main, restore)
14571   //
14572   // restoreMBB:
14573   //  v_restore = 1
14574
14575   MachineBasicBlock *thisMBB = MBB;
14576   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14577   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14578   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14579   MF->insert(I, mainMBB);
14580   MF->insert(I, sinkMBB);
14581   MF->push_back(restoreMBB);
14582
14583   MachineInstrBuilder MIB;
14584
14585   // Transfer the remainder of BB and its successor edges to sinkMBB.
14586   sinkMBB->splice(sinkMBB->begin(), MBB,
14587                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14588   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14589
14590   // thisMBB:
14591   unsigned PtrStoreOpc = 0;
14592   unsigned LabelReg = 0;
14593   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14594   Reloc::Model RM = getTargetMachine().getRelocationModel();
14595   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14596                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14597
14598   // Prepare IP either in reg or imm.
14599   if (!UseImmLabel) {
14600     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14601     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14602     LabelReg = MRI.createVirtualRegister(PtrRC);
14603     if (Subtarget->is64Bit()) {
14604       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14605               .addReg(X86::RIP)
14606               .addImm(0)
14607               .addReg(0)
14608               .addMBB(restoreMBB)
14609               .addReg(0);
14610     } else {
14611       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14612       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14613               .addReg(XII->getGlobalBaseReg(MF))
14614               .addImm(0)
14615               .addReg(0)
14616               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14617               .addReg(0);
14618     }
14619   } else
14620     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14621   // Store IP
14622   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14623   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14624     if (i == X86::AddrDisp)
14625       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14626     else
14627       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14628   }
14629   if (!UseImmLabel)
14630     MIB.addReg(LabelReg);
14631   else
14632     MIB.addMBB(restoreMBB);
14633   MIB.setMemRefs(MMOBegin, MMOEnd);
14634   // Setup
14635   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14636           .addMBB(restoreMBB);
14637   MIB.addRegMask(RegInfo->getNoPreservedMask());
14638   thisMBB->addSuccessor(mainMBB);
14639   thisMBB->addSuccessor(restoreMBB);
14640
14641   // mainMBB:
14642   //  EAX = 0
14643   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
14644   mainMBB->addSuccessor(sinkMBB);
14645
14646   // sinkMBB:
14647   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14648           TII->get(X86::PHI), DstReg)
14649     .addReg(mainDstReg).addMBB(mainMBB)
14650     .addReg(restoreDstReg).addMBB(restoreMBB);
14651
14652   // restoreMBB:
14653   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
14654   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
14655   restoreMBB->addSuccessor(sinkMBB);
14656
14657   MI->eraseFromParent();
14658   return sinkMBB;
14659 }
14660
14661 MachineBasicBlock *
14662 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
14663                                      MachineBasicBlock *MBB) const {
14664   DebugLoc DL = MI->getDebugLoc();
14665   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14666
14667   MachineFunction *MF = MBB->getParent();
14668   MachineRegisterInfo &MRI = MF->getRegInfo();
14669
14670   // Memory Reference
14671   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14672   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14673
14674   MVT PVT = getPointerTy();
14675   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14676          "Invalid Pointer Size!");
14677
14678   const TargetRegisterClass *RC =
14679     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
14680   unsigned Tmp = MRI.createVirtualRegister(RC);
14681   // Since FP is only updated here but NOT referenced, it's treated as GPR.
14682   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14683   unsigned SP = RegInfo->getStackRegister();
14684
14685   MachineInstrBuilder MIB;
14686
14687   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14688   const int64_t SPOffset = 2 * PVT.getStoreSize();
14689
14690   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14691   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14692
14693   // Reload FP
14694   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14695   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14696     MIB.addOperand(MI->getOperand(i));
14697   MIB.setMemRefs(MMOBegin, MMOEnd);
14698   // Reload IP
14699   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14700   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14701     if (i == X86::AddrDisp)
14702       MIB.addDisp(MI->getOperand(i), LabelOffset);
14703     else
14704       MIB.addOperand(MI->getOperand(i));
14705   }
14706   MIB.setMemRefs(MMOBegin, MMOEnd);
14707   // Reload SP
14708   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14709   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14710     if (i == X86::AddrDisp)
14711       MIB.addDisp(MI->getOperand(i), SPOffset);
14712     else
14713       MIB.addOperand(MI->getOperand(i));
14714   }
14715   MIB.setMemRefs(MMOBegin, MMOEnd);
14716   // Jump
14717   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14718
14719   MI->eraseFromParent();
14720   return MBB;
14721 }
14722
14723 MachineBasicBlock *
14724 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14725                                                MachineBasicBlock *BB) const {
14726   switch (MI->getOpcode()) {
14727   default: llvm_unreachable("Unexpected instr type to insert");
14728   case X86::TAILJMPd64:
14729   case X86::TAILJMPr64:
14730   case X86::TAILJMPm64:
14731     llvm_unreachable("TAILJMP64 would not be touched here.");
14732   case X86::TCRETURNdi64:
14733   case X86::TCRETURNri64:
14734   case X86::TCRETURNmi64:
14735     return BB;
14736   case X86::WIN_ALLOCA:
14737     return EmitLoweredWinAlloca(MI, BB);
14738   case X86::SEG_ALLOCA_32:
14739     return EmitLoweredSegAlloca(MI, BB, false);
14740   case X86::SEG_ALLOCA_64:
14741     return EmitLoweredSegAlloca(MI, BB, true);
14742   case X86::TLSCall_32:
14743   case X86::TLSCall_64:
14744     return EmitLoweredTLSCall(MI, BB);
14745   case X86::CMOV_GR8:
14746   case X86::CMOV_FR32:
14747   case X86::CMOV_FR64:
14748   case X86::CMOV_V4F32:
14749   case X86::CMOV_V2F64:
14750   case X86::CMOV_V2I64:
14751   case X86::CMOV_V8F32:
14752   case X86::CMOV_V4F64:
14753   case X86::CMOV_V4I64:
14754   case X86::CMOV_GR16:
14755   case X86::CMOV_GR32:
14756   case X86::CMOV_RFP32:
14757   case X86::CMOV_RFP64:
14758   case X86::CMOV_RFP80:
14759     return EmitLoweredSelect(MI, BB);
14760
14761   case X86::FP32_TO_INT16_IN_MEM:
14762   case X86::FP32_TO_INT32_IN_MEM:
14763   case X86::FP32_TO_INT64_IN_MEM:
14764   case X86::FP64_TO_INT16_IN_MEM:
14765   case X86::FP64_TO_INT32_IN_MEM:
14766   case X86::FP64_TO_INT64_IN_MEM:
14767   case X86::FP80_TO_INT16_IN_MEM:
14768   case X86::FP80_TO_INT32_IN_MEM:
14769   case X86::FP80_TO_INT64_IN_MEM: {
14770     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14771     DebugLoc DL = MI->getDebugLoc();
14772
14773     // Change the floating point control register to use "round towards zero"
14774     // mode when truncating to an integer value.
14775     MachineFunction *F = BB->getParent();
14776     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14777     addFrameReference(BuildMI(*BB, MI, DL,
14778                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14779
14780     // Load the old value of the high byte of the control word...
14781     unsigned OldCW =
14782       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14783     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14784                       CWFrameIdx);
14785
14786     // Set the high part to be round to zero...
14787     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14788       .addImm(0xC7F);
14789
14790     // Reload the modified control word now...
14791     addFrameReference(BuildMI(*BB, MI, DL,
14792                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14793
14794     // Restore the memory image of control word to original value
14795     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14796       .addReg(OldCW);
14797
14798     // Get the X86 opcode to use.
14799     unsigned Opc;
14800     switch (MI->getOpcode()) {
14801     default: llvm_unreachable("illegal opcode!");
14802     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14803     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14804     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14805     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14806     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14807     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14808     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14809     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14810     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14811     }
14812
14813     X86AddressMode AM;
14814     MachineOperand &Op = MI->getOperand(0);
14815     if (Op.isReg()) {
14816       AM.BaseType = X86AddressMode::RegBase;
14817       AM.Base.Reg = Op.getReg();
14818     } else {
14819       AM.BaseType = X86AddressMode::FrameIndexBase;
14820       AM.Base.FrameIndex = Op.getIndex();
14821     }
14822     Op = MI->getOperand(1);
14823     if (Op.isImm())
14824       AM.Scale = Op.getImm();
14825     Op = MI->getOperand(2);
14826     if (Op.isImm())
14827       AM.IndexReg = Op.getImm();
14828     Op = MI->getOperand(3);
14829     if (Op.isGlobal()) {
14830       AM.GV = Op.getGlobal();
14831     } else {
14832       AM.Disp = Op.getImm();
14833     }
14834     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14835                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14836
14837     // Reload the original control word now.
14838     addFrameReference(BuildMI(*BB, MI, DL,
14839                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14840
14841     MI->eraseFromParent();   // The pseudo instruction is gone now.
14842     return BB;
14843   }
14844     // String/text processing lowering.
14845   case X86::PCMPISTRM128REG:
14846   case X86::VPCMPISTRM128REG:
14847   case X86::PCMPISTRM128MEM:
14848   case X86::VPCMPISTRM128MEM:
14849   case X86::PCMPESTRM128REG:
14850   case X86::VPCMPESTRM128REG:
14851   case X86::PCMPESTRM128MEM:
14852   case X86::VPCMPESTRM128MEM:
14853     assert(Subtarget->hasSSE42() &&
14854            "Target must have SSE4.2 or AVX features enabled");
14855     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14856
14857   // String/text processing lowering.
14858   case X86::PCMPISTRIREG:
14859   case X86::VPCMPISTRIREG:
14860   case X86::PCMPISTRIMEM:
14861   case X86::VPCMPISTRIMEM:
14862   case X86::PCMPESTRIREG:
14863   case X86::VPCMPESTRIREG:
14864   case X86::PCMPESTRIMEM:
14865   case X86::VPCMPESTRIMEM:
14866     assert(Subtarget->hasSSE42() &&
14867            "Target must have SSE4.2 or AVX features enabled");
14868     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14869
14870   // Thread synchronization.
14871   case X86::MONITOR:
14872     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14873
14874   // xbegin
14875   case X86::XBEGIN:
14876     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14877
14878   // Atomic Lowering.
14879   case X86::ATOMAND8:
14880   case X86::ATOMAND16:
14881   case X86::ATOMAND32:
14882   case X86::ATOMAND64:
14883     // Fall through
14884   case X86::ATOMOR8:
14885   case X86::ATOMOR16:
14886   case X86::ATOMOR32:
14887   case X86::ATOMOR64:
14888     // Fall through
14889   case X86::ATOMXOR16:
14890   case X86::ATOMXOR8:
14891   case X86::ATOMXOR32:
14892   case X86::ATOMXOR64:
14893     // Fall through
14894   case X86::ATOMNAND8:
14895   case X86::ATOMNAND16:
14896   case X86::ATOMNAND32:
14897   case X86::ATOMNAND64:
14898     // Fall through
14899   case X86::ATOMMAX8:
14900   case X86::ATOMMAX16:
14901   case X86::ATOMMAX32:
14902   case X86::ATOMMAX64:
14903     // Fall through
14904   case X86::ATOMMIN8:
14905   case X86::ATOMMIN16:
14906   case X86::ATOMMIN32:
14907   case X86::ATOMMIN64:
14908     // Fall through
14909   case X86::ATOMUMAX8:
14910   case X86::ATOMUMAX16:
14911   case X86::ATOMUMAX32:
14912   case X86::ATOMUMAX64:
14913     // Fall through
14914   case X86::ATOMUMIN8:
14915   case X86::ATOMUMIN16:
14916   case X86::ATOMUMIN32:
14917   case X86::ATOMUMIN64:
14918     return EmitAtomicLoadArith(MI, BB);
14919
14920   // This group does 64-bit operations on a 32-bit host.
14921   case X86::ATOMAND6432:
14922   case X86::ATOMOR6432:
14923   case X86::ATOMXOR6432:
14924   case X86::ATOMNAND6432:
14925   case X86::ATOMADD6432:
14926   case X86::ATOMSUB6432:
14927   case X86::ATOMMAX6432:
14928   case X86::ATOMMIN6432:
14929   case X86::ATOMUMAX6432:
14930   case X86::ATOMUMIN6432:
14931   case X86::ATOMSWAP6432:
14932     return EmitAtomicLoadArith6432(MI, BB);
14933
14934   case X86::VASTART_SAVE_XMM_REGS:
14935     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14936
14937   case X86::VAARG_64:
14938     return EmitVAARG64WithCustomInserter(MI, BB);
14939
14940   case X86::EH_SjLj_SetJmp32:
14941   case X86::EH_SjLj_SetJmp64:
14942     return emitEHSjLjSetJmp(MI, BB);
14943
14944   case X86::EH_SjLj_LongJmp32:
14945   case X86::EH_SjLj_LongJmp64:
14946     return emitEHSjLjLongJmp(MI, BB);
14947   }
14948 }
14949
14950 //===----------------------------------------------------------------------===//
14951 //                           X86 Optimization Hooks
14952 //===----------------------------------------------------------------------===//
14953
14954 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14955                                                        APInt &KnownZero,
14956                                                        APInt &KnownOne,
14957                                                        const SelectionDAG &DAG,
14958                                                        unsigned Depth) const {
14959   unsigned BitWidth = KnownZero.getBitWidth();
14960   unsigned Opc = Op.getOpcode();
14961   assert((Opc >= ISD::BUILTIN_OP_END ||
14962           Opc == ISD::INTRINSIC_WO_CHAIN ||
14963           Opc == ISD::INTRINSIC_W_CHAIN ||
14964           Opc == ISD::INTRINSIC_VOID) &&
14965          "Should use MaskedValueIsZero if you don't know whether Op"
14966          " is a target node!");
14967
14968   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14969   switch (Opc) {
14970   default: break;
14971   case X86ISD::ADD:
14972   case X86ISD::SUB:
14973   case X86ISD::ADC:
14974   case X86ISD::SBB:
14975   case X86ISD::SMUL:
14976   case X86ISD::UMUL:
14977   case X86ISD::INC:
14978   case X86ISD::DEC:
14979   case X86ISD::OR:
14980   case X86ISD::XOR:
14981   case X86ISD::AND:
14982     // These nodes' second result is a boolean.
14983     if (Op.getResNo() == 0)
14984       break;
14985     // Fallthrough
14986   case X86ISD::SETCC:
14987     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14988     break;
14989   case ISD::INTRINSIC_WO_CHAIN: {
14990     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14991     unsigned NumLoBits = 0;
14992     switch (IntId) {
14993     default: break;
14994     case Intrinsic::x86_sse_movmsk_ps:
14995     case Intrinsic::x86_avx_movmsk_ps_256:
14996     case Intrinsic::x86_sse2_movmsk_pd:
14997     case Intrinsic::x86_avx_movmsk_pd_256:
14998     case Intrinsic::x86_mmx_pmovmskb:
14999     case Intrinsic::x86_sse2_pmovmskb_128:
15000     case Intrinsic::x86_avx2_pmovmskb: {
15001       // High bits of movmskp{s|d}, pmovmskb are known zero.
15002       switch (IntId) {
15003         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15004         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15005         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15006         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15007         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15008         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15009         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15010         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15011       }
15012       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15013       break;
15014     }
15015     }
15016     break;
15017   }
15018   }
15019 }
15020
15021 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15022                                                          unsigned Depth) const {
15023   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15024   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15025     return Op.getValueType().getScalarType().getSizeInBits();
15026
15027   // Fallback case.
15028   return 1;
15029 }
15030
15031 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15032 /// node is a GlobalAddress + offset.
15033 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15034                                        const GlobalValue* &GA,
15035                                        int64_t &Offset) const {
15036   if (N->getOpcode() == X86ISD::Wrapper) {
15037     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15038       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15039       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15040       return true;
15041     }
15042   }
15043   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15044 }
15045
15046 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15047 /// same as extracting the high 128-bit part of 256-bit vector and then
15048 /// inserting the result into the low part of a new 256-bit vector
15049 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15050   EVT VT = SVOp->getValueType(0);
15051   unsigned NumElems = VT.getVectorNumElements();
15052
15053   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15054   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15055     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15056         SVOp->getMaskElt(j) >= 0)
15057       return false;
15058
15059   return true;
15060 }
15061
15062 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15063 /// same as extracting the low 128-bit part of 256-bit vector and then
15064 /// inserting the result into the high part of a new 256-bit vector
15065 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15066   EVT VT = SVOp->getValueType(0);
15067   unsigned NumElems = VT.getVectorNumElements();
15068
15069   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15070   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15071     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15072         SVOp->getMaskElt(j) >= 0)
15073       return false;
15074
15075   return true;
15076 }
15077
15078 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15079 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15080                                         TargetLowering::DAGCombinerInfo &DCI,
15081                                         const X86Subtarget* Subtarget) {
15082   DebugLoc dl = N->getDebugLoc();
15083   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15084   SDValue V1 = SVOp->getOperand(0);
15085   SDValue V2 = SVOp->getOperand(1);
15086   EVT VT = SVOp->getValueType(0);
15087   unsigned NumElems = VT.getVectorNumElements();
15088
15089   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15090       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15091     //
15092     //                   0,0,0,...
15093     //                      |
15094     //    V      UNDEF    BUILD_VECTOR    UNDEF
15095     //     \      /           \           /
15096     //  CONCAT_VECTOR         CONCAT_VECTOR
15097     //         \                  /
15098     //          \                /
15099     //          RESULT: V + zero extended
15100     //
15101     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15102         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15103         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15104       return SDValue();
15105
15106     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15107       return SDValue();
15108
15109     // To match the shuffle mask, the first half of the mask should
15110     // be exactly the first vector, and all the rest a splat with the
15111     // first element of the second one.
15112     for (unsigned i = 0; i != NumElems/2; ++i)
15113       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15114           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15115         return SDValue();
15116
15117     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15118     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15119       if (Ld->hasNUsesOfValue(1, 0)) {
15120         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15121         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15122         SDValue ResNode =
15123           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2,
15124                                   Ld->getMemoryVT(),
15125                                   Ld->getPointerInfo(),
15126                                   Ld->getAlignment(),
15127                                   false/*isVolatile*/, true/*ReadMem*/,
15128                                   false/*WriteMem*/);
15129
15130         // Make sure the newly-created LOAD is in the same position as Ld in
15131         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15132         // and update uses of Ld's output chain to use the TokenFactor.
15133         if (Ld->hasAnyUseOfValue(1)) {
15134           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15135                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15136           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15137           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15138                                  SDValue(ResNode.getNode(), 1));
15139         }
15140
15141         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15142       }
15143     }
15144
15145     // Emit a zeroed vector and insert the desired subvector on its
15146     // first half.
15147     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15148     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15149     return DCI.CombineTo(N, InsV);
15150   }
15151
15152   //===--------------------------------------------------------------------===//
15153   // Combine some shuffles into subvector extracts and inserts:
15154   //
15155
15156   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15157   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15158     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15159     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15160     return DCI.CombineTo(N, InsV);
15161   }
15162
15163   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15164   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15165     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15166     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15167     return DCI.CombineTo(N, InsV);
15168   }
15169
15170   return SDValue();
15171 }
15172
15173 /// PerformShuffleCombine - Performs several different shuffle combines.
15174 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15175                                      TargetLowering::DAGCombinerInfo &DCI,
15176                                      const X86Subtarget *Subtarget) {
15177   DebugLoc dl = N->getDebugLoc();
15178   EVT VT = N->getValueType(0);
15179
15180   // Don't create instructions with illegal types after legalize types has run.
15181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15182   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15183     return SDValue();
15184
15185   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15186   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15187       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15188     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15189
15190   // Only handle 128 wide vector from here on.
15191   if (!VT.is128BitVector())
15192     return SDValue();
15193
15194   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15195   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15196   // consecutive, non-overlapping, and in the right order.
15197   SmallVector<SDValue, 16> Elts;
15198   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15199     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15200
15201   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15202 }
15203
15204 /// PerformTruncateCombine - Converts truncate operation to
15205 /// a sequence of vector shuffle operations.
15206 /// It is possible when we truncate 256-bit vector to 128-bit vector
15207 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15208                                       TargetLowering::DAGCombinerInfo &DCI,
15209                                       const X86Subtarget *Subtarget)  {
15210   return SDValue();
15211 }
15212
15213 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15214 /// specific shuffle of a load can be folded into a single element load.
15215 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15216 /// shuffles have been customed lowered so we need to handle those here.
15217 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15218                                          TargetLowering::DAGCombinerInfo &DCI) {
15219   if (DCI.isBeforeLegalizeOps())
15220     return SDValue();
15221
15222   SDValue InVec = N->getOperand(0);
15223   SDValue EltNo = N->getOperand(1);
15224
15225   if (!isa<ConstantSDNode>(EltNo))
15226     return SDValue();
15227
15228   EVT VT = InVec.getValueType();
15229
15230   bool HasShuffleIntoBitcast = false;
15231   if (InVec.getOpcode() == ISD::BITCAST) {
15232     // Don't duplicate a load with other uses.
15233     if (!InVec.hasOneUse())
15234       return SDValue();
15235     EVT BCVT = InVec.getOperand(0).getValueType();
15236     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15237       return SDValue();
15238     InVec = InVec.getOperand(0);
15239     HasShuffleIntoBitcast = true;
15240   }
15241
15242   if (!isTargetShuffle(InVec.getOpcode()))
15243     return SDValue();
15244
15245   // Don't duplicate a load with other uses.
15246   if (!InVec.hasOneUse())
15247     return SDValue();
15248
15249   SmallVector<int, 16> ShuffleMask;
15250   bool UnaryShuffle;
15251   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15252                             UnaryShuffle))
15253     return SDValue();
15254
15255   // Select the input vector, guarding against out of range extract vector.
15256   unsigned NumElems = VT.getVectorNumElements();
15257   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15258   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15259   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15260                                          : InVec.getOperand(1);
15261
15262   // If inputs to shuffle are the same for both ops, then allow 2 uses
15263   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15264
15265   if (LdNode.getOpcode() == ISD::BITCAST) {
15266     // Don't duplicate a load with other uses.
15267     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15268       return SDValue();
15269
15270     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15271     LdNode = LdNode.getOperand(0);
15272   }
15273
15274   if (!ISD::isNormalLoad(LdNode.getNode()))
15275     return SDValue();
15276
15277   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15278
15279   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15280     return SDValue();
15281
15282   if (HasShuffleIntoBitcast) {
15283     // If there's a bitcast before the shuffle, check if the load type and
15284     // alignment is valid.
15285     unsigned Align = LN0->getAlignment();
15286     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15287     unsigned NewAlign = TLI.getDataLayout()->
15288       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15289
15290     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15291       return SDValue();
15292   }
15293
15294   // All checks match so transform back to vector_shuffle so that DAG combiner
15295   // can finish the job
15296   DebugLoc dl = N->getDebugLoc();
15297
15298   // Create shuffle node taking into account the case that its a unary shuffle
15299   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15300   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15301                                  InVec.getOperand(0), Shuffle,
15302                                  &ShuffleMask[0]);
15303   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15304   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15305                      EltNo);
15306 }
15307
15308 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15309 /// generation and convert it from being a bunch of shuffles and extracts
15310 /// to a simple store and scalar loads to extract the elements.
15311 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15312                                          TargetLowering::DAGCombinerInfo &DCI) {
15313   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15314   if (NewOp.getNode())
15315     return NewOp;
15316
15317   SDValue InputVector = N->getOperand(0);
15318   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15319   // from mmx to v2i32 has a single usage.
15320   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15321       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15322       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15323     return DAG.getNode(X86ISD::MMX_MOVD2W, InputVector.getDebugLoc(),
15324                        N->getValueType(0),
15325                        InputVector.getNode()->getOperand(0));
15326
15327   // Only operate on vectors of 4 elements, where the alternative shuffling
15328   // gets to be more expensive.
15329   if (InputVector.getValueType() != MVT::v4i32)
15330     return SDValue();
15331
15332   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15333   // single use which is a sign-extend or zero-extend, and all elements are
15334   // used.
15335   SmallVector<SDNode *, 4> Uses;
15336   unsigned ExtractedElements = 0;
15337   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15338        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15339     if (UI.getUse().getResNo() != InputVector.getResNo())
15340       return SDValue();
15341
15342     SDNode *Extract = *UI;
15343     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15344       return SDValue();
15345
15346     if (Extract->getValueType(0) != MVT::i32)
15347       return SDValue();
15348     if (!Extract->hasOneUse())
15349       return SDValue();
15350     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15351         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15352       return SDValue();
15353     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15354       return SDValue();
15355
15356     // Record which element was extracted.
15357     ExtractedElements |=
15358       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15359
15360     Uses.push_back(Extract);
15361   }
15362
15363   // If not all the elements were used, this may not be worthwhile.
15364   if (ExtractedElements != 15)
15365     return SDValue();
15366
15367   // Ok, we've now decided to do the transformation.
15368   DebugLoc dl = InputVector.getDebugLoc();
15369
15370   // Store the value to a temporary stack slot.
15371   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15372   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15373                             MachinePointerInfo(), false, false, 0);
15374
15375   // Replace each use (extract) with a load of the appropriate element.
15376   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15377        UE = Uses.end(); UI != UE; ++UI) {
15378     SDNode *Extract = *UI;
15379
15380     // cOMpute the element's address.
15381     SDValue Idx = Extract->getOperand(1);
15382     unsigned EltSize =
15383         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15384     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15385     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15386     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15387
15388     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15389                                      StackPtr, OffsetVal);
15390
15391     // Load the scalar.
15392     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15393                                      ScalarAddr, MachinePointerInfo(),
15394                                      false, false, false, 0);
15395
15396     // Replace the exact with the load.
15397     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15398   }
15399
15400   // The replacement was made in place; don't return anything.
15401   return SDValue();
15402 }
15403
15404 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15405 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15406                                    SDValue RHS, SelectionDAG &DAG,
15407                                    const X86Subtarget *Subtarget) {
15408   if (!VT.isVector())
15409     return 0;
15410
15411   switch (VT.getSimpleVT().SimpleTy) {
15412   default: return 0;
15413   case MVT::v32i8:
15414   case MVT::v16i16:
15415   case MVT::v8i32:
15416     if (!Subtarget->hasAVX2())
15417       return 0;
15418   case MVT::v16i8:
15419   case MVT::v8i16:
15420   case MVT::v4i32:
15421     if (!Subtarget->hasSSE2())
15422       return 0;
15423   }
15424
15425   // SSE2 has only a small subset of the operations.
15426   bool hasUnsigned = Subtarget->hasSSE41() ||
15427                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15428   bool hasSigned = Subtarget->hasSSE41() ||
15429                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15430
15431   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15432
15433   // Check for x CC y ? x : y.
15434   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15435       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15436     switch (CC) {
15437     default: break;
15438     case ISD::SETULT:
15439     case ISD::SETULE:
15440       return hasUnsigned ? X86ISD::UMIN : 0;
15441     case ISD::SETUGT:
15442     case ISD::SETUGE:
15443       return hasUnsigned ? X86ISD::UMAX : 0;
15444     case ISD::SETLT:
15445     case ISD::SETLE:
15446       return hasSigned ? X86ISD::SMIN : 0;
15447     case ISD::SETGT:
15448     case ISD::SETGE:
15449       return hasSigned ? X86ISD::SMAX : 0;
15450     }
15451   // Check for x CC y ? y : x -- a min/max with reversed arms.
15452   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15453              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15454     switch (CC) {
15455     default: break;
15456     case ISD::SETULT:
15457     case ISD::SETULE:
15458       return hasUnsigned ? X86ISD::UMAX : 0;
15459     case ISD::SETUGT:
15460     case ISD::SETUGE:
15461       return hasUnsigned ? X86ISD::UMIN : 0;
15462     case ISD::SETLT:
15463     case ISD::SETLE:
15464       return hasSigned ? X86ISD::SMAX : 0;
15465     case ISD::SETGT:
15466     case ISD::SETGE:
15467       return hasSigned ? X86ISD::SMIN : 0;
15468     }
15469   }
15470
15471   return 0;
15472 }
15473
15474 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15475 /// nodes.
15476 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15477                                     TargetLowering::DAGCombinerInfo &DCI,
15478                                     const X86Subtarget *Subtarget) {
15479   DebugLoc DL = N->getDebugLoc();
15480   SDValue Cond = N->getOperand(0);
15481   // Get the LHS/RHS of the select.
15482   SDValue LHS = N->getOperand(1);
15483   SDValue RHS = N->getOperand(2);
15484   EVT VT = LHS.getValueType();
15485
15486   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15487   // instructions match the semantics of the common C idiom x<y?x:y but not
15488   // x<=y?x:y, because of how they handle negative zero (which can be
15489   // ignored in unsafe-math mode).
15490   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15491       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15492       (Subtarget->hasSSE2() ||
15493        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15494     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15495
15496     unsigned Opcode = 0;
15497     // Check for x CC y ? x : y.
15498     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15499         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15500       switch (CC) {
15501       default: break;
15502       case ISD::SETULT:
15503         // Converting this to a min would handle NaNs incorrectly, and swapping
15504         // the operands would cause it to handle comparisons between positive
15505         // and negative zero incorrectly.
15506         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15507           if (!DAG.getTarget().Options.UnsafeFPMath &&
15508               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15509             break;
15510           std::swap(LHS, RHS);
15511         }
15512         Opcode = X86ISD::FMIN;
15513         break;
15514       case ISD::SETOLE:
15515         // Converting this to a min would handle comparisons between positive
15516         // and negative zero incorrectly.
15517         if (!DAG.getTarget().Options.UnsafeFPMath &&
15518             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15519           break;
15520         Opcode = X86ISD::FMIN;
15521         break;
15522       case ISD::SETULE:
15523         // Converting this to a min would handle both negative zeros and NaNs
15524         // incorrectly, but we can swap the operands to fix both.
15525         std::swap(LHS, RHS);
15526       case ISD::SETOLT:
15527       case ISD::SETLT:
15528       case ISD::SETLE:
15529         Opcode = X86ISD::FMIN;
15530         break;
15531
15532       case ISD::SETOGE:
15533         // Converting this to a max would handle comparisons between positive
15534         // and negative zero incorrectly.
15535         if (!DAG.getTarget().Options.UnsafeFPMath &&
15536             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15537           break;
15538         Opcode = X86ISD::FMAX;
15539         break;
15540       case ISD::SETUGT:
15541         // Converting this to a max would handle NaNs incorrectly, and swapping
15542         // the operands would cause it to handle comparisons between positive
15543         // and negative zero incorrectly.
15544         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15545           if (!DAG.getTarget().Options.UnsafeFPMath &&
15546               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15547             break;
15548           std::swap(LHS, RHS);
15549         }
15550         Opcode = X86ISD::FMAX;
15551         break;
15552       case ISD::SETUGE:
15553         // Converting this to a max would handle both negative zeros and NaNs
15554         // incorrectly, but we can swap the operands to fix both.
15555         std::swap(LHS, RHS);
15556       case ISD::SETOGT:
15557       case ISD::SETGT:
15558       case ISD::SETGE:
15559         Opcode = X86ISD::FMAX;
15560         break;
15561       }
15562     // Check for x CC y ? y : x -- a min/max with reversed arms.
15563     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15564                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15565       switch (CC) {
15566       default: break;
15567       case ISD::SETOGE:
15568         // Converting this to a min would handle comparisons between positive
15569         // and negative zero incorrectly, and swapping the operands would
15570         // cause it to handle NaNs incorrectly.
15571         if (!DAG.getTarget().Options.UnsafeFPMath &&
15572             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15573           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15574             break;
15575           std::swap(LHS, RHS);
15576         }
15577         Opcode = X86ISD::FMIN;
15578         break;
15579       case ISD::SETUGT:
15580         // Converting this to a min would handle NaNs incorrectly.
15581         if (!DAG.getTarget().Options.UnsafeFPMath &&
15582             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15583           break;
15584         Opcode = X86ISD::FMIN;
15585         break;
15586       case ISD::SETUGE:
15587         // Converting this to a min would handle both negative zeros and NaNs
15588         // incorrectly, but we can swap the operands to fix both.
15589         std::swap(LHS, RHS);
15590       case ISD::SETOGT:
15591       case ISD::SETGT:
15592       case ISD::SETGE:
15593         Opcode = X86ISD::FMIN;
15594         break;
15595
15596       case ISD::SETULT:
15597         // Converting this to a max would handle NaNs incorrectly.
15598         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15599           break;
15600         Opcode = X86ISD::FMAX;
15601         break;
15602       case ISD::SETOLE:
15603         // Converting this to a max would handle comparisons between positive
15604         // and negative zero incorrectly, and swapping the operands would
15605         // cause it to handle NaNs incorrectly.
15606         if (!DAG.getTarget().Options.UnsafeFPMath &&
15607             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15608           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15609             break;
15610           std::swap(LHS, RHS);
15611         }
15612         Opcode = X86ISD::FMAX;
15613         break;
15614       case ISD::SETULE:
15615         // Converting this to a max would handle both negative zeros and NaNs
15616         // incorrectly, but we can swap the operands to fix both.
15617         std::swap(LHS, RHS);
15618       case ISD::SETOLT:
15619       case ISD::SETLT:
15620       case ISD::SETLE:
15621         Opcode = X86ISD::FMAX;
15622         break;
15623       }
15624     }
15625
15626     if (Opcode)
15627       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15628   }
15629
15630   // If this is a select between two integer constants, try to do some
15631   // optimizations.
15632   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15633     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15634       // Don't do this for crazy integer types.
15635       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15636         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15637         // so that TrueC (the true value) is larger than FalseC.
15638         bool NeedsCondInvert = false;
15639
15640         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15641             // Efficiently invertible.
15642             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15643              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15644               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15645           NeedsCondInvert = true;
15646           std::swap(TrueC, FalseC);
15647         }
15648
15649         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15650         if (FalseC->getAPIntValue() == 0 &&
15651             TrueC->getAPIntValue().isPowerOf2()) {
15652           if (NeedsCondInvert) // Invert the condition if needed.
15653             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15654                                DAG.getConstant(1, Cond.getValueType()));
15655
15656           // Zero extend the condition if needed.
15657           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15658
15659           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15660           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15661                              DAG.getConstant(ShAmt, MVT::i8));
15662         }
15663
15664         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15665         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15666           if (NeedsCondInvert) // Invert the condition if needed.
15667             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15668                                DAG.getConstant(1, Cond.getValueType()));
15669
15670           // Zero extend the condition if needed.
15671           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15672                              FalseC->getValueType(0), Cond);
15673           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15674                              SDValue(FalseC, 0));
15675         }
15676
15677         // Optimize cases that will turn into an LEA instruction.  This requires
15678         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15679         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15680           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15681           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15682
15683           bool isFastMultiplier = false;
15684           if (Diff < 10) {
15685             switch ((unsigned char)Diff) {
15686               default: break;
15687               case 1:  // result = add base, cond
15688               case 2:  // result = lea base(    , cond*2)
15689               case 3:  // result = lea base(cond, cond*2)
15690               case 4:  // result = lea base(    , cond*4)
15691               case 5:  // result = lea base(cond, cond*4)
15692               case 8:  // result = lea base(    , cond*8)
15693               case 9:  // result = lea base(cond, cond*8)
15694                 isFastMultiplier = true;
15695                 break;
15696             }
15697           }
15698
15699           if (isFastMultiplier) {
15700             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15701             if (NeedsCondInvert) // Invert the condition if needed.
15702               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15703                                  DAG.getConstant(1, Cond.getValueType()));
15704
15705             // Zero extend the condition if needed.
15706             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15707                                Cond);
15708             // Scale the condition by the difference.
15709             if (Diff != 1)
15710               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15711                                  DAG.getConstant(Diff, Cond.getValueType()));
15712
15713             // Add the base if non-zero.
15714             if (FalseC->getAPIntValue() != 0)
15715               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15716                                  SDValue(FalseC, 0));
15717             return Cond;
15718           }
15719         }
15720       }
15721   }
15722
15723   // Canonicalize max and min:
15724   // (x > y) ? x : y -> (x >= y) ? x : y
15725   // (x < y) ? x : y -> (x <= y) ? x : y
15726   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15727   // the need for an extra compare
15728   // against zero. e.g.
15729   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15730   // subl   %esi, %edi
15731   // testl  %edi, %edi
15732   // movl   $0, %eax
15733   // cmovgl %edi, %eax
15734   // =>
15735   // xorl   %eax, %eax
15736   // subl   %esi, $edi
15737   // cmovsl %eax, %edi
15738   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15739       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15740       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15741     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15742     switch (CC) {
15743     default: break;
15744     case ISD::SETLT:
15745     case ISD::SETGT: {
15746       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15747       Cond = DAG.getSetCC(Cond.getDebugLoc(), Cond.getValueType(),
15748                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15749       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15750     }
15751     }
15752   }
15753
15754   // Match VSELECTs into subs with unsigned saturation.
15755   if (!DCI.isBeforeLegalize() &&
15756       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15757       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15758       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15759        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15760     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15761
15762     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15763     // left side invert the predicate to simplify logic below.
15764     SDValue Other;
15765     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15766       Other = RHS;
15767       CC = ISD::getSetCCInverse(CC, true);
15768     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15769       Other = LHS;
15770     }
15771
15772     if (Other.getNode() && Other->getNumOperands() == 2 &&
15773         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15774       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15775       SDValue CondRHS = Cond->getOperand(1);
15776
15777       // Look for a general sub with unsigned saturation first.
15778       // x >= y ? x-y : 0 --> subus x, y
15779       // x >  y ? x-y : 0 --> subus x, y
15780       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15781           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15782         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15783
15784       // If the RHS is a constant we have to reverse the const canonicalization.
15785       // x > C-1 ? x+-C : 0 --> subus x, C
15786       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15787           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15788         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15789         if (CondRHS.getConstantOperandVal(0) == -A-1)
15790           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15791                              DAG.getConstant(-A, VT));
15792       }
15793
15794       // Another special case: If C was a sign bit, the sub has been
15795       // canonicalized into a xor.
15796       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15797       //        it's safe to decanonicalize the xor?
15798       // x s< 0 ? x^C : 0 --> subus x, C
15799       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15800           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15801           isSplatVector(OpRHS.getNode())) {
15802         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15803         if (A.isSignBit())
15804           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15805       }
15806     }
15807   }
15808
15809   // Try to match a min/max vector operation.
15810   if (!DCI.isBeforeLegalize() &&
15811       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15812     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15813       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15814
15815   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15816   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15817       Cond.getOpcode() == ISD::SETCC) {
15818
15819     assert(Cond.getValueType().isVector() &&
15820            "vector select expects a vector selector!");
15821
15822     EVT IntVT = Cond.getValueType();
15823     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15824     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15825
15826     if (!TValIsAllOnes && !FValIsAllZeros) {
15827       // Try invert the condition if true value is not all 1s and false value
15828       // is not all 0s.
15829       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15830       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15831
15832       if (TValIsAllZeros || FValIsAllOnes) {
15833         SDValue CC = Cond.getOperand(2);
15834         ISD::CondCode NewCC =
15835           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15836                                Cond.getOperand(0).getValueType().isInteger());
15837         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15838         std::swap(LHS, RHS);
15839         TValIsAllOnes = FValIsAllOnes;
15840         FValIsAllZeros = TValIsAllZeros;
15841       }
15842     }
15843
15844     if (TValIsAllOnes || FValIsAllZeros) {
15845       SDValue Ret;
15846
15847       if (TValIsAllOnes && FValIsAllZeros)
15848         Ret = Cond;
15849       else if (TValIsAllOnes)
15850         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15851                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15852       else if (FValIsAllZeros)
15853         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15854                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15855
15856       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15857     }
15858   }
15859
15860   // If we know that this node is legal then we know that it is going to be
15861   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15862   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15863   // to simplify previous instructions.
15864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15865   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15866       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15867     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15868
15869     // Don't optimize vector selects that map to mask-registers.
15870     if (BitWidth == 1)
15871       return SDValue();
15872
15873     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15874     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15875
15876     APInt KnownZero, KnownOne;
15877     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15878                                           DCI.isBeforeLegalizeOps());
15879     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15880         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15881       DCI.CommitTargetLoweringOpt(TLO);
15882   }
15883
15884   return SDValue();
15885 }
15886
15887 // Check whether a boolean test is testing a boolean value generated by
15888 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15889 // code.
15890 //
15891 // Simplify the following patterns:
15892 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15893 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15894 // to (Op EFLAGS Cond)
15895 //
15896 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15897 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15898 // to (Op EFLAGS !Cond)
15899 //
15900 // where Op could be BRCOND or CMOV.
15901 //
15902 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15903   // Quit if not CMP and SUB with its value result used.
15904   if (Cmp.getOpcode() != X86ISD::CMP &&
15905       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15906       return SDValue();
15907
15908   // Quit if not used as a boolean value.
15909   if (CC != X86::COND_E && CC != X86::COND_NE)
15910     return SDValue();
15911
15912   // Check CMP operands. One of them should be 0 or 1 and the other should be
15913   // an SetCC or extended from it.
15914   SDValue Op1 = Cmp.getOperand(0);
15915   SDValue Op2 = Cmp.getOperand(1);
15916
15917   SDValue SetCC;
15918   const ConstantSDNode* C = 0;
15919   bool needOppositeCond = (CC == X86::COND_E);
15920   bool checkAgainstTrue = false; // Is it a comparison against 1?
15921
15922   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15923     SetCC = Op2;
15924   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15925     SetCC = Op1;
15926   else // Quit if all operands are not constants.
15927     return SDValue();
15928
15929   if (C->getZExtValue() == 1) {
15930     needOppositeCond = !needOppositeCond;
15931     checkAgainstTrue = true;
15932   } else if (C->getZExtValue() != 0)
15933     // Quit if the constant is neither 0 or 1.
15934     return SDValue();
15935
15936   bool truncatedToBoolWithAnd = false;
15937   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15938   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15939          SetCC.getOpcode() == ISD::TRUNCATE ||
15940          SetCC.getOpcode() == ISD::AND) {
15941     if (SetCC.getOpcode() == ISD::AND) {
15942       int OpIdx = -1;
15943       ConstantSDNode *CS;
15944       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15945           CS->getZExtValue() == 1)
15946         OpIdx = 1;
15947       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15948           CS->getZExtValue() == 1)
15949         OpIdx = 0;
15950       if (OpIdx == -1)
15951         break;
15952       SetCC = SetCC.getOperand(OpIdx);
15953       truncatedToBoolWithAnd = true;
15954     } else
15955       SetCC = SetCC.getOperand(0);
15956   }
15957
15958   switch (SetCC.getOpcode()) {
15959   case X86ISD::SETCC_CARRY:
15960     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15961     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15962     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15963     // truncated to i1 using 'and'.
15964     if (checkAgainstTrue && !truncatedToBoolWithAnd)
15965       break;
15966     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15967            "Invalid use of SETCC_CARRY!");
15968     // FALL THROUGH
15969   case X86ISD::SETCC:
15970     // Set the condition code or opposite one if necessary.
15971     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15972     if (needOppositeCond)
15973       CC = X86::GetOppositeBranchCondition(CC);
15974     return SetCC.getOperand(1);
15975   case X86ISD::CMOV: {
15976     // Check whether false/true value has canonical one, i.e. 0 or 1.
15977     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15978     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15979     // Quit if true value is not a constant.
15980     if (!TVal)
15981       return SDValue();
15982     // Quit if false value is not a constant.
15983     if (!FVal) {
15984       SDValue Op = SetCC.getOperand(0);
15985       // Skip 'zext' or 'trunc' node.
15986       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15987           Op.getOpcode() == ISD::TRUNCATE)
15988         Op = Op.getOperand(0);
15989       // A special case for rdrand/rdseed, where 0 is set if false cond is
15990       // found.
15991       if ((Op.getOpcode() != X86ISD::RDRAND &&
15992            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15993         return SDValue();
15994     }
15995     // Quit if false value is not the constant 0 or 1.
15996     bool FValIsFalse = true;
15997     if (FVal && FVal->getZExtValue() != 0) {
15998       if (FVal->getZExtValue() != 1)
15999         return SDValue();
16000       // If FVal is 1, opposite cond is needed.
16001       needOppositeCond = !needOppositeCond;
16002       FValIsFalse = false;
16003     }
16004     // Quit if TVal is not the constant opposite of FVal.
16005     if (FValIsFalse && TVal->getZExtValue() != 1)
16006       return SDValue();
16007     if (!FValIsFalse && TVal->getZExtValue() != 0)
16008       return SDValue();
16009     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16010     if (needOppositeCond)
16011       CC = X86::GetOppositeBranchCondition(CC);
16012     return SetCC.getOperand(3);
16013   }
16014   }
16015
16016   return SDValue();
16017 }
16018
16019 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16020 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16021                                   TargetLowering::DAGCombinerInfo &DCI,
16022                                   const X86Subtarget *Subtarget) {
16023   DebugLoc DL = N->getDebugLoc();
16024
16025   // If the flag operand isn't dead, don't touch this CMOV.
16026   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16027     return SDValue();
16028
16029   SDValue FalseOp = N->getOperand(0);
16030   SDValue TrueOp = N->getOperand(1);
16031   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16032   SDValue Cond = N->getOperand(3);
16033
16034   if (CC == X86::COND_E || CC == X86::COND_NE) {
16035     switch (Cond.getOpcode()) {
16036     default: break;
16037     case X86ISD::BSR:
16038     case X86ISD::BSF:
16039       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16040       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16041         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16042     }
16043   }
16044
16045   SDValue Flags;
16046
16047   Flags = checkBoolTestSetCCCombine(Cond, CC);
16048   if (Flags.getNode() &&
16049       // Extra check as FCMOV only supports a subset of X86 cond.
16050       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16051     SDValue Ops[] = { FalseOp, TrueOp,
16052                       DAG.getConstant(CC, MVT::i8), Flags };
16053     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16054                        Ops, array_lengthof(Ops));
16055   }
16056
16057   // If this is a select between two integer constants, try to do some
16058   // optimizations.  Note that the operands are ordered the opposite of SELECT
16059   // operands.
16060   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16061     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16062       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16063       // larger than FalseC (the false value).
16064       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16065         CC = X86::GetOppositeBranchCondition(CC);
16066         std::swap(TrueC, FalseC);
16067         std::swap(TrueOp, FalseOp);
16068       }
16069
16070       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16071       // This is efficient for any integer data type (including i8/i16) and
16072       // shift amount.
16073       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16074         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16075                            DAG.getConstant(CC, MVT::i8), Cond);
16076
16077         // Zero extend the condition if needed.
16078         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16079
16080         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16081         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16082                            DAG.getConstant(ShAmt, MVT::i8));
16083         if (N->getNumValues() == 2)  // Dead flag value?
16084           return DCI.CombineTo(N, Cond, SDValue());
16085         return Cond;
16086       }
16087
16088       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16089       // for any integer data type, including i8/i16.
16090       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16091         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16092                            DAG.getConstant(CC, MVT::i8), Cond);
16093
16094         // Zero extend the condition if needed.
16095         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16096                            FalseC->getValueType(0), Cond);
16097         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16098                            SDValue(FalseC, 0));
16099
16100         if (N->getNumValues() == 2)  // Dead flag value?
16101           return DCI.CombineTo(N, Cond, SDValue());
16102         return Cond;
16103       }
16104
16105       // Optimize cases that will turn into an LEA instruction.  This requires
16106       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16107       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16108         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16109         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16110
16111         bool isFastMultiplier = false;
16112         if (Diff < 10) {
16113           switch ((unsigned char)Diff) {
16114           default: break;
16115           case 1:  // result = add base, cond
16116           case 2:  // result = lea base(    , cond*2)
16117           case 3:  // result = lea base(cond, cond*2)
16118           case 4:  // result = lea base(    , cond*4)
16119           case 5:  // result = lea base(cond, cond*4)
16120           case 8:  // result = lea base(    , cond*8)
16121           case 9:  // result = lea base(cond, cond*8)
16122             isFastMultiplier = true;
16123             break;
16124           }
16125         }
16126
16127         if (isFastMultiplier) {
16128           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16129           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16130                              DAG.getConstant(CC, MVT::i8), Cond);
16131           // Zero extend the condition if needed.
16132           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16133                              Cond);
16134           // Scale the condition by the difference.
16135           if (Diff != 1)
16136             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16137                                DAG.getConstant(Diff, Cond.getValueType()));
16138
16139           // Add the base if non-zero.
16140           if (FalseC->getAPIntValue() != 0)
16141             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16142                                SDValue(FalseC, 0));
16143           if (N->getNumValues() == 2)  // Dead flag value?
16144             return DCI.CombineTo(N, Cond, SDValue());
16145           return Cond;
16146         }
16147       }
16148     }
16149   }
16150
16151   // Handle these cases:
16152   //   (select (x != c), e, c) -> select (x != c), e, x),
16153   //   (select (x == c), c, e) -> select (x == c), x, e)
16154   // where the c is an integer constant, and the "select" is the combination
16155   // of CMOV and CMP.
16156   //
16157   // The rationale for this change is that the conditional-move from a constant
16158   // needs two instructions, however, conditional-move from a register needs
16159   // only one instruction.
16160   //
16161   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16162   //  some instruction-combining opportunities. This opt needs to be
16163   //  postponed as late as possible.
16164   //
16165   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16166     // the DCI.xxxx conditions are provided to postpone the optimization as
16167     // late as possible.
16168
16169     ConstantSDNode *CmpAgainst = 0;
16170     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16171         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16172         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16173
16174       if (CC == X86::COND_NE &&
16175           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16176         CC = X86::GetOppositeBranchCondition(CC);
16177         std::swap(TrueOp, FalseOp);
16178       }
16179
16180       if (CC == X86::COND_E &&
16181           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16182         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16183                           DAG.getConstant(CC, MVT::i8), Cond };
16184         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16185                            array_lengthof(Ops));
16186       }
16187     }
16188   }
16189
16190   return SDValue();
16191 }
16192
16193 /// PerformMulCombine - Optimize a single multiply with constant into two
16194 /// in order to implement it with two cheaper instructions, e.g.
16195 /// LEA + SHL, LEA + LEA.
16196 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16197                                  TargetLowering::DAGCombinerInfo &DCI) {
16198   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16199     return SDValue();
16200
16201   EVT VT = N->getValueType(0);
16202   if (VT != MVT::i64)
16203     return SDValue();
16204
16205   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16206   if (!C)
16207     return SDValue();
16208   uint64_t MulAmt = C->getZExtValue();
16209   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16210     return SDValue();
16211
16212   uint64_t MulAmt1 = 0;
16213   uint64_t MulAmt2 = 0;
16214   if ((MulAmt % 9) == 0) {
16215     MulAmt1 = 9;
16216     MulAmt2 = MulAmt / 9;
16217   } else if ((MulAmt % 5) == 0) {
16218     MulAmt1 = 5;
16219     MulAmt2 = MulAmt / 5;
16220   } else if ((MulAmt % 3) == 0) {
16221     MulAmt1 = 3;
16222     MulAmt2 = MulAmt / 3;
16223   }
16224   if (MulAmt2 &&
16225       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16226     DebugLoc DL = N->getDebugLoc();
16227
16228     if (isPowerOf2_64(MulAmt2) &&
16229         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16230       // If second multiplifer is pow2, issue it first. We want the multiply by
16231       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16232       // is an add.
16233       std::swap(MulAmt1, MulAmt2);
16234
16235     SDValue NewMul;
16236     if (isPowerOf2_64(MulAmt1))
16237       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16238                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16239     else
16240       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16241                            DAG.getConstant(MulAmt1, VT));
16242
16243     if (isPowerOf2_64(MulAmt2))
16244       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16245                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16246     else
16247       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16248                            DAG.getConstant(MulAmt2, VT));
16249
16250     // Do not add new nodes to DAG combiner worklist.
16251     DCI.CombineTo(N, NewMul, false);
16252   }
16253   return SDValue();
16254 }
16255
16256 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16257   SDValue N0 = N->getOperand(0);
16258   SDValue N1 = N->getOperand(1);
16259   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16260   EVT VT = N0.getValueType();
16261
16262   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16263   // since the result of setcc_c is all zero's or all ones.
16264   if (VT.isInteger() && !VT.isVector() &&
16265       N1C && N0.getOpcode() == ISD::AND &&
16266       N0.getOperand(1).getOpcode() == ISD::Constant) {
16267     SDValue N00 = N0.getOperand(0);
16268     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16269         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16270           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16271          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16272       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16273       APInt ShAmt = N1C->getAPIntValue();
16274       Mask = Mask.shl(ShAmt);
16275       if (Mask != 0)
16276         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
16277                            N00, DAG.getConstant(Mask, VT));
16278     }
16279   }
16280
16281   // Hardware support for vector shifts is sparse which makes us scalarize the
16282   // vector operations in many cases. Also, on sandybridge ADD is faster than
16283   // shl.
16284   // (shl V, 1) -> add V,V
16285   if (isSplatVector(N1.getNode())) {
16286     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16287     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16288     // We shift all of the values by one. In many cases we do not have
16289     // hardware support for this operation. This is better expressed as an ADD
16290     // of two values.
16291     if (N1C && (1 == N1C->getZExtValue())) {
16292       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
16293     }
16294   }
16295
16296   return SDValue();
16297 }
16298
16299 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
16300 ///                       when possible.
16301 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16302                                    TargetLowering::DAGCombinerInfo &DCI,
16303                                    const X86Subtarget *Subtarget) {
16304   if (N->getOpcode() == ISD::SHL) {
16305     SDValue V = PerformSHLCombine(N, DAG);
16306     if (V.getNode()) return V;
16307   }
16308
16309   return SDValue();
16310 }
16311
16312 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16313 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16314 // and friends.  Likewise for OR -> CMPNEQSS.
16315 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16316                             TargetLowering::DAGCombinerInfo &DCI,
16317                             const X86Subtarget *Subtarget) {
16318   unsigned opcode;
16319
16320   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16321   // we're requiring SSE2 for both.
16322   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16323     SDValue N0 = N->getOperand(0);
16324     SDValue N1 = N->getOperand(1);
16325     SDValue CMP0 = N0->getOperand(1);
16326     SDValue CMP1 = N1->getOperand(1);
16327     DebugLoc DL = N->getDebugLoc();
16328
16329     // The SETCCs should both refer to the same CMP.
16330     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16331       return SDValue();
16332
16333     SDValue CMP00 = CMP0->getOperand(0);
16334     SDValue CMP01 = CMP0->getOperand(1);
16335     EVT     VT    = CMP00.getValueType();
16336
16337     if (VT == MVT::f32 || VT == MVT::f64) {
16338       bool ExpectingFlags = false;
16339       // Check for any users that want flags:
16340       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16341            !ExpectingFlags && UI != UE; ++UI)
16342         switch (UI->getOpcode()) {
16343         default:
16344         case ISD::BR_CC:
16345         case ISD::BRCOND:
16346         case ISD::SELECT:
16347           ExpectingFlags = true;
16348           break;
16349         case ISD::CopyToReg:
16350         case ISD::SIGN_EXTEND:
16351         case ISD::ZERO_EXTEND:
16352         case ISD::ANY_EXTEND:
16353           break;
16354         }
16355
16356       if (!ExpectingFlags) {
16357         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16358         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16359
16360         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16361           X86::CondCode tmp = cc0;
16362           cc0 = cc1;
16363           cc1 = tmp;
16364         }
16365
16366         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16367             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16368           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16369           X86ISD::NodeType NTOperator = is64BitFP ?
16370             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16371           // FIXME: need symbolic constants for these magic numbers.
16372           // See X86ATTInstPrinter.cpp:printSSECC().
16373           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16374           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16375                                               DAG.getConstant(x86cc, MVT::i8));
16376           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16377                                               OnesOrZeroesF);
16378           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16379                                       DAG.getConstant(1, MVT::i32));
16380           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16381           return OneBitOfTruth;
16382         }
16383       }
16384     }
16385   }
16386   return SDValue();
16387 }
16388
16389 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16390 /// so it can be folded inside ANDNP.
16391 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16392   EVT VT = N->getValueType(0);
16393
16394   // Match direct AllOnes for 128 and 256-bit vectors
16395   if (ISD::isBuildVectorAllOnes(N))
16396     return true;
16397
16398   // Look through a bit convert.
16399   if (N->getOpcode() == ISD::BITCAST)
16400     N = N->getOperand(0).getNode();
16401
16402   // Sometimes the operand may come from a insert_subvector building a 256-bit
16403   // allones vector
16404   if (VT.is256BitVector() &&
16405       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16406     SDValue V1 = N->getOperand(0);
16407     SDValue V2 = N->getOperand(1);
16408
16409     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16410         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16411         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16412         ISD::isBuildVectorAllOnes(V2.getNode()))
16413       return true;
16414   }
16415
16416   return false;
16417 }
16418
16419 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16420 // register. In most cases we actually compare or select YMM-sized registers
16421 // and mixing the two types creates horrible code. This method optimizes
16422 // some of the transition sequences.
16423 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16424                                  TargetLowering::DAGCombinerInfo &DCI,
16425                                  const X86Subtarget *Subtarget) {
16426   EVT VT = N->getValueType(0);
16427   if (!VT.is256BitVector())
16428     return SDValue();
16429
16430   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16431           N->getOpcode() == ISD::ZERO_EXTEND ||
16432           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16433
16434   SDValue Narrow = N->getOperand(0);
16435   EVT NarrowVT = Narrow->getValueType(0);
16436   if (!NarrowVT.is128BitVector())
16437     return SDValue();
16438
16439   if (Narrow->getOpcode() != ISD::XOR &&
16440       Narrow->getOpcode() != ISD::AND &&
16441       Narrow->getOpcode() != ISD::OR)
16442     return SDValue();
16443
16444   SDValue N0  = Narrow->getOperand(0);
16445   SDValue N1  = Narrow->getOperand(1);
16446   DebugLoc DL = Narrow->getDebugLoc();
16447
16448   // The Left side has to be a trunc.
16449   if (N0.getOpcode() != ISD::TRUNCATE)
16450     return SDValue();
16451
16452   // The type of the truncated inputs.
16453   EVT WideVT = N0->getOperand(0)->getValueType(0);
16454   if (WideVT != VT)
16455     return SDValue();
16456
16457   // The right side has to be a 'trunc' or a constant vector.
16458   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16459   bool RHSConst = (isSplatVector(N1.getNode()) &&
16460                    isa<ConstantSDNode>(N1->getOperand(0)));
16461   if (!RHSTrunc && !RHSConst)
16462     return SDValue();
16463
16464   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16465
16466   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16467     return SDValue();
16468
16469   // Set N0 and N1 to hold the inputs to the new wide operation.
16470   N0 = N0->getOperand(0);
16471   if (RHSConst) {
16472     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16473                      N1->getOperand(0));
16474     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16475     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16476   } else if (RHSTrunc) {
16477     N1 = N1->getOperand(0);
16478   }
16479
16480   // Generate the wide operation.
16481   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16482   unsigned Opcode = N->getOpcode();
16483   switch (Opcode) {
16484   case ISD::ANY_EXTEND:
16485     return Op;
16486   case ISD::ZERO_EXTEND: {
16487     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16488     APInt Mask = APInt::getAllOnesValue(InBits);
16489     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16490     return DAG.getNode(ISD::AND, DL, VT,
16491                        Op, DAG.getConstant(Mask, VT));
16492   }
16493   case ISD::SIGN_EXTEND:
16494     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16495                        Op, DAG.getValueType(NarrowVT));
16496   default:
16497     llvm_unreachable("Unexpected opcode");
16498   }
16499 }
16500
16501 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16502                                  TargetLowering::DAGCombinerInfo &DCI,
16503                                  const X86Subtarget *Subtarget) {
16504   EVT VT = N->getValueType(0);
16505   if (DCI.isBeforeLegalizeOps())
16506     return SDValue();
16507
16508   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16509   if (R.getNode())
16510     return R;
16511
16512   // Create BLSI, and BLSR instructions
16513   // BLSI is X & (-X)
16514   // BLSR is X & (X-1)
16515   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16516     SDValue N0 = N->getOperand(0);
16517     SDValue N1 = N->getOperand(1);
16518     DebugLoc DL = N->getDebugLoc();
16519
16520     // Check LHS for neg
16521     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16522         isZero(N0.getOperand(0)))
16523       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16524
16525     // Check RHS for neg
16526     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16527         isZero(N1.getOperand(0)))
16528       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16529
16530     // Check LHS for X-1
16531     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16532         isAllOnes(N0.getOperand(1)))
16533       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16534
16535     // Check RHS for X-1
16536     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16537         isAllOnes(N1.getOperand(1)))
16538       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16539
16540     return SDValue();
16541   }
16542
16543   // Want to form ANDNP nodes:
16544   // 1) In the hopes of then easily combining them with OR and AND nodes
16545   //    to form PBLEND/PSIGN.
16546   // 2) To match ANDN packed intrinsics
16547   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16548     return SDValue();
16549
16550   SDValue N0 = N->getOperand(0);
16551   SDValue N1 = N->getOperand(1);
16552   DebugLoc DL = N->getDebugLoc();
16553
16554   // Check LHS for vnot
16555   if (N0.getOpcode() == ISD::XOR &&
16556       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16557       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16558     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16559
16560   // Check RHS for vnot
16561   if (N1.getOpcode() == ISD::XOR &&
16562       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16563       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16564     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16565
16566   return SDValue();
16567 }
16568
16569 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16570                                 TargetLowering::DAGCombinerInfo &DCI,
16571                                 const X86Subtarget *Subtarget) {
16572   EVT VT = N->getValueType(0);
16573   if (DCI.isBeforeLegalizeOps())
16574     return SDValue();
16575
16576   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16577   if (R.getNode())
16578     return R;
16579
16580   SDValue N0 = N->getOperand(0);
16581   SDValue N1 = N->getOperand(1);
16582
16583   // look for psign/blend
16584   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16585     if (!Subtarget->hasSSSE3() ||
16586         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16587       return SDValue();
16588
16589     // Canonicalize pandn to RHS
16590     if (N0.getOpcode() == X86ISD::ANDNP)
16591       std::swap(N0, N1);
16592     // or (and (m, y), (pandn m, x))
16593     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16594       SDValue Mask = N1.getOperand(0);
16595       SDValue X    = N1.getOperand(1);
16596       SDValue Y;
16597       if (N0.getOperand(0) == Mask)
16598         Y = N0.getOperand(1);
16599       if (N0.getOperand(1) == Mask)
16600         Y = N0.getOperand(0);
16601
16602       // Check to see if the mask appeared in both the AND and ANDNP and
16603       if (!Y.getNode())
16604         return SDValue();
16605
16606       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16607       // Look through mask bitcast.
16608       if (Mask.getOpcode() == ISD::BITCAST)
16609         Mask = Mask.getOperand(0);
16610       if (X.getOpcode() == ISD::BITCAST)
16611         X = X.getOperand(0);
16612       if (Y.getOpcode() == ISD::BITCAST)
16613         Y = Y.getOperand(0);
16614
16615       EVT MaskVT = Mask.getValueType();
16616
16617       // Validate that the Mask operand is a vector sra node.
16618       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16619       // there is no psrai.b
16620       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16621       unsigned SraAmt = ~0;
16622       if (Mask.getOpcode() == ISD::SRA) {
16623         SDValue Amt = Mask.getOperand(1);
16624         if (isSplatVector(Amt.getNode())) {
16625           SDValue SclrAmt = Amt->getOperand(0);
16626           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16627             SraAmt = C->getZExtValue();
16628         }
16629       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16630         SDValue SraC = Mask.getOperand(1);
16631         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16632       }
16633       if ((SraAmt + 1) != EltBits)
16634         return SDValue();
16635
16636       DebugLoc DL = N->getDebugLoc();
16637
16638       // Now we know we at least have a plendvb with the mask val.  See if
16639       // we can form a psignb/w/d.
16640       // psign = x.type == y.type == mask.type && y = sub(0, x);
16641       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16642           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16643           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16644         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16645                "Unsupported VT for PSIGN");
16646         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16647         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16648       }
16649       // PBLENDVB only available on SSE 4.1
16650       if (!Subtarget->hasSSE41())
16651         return SDValue();
16652
16653       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16654
16655       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16656       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16657       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16658       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16659       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16660     }
16661   }
16662
16663   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16664     return SDValue();
16665
16666   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16667   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16668     std::swap(N0, N1);
16669   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16670     return SDValue();
16671   if (!N0.hasOneUse() || !N1.hasOneUse())
16672     return SDValue();
16673
16674   SDValue ShAmt0 = N0.getOperand(1);
16675   if (ShAmt0.getValueType() != MVT::i8)
16676     return SDValue();
16677   SDValue ShAmt1 = N1.getOperand(1);
16678   if (ShAmt1.getValueType() != MVT::i8)
16679     return SDValue();
16680   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16681     ShAmt0 = ShAmt0.getOperand(0);
16682   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16683     ShAmt1 = ShAmt1.getOperand(0);
16684
16685   DebugLoc DL = N->getDebugLoc();
16686   unsigned Opc = X86ISD::SHLD;
16687   SDValue Op0 = N0.getOperand(0);
16688   SDValue Op1 = N1.getOperand(0);
16689   if (ShAmt0.getOpcode() == ISD::SUB) {
16690     Opc = X86ISD::SHRD;
16691     std::swap(Op0, Op1);
16692     std::swap(ShAmt0, ShAmt1);
16693   }
16694
16695   unsigned Bits = VT.getSizeInBits();
16696   if (ShAmt1.getOpcode() == ISD::SUB) {
16697     SDValue Sum = ShAmt1.getOperand(0);
16698     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16699       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16700       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16701         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16702       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16703         return DAG.getNode(Opc, DL, VT,
16704                            Op0, Op1,
16705                            DAG.getNode(ISD::TRUNCATE, DL,
16706                                        MVT::i8, ShAmt0));
16707     }
16708   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16709     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16710     if (ShAmt0C &&
16711         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16712       return DAG.getNode(Opc, DL, VT,
16713                          N0.getOperand(0), N1.getOperand(0),
16714                          DAG.getNode(ISD::TRUNCATE, DL,
16715                                        MVT::i8, ShAmt0));
16716   }
16717
16718   return SDValue();
16719 }
16720
16721 // Generate NEG and CMOV for integer abs.
16722 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16723   EVT VT = N->getValueType(0);
16724
16725   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16726   // 8-bit integer abs to NEG and CMOV.
16727   if (VT.isInteger() && VT.getSizeInBits() == 8)
16728     return SDValue();
16729
16730   SDValue N0 = N->getOperand(0);
16731   SDValue N1 = N->getOperand(1);
16732   DebugLoc DL = N->getDebugLoc();
16733
16734   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16735   // and change it to SUB and CMOV.
16736   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16737       N0.getOpcode() == ISD::ADD &&
16738       N0.getOperand(1) == N1 &&
16739       N1.getOpcode() == ISD::SRA &&
16740       N1.getOperand(0) == N0.getOperand(0))
16741     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16742       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16743         // Generate SUB & CMOV.
16744         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16745                                   DAG.getConstant(0, VT), N0.getOperand(0));
16746
16747         SDValue Ops[] = { N0.getOperand(0), Neg,
16748                           DAG.getConstant(X86::COND_GE, MVT::i8),
16749                           SDValue(Neg.getNode(), 1) };
16750         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16751                            Ops, array_lengthof(Ops));
16752       }
16753   return SDValue();
16754 }
16755
16756 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16757 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16758                                  TargetLowering::DAGCombinerInfo &DCI,
16759                                  const X86Subtarget *Subtarget) {
16760   EVT VT = N->getValueType(0);
16761   if (DCI.isBeforeLegalizeOps())
16762     return SDValue();
16763
16764   if (Subtarget->hasCMov()) {
16765     SDValue RV = performIntegerAbsCombine(N, DAG);
16766     if (RV.getNode())
16767       return RV;
16768   }
16769
16770   // Try forming BMI if it is available.
16771   if (!Subtarget->hasBMI())
16772     return SDValue();
16773
16774   if (VT != MVT::i32 && VT != MVT::i64)
16775     return SDValue();
16776
16777   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16778
16779   // Create BLSMSK instructions by finding X ^ (X-1)
16780   SDValue N0 = N->getOperand(0);
16781   SDValue N1 = N->getOperand(1);
16782   DebugLoc DL = N->getDebugLoc();
16783
16784   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16785       isAllOnes(N0.getOperand(1)))
16786     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16787
16788   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16789       isAllOnes(N1.getOperand(1)))
16790     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16791
16792   return SDValue();
16793 }
16794
16795 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16796 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16797                                   TargetLowering::DAGCombinerInfo &DCI,
16798                                   const X86Subtarget *Subtarget) {
16799   LoadSDNode *Ld = cast<LoadSDNode>(N);
16800   EVT RegVT = Ld->getValueType(0);
16801   EVT MemVT = Ld->getMemoryVT();
16802   DebugLoc dl = Ld->getDebugLoc();
16803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16804   unsigned RegSz = RegVT.getSizeInBits();
16805
16806   // On Sandybridge unaligned 256bit loads are inefficient.
16807   ISD::LoadExtType Ext = Ld->getExtensionType();
16808   unsigned Alignment = Ld->getAlignment();
16809   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16810   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16811       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16812     unsigned NumElems = RegVT.getVectorNumElements();
16813     if (NumElems < 2)
16814       return SDValue();
16815
16816     SDValue Ptr = Ld->getBasePtr();
16817     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16818
16819     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16820                                   NumElems/2);
16821     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16822                                 Ld->getPointerInfo(), Ld->isVolatile(),
16823                                 Ld->isNonTemporal(), Ld->isInvariant(),
16824                                 Alignment);
16825     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16826     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16827                                 Ld->getPointerInfo(), Ld->isVolatile(),
16828                                 Ld->isNonTemporal(), Ld->isInvariant(),
16829                                 std::min(16U, Alignment));
16830     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16831                              Load1.getValue(1),
16832                              Load2.getValue(1));
16833
16834     SDValue NewVec = DAG.getUNDEF(RegVT);
16835     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16836     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16837     return DCI.CombineTo(N, NewVec, TF, true);
16838   }
16839
16840   // If this is a vector EXT Load then attempt to optimize it using a
16841   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16842   // expansion is still better than scalar code.
16843   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16844   // emit a shuffle and a arithmetic shift.
16845   // TODO: It is possible to support ZExt by zeroing the undef values
16846   // during the shuffle phase or after the shuffle.
16847   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16848       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16849     assert(MemVT != RegVT && "Cannot extend to the same type");
16850     assert(MemVT.isVector() && "Must load a vector from memory");
16851
16852     unsigned NumElems = RegVT.getVectorNumElements();
16853     unsigned MemSz = MemVT.getSizeInBits();
16854     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16855
16856     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16857       return SDValue();
16858
16859     // All sizes must be a power of two.
16860     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16861       return SDValue();
16862
16863     // Attempt to load the original value using scalar loads.
16864     // Find the largest scalar type that divides the total loaded size.
16865     MVT SclrLoadTy = MVT::i8;
16866     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16867          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16868       MVT Tp = (MVT::SimpleValueType)tp;
16869       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16870         SclrLoadTy = Tp;
16871       }
16872     }
16873
16874     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16875     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16876         (64 <= MemSz))
16877       SclrLoadTy = MVT::f64;
16878
16879     // Calculate the number of scalar loads that we need to perform
16880     // in order to load our vector from memory.
16881     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16882     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16883       return SDValue();
16884
16885     unsigned loadRegZize = RegSz;
16886     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16887       loadRegZize /= 2;
16888
16889     // Represent our vector as a sequence of elements which are the
16890     // largest scalar that we can load.
16891     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16892       loadRegZize/SclrLoadTy.getSizeInBits());
16893
16894     // Represent the data using the same element type that is stored in
16895     // memory. In practice, we ''widen'' MemVT.
16896     EVT WideVecVT =
16897           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16898                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16899
16900     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16901       "Invalid vector type");
16902
16903     // We can't shuffle using an illegal type.
16904     if (!TLI.isTypeLegal(WideVecVT))
16905       return SDValue();
16906
16907     SmallVector<SDValue, 8> Chains;
16908     SDValue Ptr = Ld->getBasePtr();
16909     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16910                                         TLI.getPointerTy());
16911     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16912
16913     for (unsigned i = 0; i < NumLoads; ++i) {
16914       // Perform a single load.
16915       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16916                                        Ptr, Ld->getPointerInfo(),
16917                                        Ld->isVolatile(), Ld->isNonTemporal(),
16918                                        Ld->isInvariant(), Ld->getAlignment());
16919       Chains.push_back(ScalarLoad.getValue(1));
16920       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16921       // another round of DAGCombining.
16922       if (i == 0)
16923         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16924       else
16925         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16926                           ScalarLoad, DAG.getIntPtrConstant(i));
16927
16928       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16929     }
16930
16931     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16932                                Chains.size());
16933
16934     // Bitcast the loaded value to a vector of the original element type, in
16935     // the size of the target vector type.
16936     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16937     unsigned SizeRatio = RegSz/MemSz;
16938
16939     if (Ext == ISD::SEXTLOAD) {
16940       // If we have SSE4.1 we can directly emit a VSEXT node.
16941       if (Subtarget->hasSSE41()) {
16942         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16943         return DCI.CombineTo(N, Sext, TF, true);
16944       }
16945
16946       // Otherwise we'll shuffle the small elements in the high bits of the
16947       // larger type and perform an arithmetic shift. If the shift is not legal
16948       // it's better to scalarize.
16949       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16950         return SDValue();
16951
16952       // Redistribute the loaded elements into the different locations.
16953       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16954       for (unsigned i = 0; i != NumElems; ++i)
16955         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16956
16957       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16958                                            DAG.getUNDEF(WideVecVT),
16959                                            &ShuffleVec[0]);
16960
16961       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16962
16963       // Build the arithmetic shift.
16964       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16965                      MemVT.getVectorElementType().getSizeInBits();
16966       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16967                           DAG.getConstant(Amt, RegVT));
16968
16969       return DCI.CombineTo(N, Shuff, TF, true);
16970     }
16971
16972     // Redistribute the loaded elements into the different locations.
16973     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16974     for (unsigned i = 0; i != NumElems; ++i)
16975       ShuffleVec[i*SizeRatio] = i;
16976
16977     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16978                                          DAG.getUNDEF(WideVecVT),
16979                                          &ShuffleVec[0]);
16980
16981     // Bitcast to the requested type.
16982     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16983     // Replace the original load with the new sequence
16984     // and return the new chain.
16985     return DCI.CombineTo(N, Shuff, TF, true);
16986   }
16987
16988   return SDValue();
16989 }
16990
16991 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16992 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16993                                    const X86Subtarget *Subtarget) {
16994   StoreSDNode *St = cast<StoreSDNode>(N);
16995   EVT VT = St->getValue().getValueType();
16996   EVT StVT = St->getMemoryVT();
16997   DebugLoc dl = St->getDebugLoc();
16998   SDValue StoredVal = St->getOperand(1);
16999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17000
17001   // If we are saving a concatenation of two XMM registers, perform two stores.
17002   // On Sandy Bridge, 256-bit memory operations are executed by two
17003   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17004   // memory  operation.
17005   unsigned Alignment = St->getAlignment();
17006   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17007   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17008       StVT == VT && !IsAligned) {
17009     unsigned NumElems = VT.getVectorNumElements();
17010     if (NumElems < 2)
17011       return SDValue();
17012
17013     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17014     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17015
17016     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17017     SDValue Ptr0 = St->getBasePtr();
17018     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17019
17020     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17021                                 St->getPointerInfo(), St->isVolatile(),
17022                                 St->isNonTemporal(), Alignment);
17023     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17024                                 St->getPointerInfo(), St->isVolatile(),
17025                                 St->isNonTemporal(),
17026                                 std::min(16U, Alignment));
17027     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17028   }
17029
17030   // Optimize trunc store (of multiple scalars) to shuffle and store.
17031   // First, pack all of the elements in one place. Next, store to memory
17032   // in fewer chunks.
17033   if (St->isTruncatingStore() && VT.isVector()) {
17034     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17035     unsigned NumElems = VT.getVectorNumElements();
17036     assert(StVT != VT && "Cannot truncate to the same type");
17037     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17038     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17039
17040     // From, To sizes and ElemCount must be pow of two
17041     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17042     // We are going to use the original vector elt for storing.
17043     // Accumulated smaller vector elements must be a multiple of the store size.
17044     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17045
17046     unsigned SizeRatio  = FromSz / ToSz;
17047
17048     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17049
17050     // Create a type on which we perform the shuffle
17051     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17052             StVT.getScalarType(), NumElems*SizeRatio);
17053
17054     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17055
17056     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17057     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17058     for (unsigned i = 0; i != NumElems; ++i)
17059       ShuffleVec[i] = i * SizeRatio;
17060
17061     // Can't shuffle using an illegal type.
17062     if (!TLI.isTypeLegal(WideVecVT))
17063       return SDValue();
17064
17065     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17066                                          DAG.getUNDEF(WideVecVT),
17067                                          &ShuffleVec[0]);
17068     // At this point all of the data is stored at the bottom of the
17069     // register. We now need to save it to mem.
17070
17071     // Find the largest store unit
17072     MVT StoreType = MVT::i8;
17073     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17074          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17075       MVT Tp = (MVT::SimpleValueType)tp;
17076       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17077         StoreType = Tp;
17078     }
17079
17080     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17081     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17082         (64 <= NumElems * ToSz))
17083       StoreType = MVT::f64;
17084
17085     // Bitcast the original vector into a vector of store-size units
17086     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17087             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17088     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17089     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17090     SmallVector<SDValue, 8> Chains;
17091     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17092                                         TLI.getPointerTy());
17093     SDValue Ptr = St->getBasePtr();
17094
17095     // Perform one or more big stores into memory.
17096     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17097       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17098                                    StoreType, ShuffWide,
17099                                    DAG.getIntPtrConstant(i));
17100       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17101                                 St->getPointerInfo(), St->isVolatile(),
17102                                 St->isNonTemporal(), St->getAlignment());
17103       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17104       Chains.push_back(Ch);
17105     }
17106
17107     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17108                                Chains.size());
17109   }
17110
17111   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17112   // the FP state in cases where an emms may be missing.
17113   // A preferable solution to the general problem is to figure out the right
17114   // places to insert EMMS.  This qualifies as a quick hack.
17115
17116   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17117   if (VT.getSizeInBits() != 64)
17118     return SDValue();
17119
17120   const Function *F = DAG.getMachineFunction().getFunction();
17121   bool NoImplicitFloatOps = F->getAttributes().
17122     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17123   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17124                      && Subtarget->hasSSE2();
17125   if ((VT.isVector() ||
17126        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17127       isa<LoadSDNode>(St->getValue()) &&
17128       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17129       St->getChain().hasOneUse() && !St->isVolatile()) {
17130     SDNode* LdVal = St->getValue().getNode();
17131     LoadSDNode *Ld = 0;
17132     int TokenFactorIndex = -1;
17133     SmallVector<SDValue, 8> Ops;
17134     SDNode* ChainVal = St->getChain().getNode();
17135     // Must be a store of a load.  We currently handle two cases:  the load
17136     // is a direct child, and it's under an intervening TokenFactor.  It is
17137     // possible to dig deeper under nested TokenFactors.
17138     if (ChainVal == LdVal)
17139       Ld = cast<LoadSDNode>(St->getChain());
17140     else if (St->getValue().hasOneUse() &&
17141              ChainVal->getOpcode() == ISD::TokenFactor) {
17142       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17143         if (ChainVal->getOperand(i).getNode() == LdVal) {
17144           TokenFactorIndex = i;
17145           Ld = cast<LoadSDNode>(St->getValue());
17146         } else
17147           Ops.push_back(ChainVal->getOperand(i));
17148       }
17149     }
17150
17151     if (!Ld || !ISD::isNormalLoad(Ld))
17152       return SDValue();
17153
17154     // If this is not the MMX case, i.e. we are just turning i64 load/store
17155     // into f64 load/store, avoid the transformation if there are multiple
17156     // uses of the loaded value.
17157     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17158       return SDValue();
17159
17160     DebugLoc LdDL = Ld->getDebugLoc();
17161     DebugLoc StDL = N->getDebugLoc();
17162     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17163     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17164     // pair instead.
17165     if (Subtarget->is64Bit() || F64IsLegal) {
17166       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17167       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17168                                   Ld->getPointerInfo(), Ld->isVolatile(),
17169                                   Ld->isNonTemporal(), Ld->isInvariant(),
17170                                   Ld->getAlignment());
17171       SDValue NewChain = NewLd.getValue(1);
17172       if (TokenFactorIndex != -1) {
17173         Ops.push_back(NewChain);
17174         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17175                                Ops.size());
17176       }
17177       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17178                           St->getPointerInfo(),
17179                           St->isVolatile(), St->isNonTemporal(),
17180                           St->getAlignment());
17181     }
17182
17183     // Otherwise, lower to two pairs of 32-bit loads / stores.
17184     SDValue LoAddr = Ld->getBasePtr();
17185     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17186                                  DAG.getConstant(4, MVT::i32));
17187
17188     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17189                                Ld->getPointerInfo(),
17190                                Ld->isVolatile(), Ld->isNonTemporal(),
17191                                Ld->isInvariant(), Ld->getAlignment());
17192     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17193                                Ld->getPointerInfo().getWithOffset(4),
17194                                Ld->isVolatile(), Ld->isNonTemporal(),
17195                                Ld->isInvariant(),
17196                                MinAlign(Ld->getAlignment(), 4));
17197
17198     SDValue NewChain = LoLd.getValue(1);
17199     if (TokenFactorIndex != -1) {
17200       Ops.push_back(LoLd);
17201       Ops.push_back(HiLd);
17202       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17203                              Ops.size());
17204     }
17205
17206     LoAddr = St->getBasePtr();
17207     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17208                          DAG.getConstant(4, MVT::i32));
17209
17210     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17211                                 St->getPointerInfo(),
17212                                 St->isVolatile(), St->isNonTemporal(),
17213                                 St->getAlignment());
17214     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17215                                 St->getPointerInfo().getWithOffset(4),
17216                                 St->isVolatile(),
17217                                 St->isNonTemporal(),
17218                                 MinAlign(St->getAlignment(), 4));
17219     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17220   }
17221   return SDValue();
17222 }
17223
17224 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17225 /// and return the operands for the horizontal operation in LHS and RHS.  A
17226 /// horizontal operation performs the binary operation on successive elements
17227 /// of its first operand, then on successive elements of its second operand,
17228 /// returning the resulting values in a vector.  For example, if
17229 ///   A = < float a0, float a1, float a2, float a3 >
17230 /// and
17231 ///   B = < float b0, float b1, float b2, float b3 >
17232 /// then the result of doing a horizontal operation on A and B is
17233 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17234 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17235 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17236 /// set to A, RHS to B, and the routine returns 'true'.
17237 /// Note that the binary operation should have the property that if one of the
17238 /// operands is UNDEF then the result is UNDEF.
17239 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17240   // Look for the following pattern: if
17241   //   A = < float a0, float a1, float a2, float a3 >
17242   //   B = < float b0, float b1, float b2, float b3 >
17243   // and
17244   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17245   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17246   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17247   // which is A horizontal-op B.
17248
17249   // At least one of the operands should be a vector shuffle.
17250   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17251       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17252     return false;
17253
17254   EVT VT = LHS.getValueType();
17255
17256   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17257          "Unsupported vector type for horizontal add/sub");
17258
17259   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17260   // operate independently on 128-bit lanes.
17261   unsigned NumElts = VT.getVectorNumElements();
17262   unsigned NumLanes = VT.getSizeInBits()/128;
17263   unsigned NumLaneElts = NumElts / NumLanes;
17264   assert((NumLaneElts % 2 == 0) &&
17265          "Vector type should have an even number of elements in each lane");
17266   unsigned HalfLaneElts = NumLaneElts/2;
17267
17268   // View LHS in the form
17269   //   LHS = VECTOR_SHUFFLE A, B, LMask
17270   // If LHS is not a shuffle then pretend it is the shuffle
17271   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17272   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17273   // type VT.
17274   SDValue A, B;
17275   SmallVector<int, 16> LMask(NumElts);
17276   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17277     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17278       A = LHS.getOperand(0);
17279     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17280       B = LHS.getOperand(1);
17281     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17282     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17283   } else {
17284     if (LHS.getOpcode() != ISD::UNDEF)
17285       A = LHS;
17286     for (unsigned i = 0; i != NumElts; ++i)
17287       LMask[i] = i;
17288   }
17289
17290   // Likewise, view RHS in the form
17291   //   RHS = VECTOR_SHUFFLE C, D, RMask
17292   SDValue C, D;
17293   SmallVector<int, 16> RMask(NumElts);
17294   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17295     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17296       C = RHS.getOperand(0);
17297     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17298       D = RHS.getOperand(1);
17299     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17300     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17301   } else {
17302     if (RHS.getOpcode() != ISD::UNDEF)
17303       C = RHS;
17304     for (unsigned i = 0; i != NumElts; ++i)
17305       RMask[i] = i;
17306   }
17307
17308   // Check that the shuffles are both shuffling the same vectors.
17309   if (!(A == C && B == D) && !(A == D && B == C))
17310     return false;
17311
17312   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17313   if (!A.getNode() && !B.getNode())
17314     return false;
17315
17316   // If A and B occur in reverse order in RHS, then "swap" them (which means
17317   // rewriting the mask).
17318   if (A != C)
17319     CommuteVectorShuffleMask(RMask, NumElts);
17320
17321   // At this point LHS and RHS are equivalent to
17322   //   LHS = VECTOR_SHUFFLE A, B, LMask
17323   //   RHS = VECTOR_SHUFFLE A, B, RMask
17324   // Check that the masks correspond to performing a horizontal operation.
17325   for (unsigned i = 0; i != NumElts; ++i) {
17326     int LIdx = LMask[i], RIdx = RMask[i];
17327
17328     // Ignore any UNDEF components.
17329     if (LIdx < 0 || RIdx < 0 ||
17330         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17331         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17332       continue;
17333
17334     // Check that successive elements are being operated on.  If not, this is
17335     // not a horizontal operation.
17336     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17337     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17338     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17339     if (!(LIdx == Index && RIdx == Index + 1) &&
17340         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17341       return false;
17342   }
17343
17344   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17345   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17346   return true;
17347 }
17348
17349 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17350 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17351                                   const X86Subtarget *Subtarget) {
17352   EVT VT = N->getValueType(0);
17353   SDValue LHS = N->getOperand(0);
17354   SDValue RHS = N->getOperand(1);
17355
17356   // Try to synthesize horizontal adds from adds of shuffles.
17357   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17358        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17359       isHorizontalBinOp(LHS, RHS, true))
17360     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
17361   return SDValue();
17362 }
17363
17364 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17365 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17366                                   const X86Subtarget *Subtarget) {
17367   EVT VT = N->getValueType(0);
17368   SDValue LHS = N->getOperand(0);
17369   SDValue RHS = N->getOperand(1);
17370
17371   // Try to synthesize horizontal subs from subs of shuffles.
17372   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17373        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17374       isHorizontalBinOp(LHS, RHS, false))
17375     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
17376   return SDValue();
17377 }
17378
17379 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17380 /// X86ISD::FXOR nodes.
17381 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17382   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17383   // F[X]OR(0.0, x) -> x
17384   // F[X]OR(x, 0.0) -> x
17385   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17386     if (C->getValueAPF().isPosZero())
17387       return N->getOperand(1);
17388   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17389     if (C->getValueAPF().isPosZero())
17390       return N->getOperand(0);
17391   return SDValue();
17392 }
17393
17394 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17395 /// X86ISD::FMAX nodes.
17396 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17397   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17398
17399   // Only perform optimizations if UnsafeMath is used.
17400   if (!DAG.getTarget().Options.UnsafeFPMath)
17401     return SDValue();
17402
17403   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17404   // into FMINC and FMAXC, which are Commutative operations.
17405   unsigned NewOp = 0;
17406   switch (N->getOpcode()) {
17407     default: llvm_unreachable("unknown opcode");
17408     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17409     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17410   }
17411
17412   return DAG.getNode(NewOp, N->getDebugLoc(), N->getValueType(0),
17413                      N->getOperand(0), N->getOperand(1));
17414 }
17415
17416 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17417 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17418   // FAND(0.0, x) -> 0.0
17419   // FAND(x, 0.0) -> 0.0
17420   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17421     if (C->getValueAPF().isPosZero())
17422       return N->getOperand(0);
17423   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17424     if (C->getValueAPF().isPosZero())
17425       return N->getOperand(1);
17426   return SDValue();
17427 }
17428
17429 static SDValue PerformBTCombine(SDNode *N,
17430                                 SelectionDAG &DAG,
17431                                 TargetLowering::DAGCombinerInfo &DCI) {
17432   // BT ignores high bits in the bit index operand.
17433   SDValue Op1 = N->getOperand(1);
17434   if (Op1.hasOneUse()) {
17435     unsigned BitWidth = Op1.getValueSizeInBits();
17436     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17437     APInt KnownZero, KnownOne;
17438     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17439                                           !DCI.isBeforeLegalizeOps());
17440     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17441     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17442         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17443       DCI.CommitTargetLoweringOpt(TLO);
17444   }
17445   return SDValue();
17446 }
17447
17448 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17449   SDValue Op = N->getOperand(0);
17450   if (Op.getOpcode() == ISD::BITCAST)
17451     Op = Op.getOperand(0);
17452   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17453   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17454       VT.getVectorElementType().getSizeInBits() ==
17455       OpVT.getVectorElementType().getSizeInBits()) {
17456     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
17457   }
17458   return SDValue();
17459 }
17460
17461 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 
17462                                                const X86Subtarget *Subtarget) {
17463   EVT VT = N->getValueType(0);
17464   if (!VT.isVector())
17465     return SDValue();
17466
17467   SDValue N0 = N->getOperand(0);
17468   SDValue N1 = N->getOperand(1);
17469   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17470   DebugLoc dl = N->getDebugLoc();
17471
17472   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17473   // both SSE and AVX2 since there is no sign-extended shift right
17474   // operation on a vector with 64-bit elements.
17475   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17476   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17477   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17478       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17479     SDValue N00 = N0.getOperand(0);
17480
17481     // EXTLOAD has a better solution on AVX2, 
17482     // it may be replaced with X86ISD::VSEXT node.
17483     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17484       if (!ISD::isNormalLoad(N00.getNode()))
17485         return SDValue();
17486
17487     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17488         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, 
17489                                   N00, N1);
17490       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17491     }
17492   }
17493   return SDValue();
17494 }
17495
17496 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17497                                   TargetLowering::DAGCombinerInfo &DCI,
17498                                   const X86Subtarget *Subtarget) {
17499   if (!DCI.isBeforeLegalizeOps())
17500     return SDValue();
17501
17502   if (!Subtarget->hasFp256())
17503     return SDValue();
17504
17505   EVT VT = N->getValueType(0);
17506   if (VT.isVector() && VT.getSizeInBits() == 256) {
17507     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17508     if (R.getNode())
17509       return R;
17510   }
17511
17512   return SDValue();
17513 }
17514
17515 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17516                                  const X86Subtarget* Subtarget) {
17517   DebugLoc dl = N->getDebugLoc();
17518   EVT VT = N->getValueType(0);
17519
17520   // Let legalize expand this if it isn't a legal type yet.
17521   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17522     return SDValue();
17523
17524   EVT ScalarVT = VT.getScalarType();
17525   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17526       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17527     return SDValue();
17528
17529   SDValue A = N->getOperand(0);
17530   SDValue B = N->getOperand(1);
17531   SDValue C = N->getOperand(2);
17532
17533   bool NegA = (A.getOpcode() == ISD::FNEG);
17534   bool NegB = (B.getOpcode() == ISD::FNEG);
17535   bool NegC = (C.getOpcode() == ISD::FNEG);
17536
17537   // Negative multiplication when NegA xor NegB
17538   bool NegMul = (NegA != NegB);
17539   if (NegA)
17540     A = A.getOperand(0);
17541   if (NegB)
17542     B = B.getOperand(0);
17543   if (NegC)
17544     C = C.getOperand(0);
17545
17546   unsigned Opcode;
17547   if (!NegMul)
17548     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17549   else
17550     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17551
17552   return DAG.getNode(Opcode, dl, VT, A, B, C);
17553 }
17554
17555 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17556                                   TargetLowering::DAGCombinerInfo &DCI,
17557                                   const X86Subtarget *Subtarget) {
17558   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17559   //           (and (i32 x86isd::setcc_carry), 1)
17560   // This eliminates the zext. This transformation is necessary because
17561   // ISD::SETCC is always legalized to i8.
17562   DebugLoc dl = N->getDebugLoc();
17563   SDValue N0 = N->getOperand(0);
17564   EVT VT = N->getValueType(0);
17565
17566   if (N0.getOpcode() == ISD::AND &&
17567       N0.hasOneUse() &&
17568       N0.getOperand(0).hasOneUse()) {
17569     SDValue N00 = N0.getOperand(0);
17570     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17571       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17572       if (!C || C->getZExtValue() != 1)
17573         return SDValue();
17574       return DAG.getNode(ISD::AND, dl, VT,
17575                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17576                                      N00.getOperand(0), N00.getOperand(1)),
17577                          DAG.getConstant(1, VT));
17578     }
17579   }
17580
17581   if (VT.is256BitVector()) {
17582     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17583     if (R.getNode())
17584       return R;
17585   }
17586
17587   return SDValue();
17588 }
17589
17590 // Optimize x == -y --> x+y == 0
17591 //          x != -y --> x+y != 0
17592 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17593   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17594   SDValue LHS = N->getOperand(0);
17595   SDValue RHS = N->getOperand(1);
17596
17597   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17598     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17599       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17600         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17601                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17602         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17603                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17604       }
17605   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17606     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17607       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17608         SDValue addV = DAG.getNode(ISD::ADD, N->getDebugLoc(),
17609                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17610         return DAG.getSetCC(N->getDebugLoc(), N->getValueType(0),
17611                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17612       }
17613   return SDValue();
17614 }
17615
17616 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17617 // as "sbb reg,reg", since it can be extended without zext and produces
17618 // an all-ones bit which is more useful than 0/1 in some cases.
17619 static SDValue MaterializeSETB(DebugLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17620   return DAG.getNode(ISD::AND, DL, MVT::i8,
17621                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17622                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17623                      DAG.getConstant(1, MVT::i8));
17624 }
17625
17626 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17627 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17628                                    TargetLowering::DAGCombinerInfo &DCI,
17629                                    const X86Subtarget *Subtarget) {
17630   DebugLoc DL = N->getDebugLoc();
17631   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17632   SDValue EFLAGS = N->getOperand(1);
17633
17634   if (CC == X86::COND_A) {
17635     // Try to convert COND_A into COND_B in an attempt to facilitate
17636     // materializing "setb reg".
17637     //
17638     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17639     // cannot take an immediate as its first operand.
17640     //
17641     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17642         EFLAGS.getValueType().isInteger() &&
17643         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17644       SDValue NewSub = DAG.getNode(X86ISD::SUB, EFLAGS.getDebugLoc(),
17645                                    EFLAGS.getNode()->getVTList(),
17646                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17647       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17648       return MaterializeSETB(DL, NewEFLAGS, DAG);
17649     }
17650   }
17651
17652   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17653   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17654   // cases.
17655   if (CC == X86::COND_B)
17656     return MaterializeSETB(DL, EFLAGS, DAG);
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::SETCC, DL, N->getVTList(), Cond, Flags);
17664   }
17665
17666   return SDValue();
17667 }
17668
17669 // Optimize branch condition evaluation.
17670 //
17671 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17672                                     TargetLowering::DAGCombinerInfo &DCI,
17673                                     const X86Subtarget *Subtarget) {
17674   DebugLoc DL = N->getDebugLoc();
17675   SDValue Chain = N->getOperand(0);
17676   SDValue Dest = N->getOperand(1);
17677   SDValue EFLAGS = N->getOperand(3);
17678   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17679
17680   SDValue Flags;
17681
17682   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17683   if (Flags.getNode()) {
17684     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17685     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17686                        Flags);
17687   }
17688
17689   return SDValue();
17690 }
17691
17692 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17693                                         const X86TargetLowering *XTLI) {
17694   SDValue Op0 = N->getOperand(0);
17695   EVT InVT = Op0->getValueType(0);
17696
17697   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17698   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17699     DebugLoc dl = N->getDebugLoc();
17700     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17701     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17702     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17703   }
17704
17705   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17706   // a 32-bit target where SSE doesn't support i64->FP operations.
17707   if (Op0.getOpcode() == ISD::LOAD) {
17708     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17709     EVT VT = Ld->getValueType(0);
17710     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17711         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17712         !XTLI->getSubtarget()->is64Bit() &&
17713         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17714       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17715                                           Ld->getChain(), Op0, DAG);
17716       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17717       return FILDChain;
17718     }
17719   }
17720   return SDValue();
17721 }
17722
17723 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17724 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17725                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17726   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17727   // the result is either zero or one (depending on the input carry bit).
17728   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17729   if (X86::isZeroNode(N->getOperand(0)) &&
17730       X86::isZeroNode(N->getOperand(1)) &&
17731       // We don't have a good way to replace an EFLAGS use, so only do this when
17732       // dead right now.
17733       SDValue(N, 1).use_empty()) {
17734     DebugLoc DL = N->getDebugLoc();
17735     EVT VT = N->getValueType(0);
17736     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17737     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17738                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17739                                            DAG.getConstant(X86::COND_B,MVT::i8),
17740                                            N->getOperand(2)),
17741                                DAG.getConstant(1, VT));
17742     return DCI.CombineTo(N, Res1, CarryOut);
17743   }
17744
17745   return SDValue();
17746 }
17747
17748 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17749 //      (add Y, (setne X, 0)) -> sbb -1, Y
17750 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17751 //      (sub (setne X, 0), Y) -> adc -1, Y
17752 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17753   DebugLoc DL = N->getDebugLoc();
17754
17755   // Look through ZExts.
17756   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17757   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17758     return SDValue();
17759
17760   SDValue SetCC = Ext.getOperand(0);
17761   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17762     return SDValue();
17763
17764   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17765   if (CC != X86::COND_E && CC != X86::COND_NE)
17766     return SDValue();
17767
17768   SDValue Cmp = SetCC.getOperand(1);
17769   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17770       !X86::isZeroNode(Cmp.getOperand(1)) ||
17771       !Cmp.getOperand(0).getValueType().isInteger())
17772     return SDValue();
17773
17774   SDValue CmpOp0 = Cmp.getOperand(0);
17775   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17776                                DAG.getConstant(1, CmpOp0.getValueType()));
17777
17778   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17779   if (CC == X86::COND_NE)
17780     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17781                        DL, OtherVal.getValueType(), OtherVal,
17782                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17783   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17784                      DL, OtherVal.getValueType(), OtherVal,
17785                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17786 }
17787
17788 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17789 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17790                                  const X86Subtarget *Subtarget) {
17791   EVT VT = N->getValueType(0);
17792   SDValue Op0 = N->getOperand(0);
17793   SDValue Op1 = N->getOperand(1);
17794
17795   // Try to synthesize horizontal adds from adds of shuffles.
17796   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17797        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17798       isHorizontalBinOp(Op0, Op1, true))
17799     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
17800
17801   return OptimizeConditionalInDecrement(N, DAG);
17802 }
17803
17804 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17805                                  const X86Subtarget *Subtarget) {
17806   SDValue Op0 = N->getOperand(0);
17807   SDValue Op1 = N->getOperand(1);
17808
17809   // X86 can't encode an immediate LHS of a sub. See if we can push the
17810   // negation into a preceding instruction.
17811   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17812     // If the RHS of the sub is a XOR with one use and a constant, invert the
17813     // immediate. Then add one to the LHS of the sub so we can turn
17814     // X-Y -> X+~Y+1, saving one register.
17815     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17816         isa<ConstantSDNode>(Op1.getOperand(1))) {
17817       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17818       EVT VT = Op0.getValueType();
17819       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
17820                                    Op1.getOperand(0),
17821                                    DAG.getConstant(~XorC, VT));
17822       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
17823                          DAG.getConstant(C->getAPIntValue()+1, VT));
17824     }
17825   }
17826
17827   // Try to synthesize horizontal adds from adds of shuffles.
17828   EVT VT = N->getValueType(0);
17829   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17830        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17831       isHorizontalBinOp(Op0, Op1, true))
17832     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
17833
17834   return OptimizeConditionalInDecrement(N, DAG);
17835 }
17836
17837 /// performVZEXTCombine - Performs build vector combines
17838 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17839                                         TargetLowering::DAGCombinerInfo &DCI,
17840                                         const X86Subtarget *Subtarget) {
17841   // (vzext (bitcast (vzext (x)) -> (vzext x)
17842   SDValue In = N->getOperand(0);
17843   while (In.getOpcode() == ISD::BITCAST)
17844     In = In.getOperand(0);
17845
17846   if (In.getOpcode() != X86ISD::VZEXT)
17847     return SDValue();
17848
17849   return DAG.getNode(X86ISD::VZEXT, N->getDebugLoc(), N->getValueType(0),
17850                      In.getOperand(0));
17851 }
17852
17853 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17854                                              DAGCombinerInfo &DCI) const {
17855   SelectionDAG &DAG = DCI.DAG;
17856   switch (N->getOpcode()) {
17857   default: break;
17858   case ISD::EXTRACT_VECTOR_ELT:
17859     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17860   case ISD::VSELECT:
17861   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17862   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17863   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17864   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17865   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17866   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17867   case ISD::SHL:
17868   case ISD::SRA:
17869   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17870   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17871   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17872   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17873   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17874   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17875   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17876   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17877   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17878   case X86ISD::FXOR:
17879   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17880   case X86ISD::FMIN:
17881   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17882   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17883   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17884   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17885   case ISD::ANY_EXTEND:
17886   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17887   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17888   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17889   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17890   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17891   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17892   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17893   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17894   case X86ISD::SHUFP:       // Handle all target specific shuffles
17895   case X86ISD::PALIGNR:
17896   case X86ISD::UNPCKH:
17897   case X86ISD::UNPCKL:
17898   case X86ISD::MOVHLPS:
17899   case X86ISD::MOVLHPS:
17900   case X86ISD::PSHUFD:
17901   case X86ISD::PSHUFHW:
17902   case X86ISD::PSHUFLW:
17903   case X86ISD::MOVSS:
17904   case X86ISD::MOVSD:
17905   case X86ISD::VPERMILP:
17906   case X86ISD::VPERM2X128:
17907   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17908   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17909   }
17910
17911   return SDValue();
17912 }
17913
17914 /// isTypeDesirableForOp - Return true if the target has native support for
17915 /// the specified value type and it is 'desirable' to use the type for the
17916 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17917 /// instruction encodings are longer and some i16 instructions are slow.
17918 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17919   if (!isTypeLegal(VT))
17920     return false;
17921   if (VT != MVT::i16)
17922     return true;
17923
17924   switch (Opc) {
17925   default:
17926     return true;
17927   case ISD::LOAD:
17928   case ISD::SIGN_EXTEND:
17929   case ISD::ZERO_EXTEND:
17930   case ISD::ANY_EXTEND:
17931   case ISD::SHL:
17932   case ISD::SRL:
17933   case ISD::SUB:
17934   case ISD::ADD:
17935   case ISD::MUL:
17936   case ISD::AND:
17937   case ISD::OR:
17938   case ISD::XOR:
17939     return false;
17940   }
17941 }
17942
17943 /// IsDesirableToPromoteOp - This method query the target whether it is
17944 /// beneficial for dag combiner to promote the specified node. If true, it
17945 /// should return the desired promotion type by reference.
17946 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17947   EVT VT = Op.getValueType();
17948   if (VT != MVT::i16)
17949     return false;
17950
17951   bool Promote = false;
17952   bool Commute = false;
17953   switch (Op.getOpcode()) {
17954   default: break;
17955   case ISD::LOAD: {
17956     LoadSDNode *LD = cast<LoadSDNode>(Op);
17957     // If the non-extending load has a single use and it's not live out, then it
17958     // might be folded.
17959     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17960                                                      Op.hasOneUse()*/) {
17961       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17962              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17963         // The only case where we'd want to promote LOAD (rather then it being
17964         // promoted as an operand is when it's only use is liveout.
17965         if (UI->getOpcode() != ISD::CopyToReg)
17966           return false;
17967       }
17968     }
17969     Promote = true;
17970     break;
17971   }
17972   case ISD::SIGN_EXTEND:
17973   case ISD::ZERO_EXTEND:
17974   case ISD::ANY_EXTEND:
17975     Promote = true;
17976     break;
17977   case ISD::SHL:
17978   case ISD::SRL: {
17979     SDValue N0 = Op.getOperand(0);
17980     // Look out for (store (shl (load), x)).
17981     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17982       return false;
17983     Promote = true;
17984     break;
17985   }
17986   case ISD::ADD:
17987   case ISD::MUL:
17988   case ISD::AND:
17989   case ISD::OR:
17990   case ISD::XOR:
17991     Commute = true;
17992     // fallthrough
17993   case ISD::SUB: {
17994     SDValue N0 = Op.getOperand(0);
17995     SDValue N1 = Op.getOperand(1);
17996     if (!Commute && MayFoldLoad(N1))
17997       return false;
17998     // Avoid disabling potential load folding opportunities.
17999     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18000       return false;
18001     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18002       return false;
18003     Promote = true;
18004   }
18005   }
18006
18007   PVT = MVT::i32;
18008   return Promote;
18009 }
18010
18011 //===----------------------------------------------------------------------===//
18012 //                           X86 Inline Assembly Support
18013 //===----------------------------------------------------------------------===//
18014
18015 namespace {
18016   // Helper to match a string separated by whitespace.
18017   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18018     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18019
18020     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18021       StringRef piece(*args[i]);
18022       if (!s.startswith(piece)) // Check if the piece matches.
18023         return false;
18024
18025       s = s.substr(piece.size());
18026       StringRef::size_type pos = s.find_first_not_of(" \t");
18027       if (pos == 0) // We matched a prefix.
18028         return false;
18029
18030       s = s.substr(pos);
18031     }
18032
18033     return s.empty();
18034   }
18035   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18036 }
18037
18038 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18039   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18040
18041   std::string AsmStr = IA->getAsmString();
18042
18043   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18044   if (!Ty || Ty->getBitWidth() % 16 != 0)
18045     return false;
18046
18047   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18048   SmallVector<StringRef, 4> AsmPieces;
18049   SplitString(AsmStr, AsmPieces, ";\n");
18050
18051   switch (AsmPieces.size()) {
18052   default: return false;
18053   case 1:
18054     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18055     // we will turn this bswap into something that will be lowered to logical
18056     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18057     // lower so don't worry about this.
18058     // bswap $0
18059     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18060         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18061         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18062         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18063         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18064         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18065       // No need to check constraints, nothing other than the equivalent of
18066       // "=r,0" would be valid here.
18067       return IntrinsicLowering::LowerToByteSwap(CI);
18068     }
18069
18070     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18071     if (CI->getType()->isIntegerTy(16) &&
18072         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18073         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18074          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18075       AsmPieces.clear();
18076       const std::string &ConstraintsStr = IA->getConstraintString();
18077       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18078       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18079       if (AsmPieces.size() == 4 &&
18080           AsmPieces[0] == "~{cc}" &&
18081           AsmPieces[1] == "~{dirflag}" &&
18082           AsmPieces[2] == "~{flags}" &&
18083           AsmPieces[3] == "~{fpsr}")
18084       return IntrinsicLowering::LowerToByteSwap(CI);
18085     }
18086     break;
18087   case 3:
18088     if (CI->getType()->isIntegerTy(32) &&
18089         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18090         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18091         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18092         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18093       AsmPieces.clear();
18094       const std::string &ConstraintsStr = IA->getConstraintString();
18095       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18096       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18097       if (AsmPieces.size() == 4 &&
18098           AsmPieces[0] == "~{cc}" &&
18099           AsmPieces[1] == "~{dirflag}" &&
18100           AsmPieces[2] == "~{flags}" &&
18101           AsmPieces[3] == "~{fpsr}")
18102         return IntrinsicLowering::LowerToByteSwap(CI);
18103     }
18104
18105     if (CI->getType()->isIntegerTy(64)) {
18106       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18107       if (Constraints.size() >= 2 &&
18108           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18109           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18110         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18111         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18112             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18113             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18114           return IntrinsicLowering::LowerToByteSwap(CI);
18115       }
18116     }
18117     break;
18118   }
18119   return false;
18120 }
18121
18122 /// getConstraintType - Given a constraint letter, return the type of
18123 /// constraint it is for this target.
18124 X86TargetLowering::ConstraintType
18125 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18126   if (Constraint.size() == 1) {
18127     switch (Constraint[0]) {
18128     case 'R':
18129     case 'q':
18130     case 'Q':
18131     case 'f':
18132     case 't':
18133     case 'u':
18134     case 'y':
18135     case 'x':
18136     case 'Y':
18137     case 'l':
18138       return C_RegisterClass;
18139     case 'a':
18140     case 'b':
18141     case 'c':
18142     case 'd':
18143     case 'S':
18144     case 'D':
18145     case 'A':
18146       return C_Register;
18147     case 'I':
18148     case 'J':
18149     case 'K':
18150     case 'L':
18151     case 'M':
18152     case 'N':
18153     case 'G':
18154     case 'C':
18155     case 'e':
18156     case 'Z':
18157       return C_Other;
18158     default:
18159       break;
18160     }
18161   }
18162   return TargetLowering::getConstraintType(Constraint);
18163 }
18164
18165 /// Examine constraint type and operand type and determine a weight value.
18166 /// This object must already have been set up with the operand type
18167 /// and the current alternative constraint selected.
18168 TargetLowering::ConstraintWeight
18169   X86TargetLowering::getSingleConstraintMatchWeight(
18170     AsmOperandInfo &info, const char *constraint) const {
18171   ConstraintWeight weight = CW_Invalid;
18172   Value *CallOperandVal = info.CallOperandVal;
18173     // If we don't have a value, we can't do a match,
18174     // but allow it at the lowest weight.
18175   if (CallOperandVal == NULL)
18176     return CW_Default;
18177   Type *type = CallOperandVal->getType();
18178   // Look at the constraint type.
18179   switch (*constraint) {
18180   default:
18181     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18182   case 'R':
18183   case 'q':
18184   case 'Q':
18185   case 'a':
18186   case 'b':
18187   case 'c':
18188   case 'd':
18189   case 'S':
18190   case 'D':
18191   case 'A':
18192     if (CallOperandVal->getType()->isIntegerTy())
18193       weight = CW_SpecificReg;
18194     break;
18195   case 'f':
18196   case 't':
18197   case 'u':
18198     if (type->isFloatingPointTy())
18199       weight = CW_SpecificReg;
18200     break;
18201   case 'y':
18202     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18203       weight = CW_SpecificReg;
18204     break;
18205   case 'x':
18206   case 'Y':
18207     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18208         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18209       weight = CW_Register;
18210     break;
18211   case 'I':
18212     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18213       if (C->getZExtValue() <= 31)
18214         weight = CW_Constant;
18215     }
18216     break;
18217   case 'J':
18218     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18219       if (C->getZExtValue() <= 63)
18220         weight = CW_Constant;
18221     }
18222     break;
18223   case 'K':
18224     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18225       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18226         weight = CW_Constant;
18227     }
18228     break;
18229   case 'L':
18230     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18231       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18232         weight = CW_Constant;
18233     }
18234     break;
18235   case 'M':
18236     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18237       if (C->getZExtValue() <= 3)
18238         weight = CW_Constant;
18239     }
18240     break;
18241   case 'N':
18242     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18243       if (C->getZExtValue() <= 0xff)
18244         weight = CW_Constant;
18245     }
18246     break;
18247   case 'G':
18248   case 'C':
18249     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18250       weight = CW_Constant;
18251     }
18252     break;
18253   case 'e':
18254     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18255       if ((C->getSExtValue() >= -0x80000000LL) &&
18256           (C->getSExtValue() <= 0x7fffffffLL))
18257         weight = CW_Constant;
18258     }
18259     break;
18260   case 'Z':
18261     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18262       if (C->getZExtValue() <= 0xffffffff)
18263         weight = CW_Constant;
18264     }
18265     break;
18266   }
18267   return weight;
18268 }
18269
18270 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18271 /// with another that has more specific requirements based on the type of the
18272 /// corresponding operand.
18273 const char *X86TargetLowering::
18274 LowerXConstraint(EVT ConstraintVT) const {
18275   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18276   // 'f' like normal targets.
18277   if (ConstraintVT.isFloatingPoint()) {
18278     if (Subtarget->hasSSE2())
18279       return "Y";
18280     if (Subtarget->hasSSE1())
18281       return "x";
18282   }
18283
18284   return TargetLowering::LowerXConstraint(ConstraintVT);
18285 }
18286
18287 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18288 /// vector.  If it is invalid, don't add anything to Ops.
18289 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18290                                                      std::string &Constraint,
18291                                                      std::vector<SDValue>&Ops,
18292                                                      SelectionDAG &DAG) const {
18293   SDValue Result(0, 0);
18294
18295   // Only support length 1 constraints for now.
18296   if (Constraint.length() > 1) return;
18297
18298   char ConstraintLetter = Constraint[0];
18299   switch (ConstraintLetter) {
18300   default: break;
18301   case 'I':
18302     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18303       if (C->getZExtValue() <= 31) {
18304         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18305         break;
18306       }
18307     }
18308     return;
18309   case 'J':
18310     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18311       if (C->getZExtValue() <= 63) {
18312         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18313         break;
18314       }
18315     }
18316     return;
18317   case 'K':
18318     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18319       if (isInt<8>(C->getSExtValue())) {
18320         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18321         break;
18322       }
18323     }
18324     return;
18325   case 'N':
18326     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18327       if (C->getZExtValue() <= 255) {
18328         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18329         break;
18330       }
18331     }
18332     return;
18333   case 'e': {
18334     // 32-bit signed value
18335     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18336       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18337                                            C->getSExtValue())) {
18338         // Widen to 64 bits here to get it sign extended.
18339         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18340         break;
18341       }
18342     // FIXME gcc accepts some relocatable values here too, but only in certain
18343     // memory models; it's complicated.
18344     }
18345     return;
18346   }
18347   case 'Z': {
18348     // 32-bit unsigned value
18349     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18350       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18351                                            C->getZExtValue())) {
18352         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18353         break;
18354       }
18355     }
18356     // FIXME gcc accepts some relocatable values here too, but only in certain
18357     // memory models; it's complicated.
18358     return;
18359   }
18360   case 'i': {
18361     // Literal immediates are always ok.
18362     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18363       // Widen to 64 bits here to get it sign extended.
18364       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18365       break;
18366     }
18367
18368     // In any sort of PIC mode addresses need to be computed at runtime by
18369     // adding in a register or some sort of table lookup.  These can't
18370     // be used as immediates.
18371     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18372       return;
18373
18374     // If we are in non-pic codegen mode, we allow the address of a global (with
18375     // an optional displacement) to be used with 'i'.
18376     GlobalAddressSDNode *GA = 0;
18377     int64_t Offset = 0;
18378
18379     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18380     while (1) {
18381       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18382         Offset += GA->getOffset();
18383         break;
18384       } else if (Op.getOpcode() == ISD::ADD) {
18385         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18386           Offset += C->getZExtValue();
18387           Op = Op.getOperand(0);
18388           continue;
18389         }
18390       } else if (Op.getOpcode() == ISD::SUB) {
18391         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18392           Offset += -C->getZExtValue();
18393           Op = Op.getOperand(0);
18394           continue;
18395         }
18396       }
18397
18398       // Otherwise, this isn't something we can handle, reject it.
18399       return;
18400     }
18401
18402     const GlobalValue *GV = GA->getGlobal();
18403     // If we require an extra load to get this address, as in PIC mode, we
18404     // can't accept it.
18405     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18406                                                         getTargetMachine())))
18407       return;
18408
18409     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
18410                                         GA->getValueType(0), Offset);
18411     break;
18412   }
18413   }
18414
18415   if (Result.getNode()) {
18416     Ops.push_back(Result);
18417     return;
18418   }
18419   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18420 }
18421
18422 std::pair<unsigned, const TargetRegisterClass*>
18423 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18424                                                 EVT VT) const {
18425   // First, see if this is a constraint that directly corresponds to an LLVM
18426   // register class.
18427   if (Constraint.size() == 1) {
18428     // GCC Constraint Letters
18429     switch (Constraint[0]) {
18430     default: break;
18431       // TODO: Slight differences here in allocation order and leaving
18432       // RIP in the class. Do they matter any more here than they do
18433       // in the normal allocation?
18434     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18435       if (Subtarget->is64Bit()) {
18436         if (VT == MVT::i32 || VT == MVT::f32)
18437           return std::make_pair(0U, &X86::GR32RegClass);
18438         if (VT == MVT::i16)
18439           return std::make_pair(0U, &X86::GR16RegClass);
18440         if (VT == MVT::i8 || VT == MVT::i1)
18441           return std::make_pair(0U, &X86::GR8RegClass);
18442         if (VT == MVT::i64 || VT == MVT::f64)
18443           return std::make_pair(0U, &X86::GR64RegClass);
18444         break;
18445       }
18446       // 32-bit fallthrough
18447     case 'Q':   // Q_REGS
18448       if (VT == MVT::i32 || VT == MVT::f32)
18449         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18450       if (VT == MVT::i16)
18451         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18452       if (VT == MVT::i8 || VT == MVT::i1)
18453         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18454       if (VT == MVT::i64)
18455         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18456       break;
18457     case 'r':   // GENERAL_REGS
18458     case 'l':   // INDEX_REGS
18459       if (VT == MVT::i8 || VT == MVT::i1)
18460         return std::make_pair(0U, &X86::GR8RegClass);
18461       if (VT == MVT::i16)
18462         return std::make_pair(0U, &X86::GR16RegClass);
18463       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18464         return std::make_pair(0U, &X86::GR32RegClass);
18465       return std::make_pair(0U, &X86::GR64RegClass);
18466     case 'R':   // LEGACY_REGS
18467       if (VT == MVT::i8 || VT == MVT::i1)
18468         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18469       if (VT == MVT::i16)
18470         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18471       if (VT == MVT::i32 || !Subtarget->is64Bit())
18472         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18473       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18474     case 'f':  // FP Stack registers.
18475       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18476       // value to the correct fpstack register class.
18477       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18478         return std::make_pair(0U, &X86::RFP32RegClass);
18479       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18480         return std::make_pair(0U, &X86::RFP64RegClass);
18481       return std::make_pair(0U, &X86::RFP80RegClass);
18482     case 'y':   // MMX_REGS if MMX allowed.
18483       if (!Subtarget->hasMMX()) break;
18484       return std::make_pair(0U, &X86::VR64RegClass);
18485     case 'Y':   // SSE_REGS if SSE2 allowed
18486       if (!Subtarget->hasSSE2()) break;
18487       // FALL THROUGH.
18488     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18489       if (!Subtarget->hasSSE1()) break;
18490
18491       switch (VT.getSimpleVT().SimpleTy) {
18492       default: break;
18493       // Scalar SSE types.
18494       case MVT::f32:
18495       case MVT::i32:
18496         return std::make_pair(0U, &X86::FR32RegClass);
18497       case MVT::f64:
18498       case MVT::i64:
18499         return std::make_pair(0U, &X86::FR64RegClass);
18500       // Vector types.
18501       case MVT::v16i8:
18502       case MVT::v8i16:
18503       case MVT::v4i32:
18504       case MVT::v2i64:
18505       case MVT::v4f32:
18506       case MVT::v2f64:
18507         return std::make_pair(0U, &X86::VR128RegClass);
18508       // AVX types.
18509       case MVT::v32i8:
18510       case MVT::v16i16:
18511       case MVT::v8i32:
18512       case MVT::v4i64:
18513       case MVT::v8f32:
18514       case MVT::v4f64:
18515         return std::make_pair(0U, &X86::VR256RegClass);
18516       }
18517       break;
18518     }
18519   }
18520
18521   // Use the default implementation in TargetLowering to convert the register
18522   // constraint into a member of a register class.
18523   std::pair<unsigned, const TargetRegisterClass*> Res;
18524   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18525
18526   // Not found as a standard register?
18527   if (Res.second == 0) {
18528     // Map st(0) -> st(7) -> ST0
18529     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18530         tolower(Constraint[1]) == 's' &&
18531         tolower(Constraint[2]) == 't' &&
18532         Constraint[3] == '(' &&
18533         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18534         Constraint[5] == ')' &&
18535         Constraint[6] == '}') {
18536
18537       Res.first = X86::ST0+Constraint[4]-'0';
18538       Res.second = &X86::RFP80RegClass;
18539       return Res;
18540     }
18541
18542     // GCC allows "st(0)" to be called just plain "st".
18543     if (StringRef("{st}").equals_lower(Constraint)) {
18544       Res.first = X86::ST0;
18545       Res.second = &X86::RFP80RegClass;
18546       return Res;
18547     }
18548
18549     // flags -> EFLAGS
18550     if (StringRef("{flags}").equals_lower(Constraint)) {
18551       Res.first = X86::EFLAGS;
18552       Res.second = &X86::CCRRegClass;
18553       return Res;
18554     }
18555
18556     // 'A' means EAX + EDX.
18557     if (Constraint == "A") {
18558       Res.first = X86::EAX;
18559       Res.second = &X86::GR32_ADRegClass;
18560       return Res;
18561     }
18562     return Res;
18563   }
18564
18565   // Otherwise, check to see if this is a register class of the wrong value
18566   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18567   // turn into {ax},{dx}.
18568   if (Res.second->hasType(VT))
18569     return Res;   // Correct type already, nothing to do.
18570
18571   // All of the single-register GCC register classes map their values onto
18572   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18573   // really want an 8-bit or 32-bit register, map to the appropriate register
18574   // class and return the appropriate register.
18575   if (Res.second == &X86::GR16RegClass) {
18576     if (VT == MVT::i8 || VT == MVT::i1) {
18577       unsigned DestReg = 0;
18578       switch (Res.first) {
18579       default: break;
18580       case X86::AX: DestReg = X86::AL; break;
18581       case X86::DX: DestReg = X86::DL; break;
18582       case X86::CX: DestReg = X86::CL; break;
18583       case X86::BX: DestReg = X86::BL; break;
18584       }
18585       if (DestReg) {
18586         Res.first = DestReg;
18587         Res.second = &X86::GR8RegClass;
18588       }
18589     } else if (VT == MVT::i32 || VT == MVT::f32) {
18590       unsigned DestReg = 0;
18591       switch (Res.first) {
18592       default: break;
18593       case X86::AX: DestReg = X86::EAX; break;
18594       case X86::DX: DestReg = X86::EDX; break;
18595       case X86::CX: DestReg = X86::ECX; break;
18596       case X86::BX: DestReg = X86::EBX; break;
18597       case X86::SI: DestReg = X86::ESI; break;
18598       case X86::DI: DestReg = X86::EDI; break;
18599       case X86::BP: DestReg = X86::EBP; break;
18600       case X86::SP: DestReg = X86::ESP; break;
18601       }
18602       if (DestReg) {
18603         Res.first = DestReg;
18604         Res.second = &X86::GR32RegClass;
18605       }
18606     } else if (VT == MVT::i64 || VT == MVT::f64) {
18607       unsigned DestReg = 0;
18608       switch (Res.first) {
18609       default: break;
18610       case X86::AX: DestReg = X86::RAX; break;
18611       case X86::DX: DestReg = X86::RDX; break;
18612       case X86::CX: DestReg = X86::RCX; break;
18613       case X86::BX: DestReg = X86::RBX; break;
18614       case X86::SI: DestReg = X86::RSI; break;
18615       case X86::DI: DestReg = X86::RDI; break;
18616       case X86::BP: DestReg = X86::RBP; break;
18617       case X86::SP: DestReg = X86::RSP; break;
18618       }
18619       if (DestReg) {
18620         Res.first = DestReg;
18621         Res.second = &X86::GR64RegClass;
18622       }
18623     }
18624   } else if (Res.second == &X86::FR32RegClass ||
18625              Res.second == &X86::FR64RegClass ||
18626              Res.second == &X86::VR128RegClass) {
18627     // Handle references to XMM physical registers that got mapped into the
18628     // wrong class.  This can happen with constraints like {xmm0} where the
18629     // target independent register mapper will just pick the first match it can
18630     // find, ignoring the required type.
18631
18632     if (VT == MVT::f32 || VT == MVT::i32)
18633       Res.second = &X86::FR32RegClass;
18634     else if (VT == MVT::f64 || VT == MVT::i64)
18635       Res.second = &X86::FR64RegClass;
18636     else if (X86::VR128RegClass.hasType(VT))
18637       Res.second = &X86::VR128RegClass;
18638     else if (X86::VR256RegClass.hasType(VT))
18639       Res.second = &X86::VR256RegClass;
18640   }
18641
18642   return Res;
18643 }