Revert "Reuse %rax after calling __chkstk on win64"
[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, SDLoc 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, SDLoc 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                                   SDLoc 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                                    SDLoc 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   TD = getDataLayout();
167
168   resetOperationActions();
169 }
170
171 void X86TargetLowering::resetOperationActions() {
172   const TargetMachine &TM = getTargetMachine();
173   static bool FirstTimeThrough = true;
174
175   // If none of the target options have changed, then we don't need to reset the
176   // operation actions.
177   if (!FirstTimeThrough && TO == TM.Options) return;
178
179   if (!FirstTimeThrough) {
180     // Reinitialize the actions.
181     initActions();
182     FirstTimeThrough = false;
183   }
184
185   TO = TM.Options;
186
187   // Set up the TargetLowering object.
188   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
189
190   // X86 is weird, it always uses i8 for shift amounts and setcc results.
191   setBooleanContents(ZeroOrOneBooleanContent);
192   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
193   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
194
195   // For 64-bit since we have so many registers use the ILP scheduler, for
196   // 32-bit code use the register pressure specific scheduling.
197   // For Atom, always use ILP scheduling.
198   if (Subtarget->isAtom())
199     setSchedulingPreference(Sched::ILP);
200   else if (Subtarget->is64Bit())
201     setSchedulingPreference(Sched::ILP);
202   else
203     setSchedulingPreference(Sched::RegPressure);
204   const X86RegisterInfo *RegInfo =
205     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
206   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
207
208   // Bypass expensive divides on Atom when compiling with O2
209   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
210     addBypassSlowDiv(32, 8);
211     if (Subtarget->is64Bit())
212       addBypassSlowDiv(64, 16);
213   }
214
215   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
216     // Setup Windows compiler runtime calls.
217     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
218     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
219     setLibcallName(RTLIB::SREM_I64, "_allrem");
220     setLibcallName(RTLIB::UREM_I64, "_aullrem");
221     setLibcallName(RTLIB::MUL_I64, "_allmul");
222     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
223     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
224     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
225     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
226     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
227
228     // The _ftol2 runtime function has an unusual calling conv, which
229     // is modeled by a special pseudo-instruction.
230     setLibcallName(RTLIB::FPTOUINT_F64_I64, 0);
231     setLibcallName(RTLIB::FPTOUINT_F32_I64, 0);
232     setLibcallName(RTLIB::FPTOUINT_F64_I32, 0);
233     setLibcallName(RTLIB::FPTOUINT_F32_I32, 0);
234   }
235
236   if (Subtarget->isTargetDarwin()) {
237     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
238     setUseUnderscoreSetJmp(false);
239     setUseUnderscoreLongJmp(false);
240   } else if (Subtarget->isTargetMingw()) {
241     // MS runtime is weird: it exports _setjmp, but longjmp!
242     setUseUnderscoreSetJmp(true);
243     setUseUnderscoreLongJmp(false);
244   } else {
245     setUseUnderscoreSetJmp(true);
246     setUseUnderscoreLongJmp(true);
247   }
248
249   // Set up the register classes.
250   addRegisterClass(MVT::i8, &X86::GR8RegClass);
251   addRegisterClass(MVT::i16, &X86::GR16RegClass);
252   addRegisterClass(MVT::i32, &X86::GR32RegClass);
253   if (Subtarget->is64Bit())
254     addRegisterClass(MVT::i64, &X86::GR64RegClass);
255
256   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
257
258   // We don't accept any truncstore of integer registers.
259   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
260   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
261   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
262   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
263   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
264   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
265
266   // SETOEQ and SETUNE require checking two conditions.
267   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
268   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
269   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
270   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
271   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
272   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
273
274   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
275   // operation.
276   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
277   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
278   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
279
280   if (Subtarget->is64Bit()) {
281     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
282     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
283   } else if (!TM.Options.UseSoftFloat) {
284     // We have an algorithm for SSE2->double, and we turn this into a
285     // 64-bit FILD followed by conditional FADD for other targets.
286     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
287     // We have an algorithm for SSE2, and we turn this into a 64-bit
288     // FILD for other targets.
289     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
290   }
291
292   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
293   // this operation.
294   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
295   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
296
297   if (!TM.Options.UseSoftFloat) {
298     // SSE has no i16 to fp conversion, only i32
299     if (X86ScalarSSEf32) {
300       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
301       // f32 and f64 cases are Legal, f80 case is not
302       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
303     } else {
304       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
305       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
306     }
307   } else {
308     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
309     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
310   }
311
312   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
313   // are Legal, f80 is custom lowered.
314   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
315   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
316
317   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
318   // this operation.
319   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
320   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
321
322   if (X86ScalarSSEf32) {
323     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
324     // f32 and f64 cases are Legal, f80 case is not
325     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
326   } else {
327     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
328     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
329   }
330
331   // Handle FP_TO_UINT by promoting the destination to a larger signed
332   // conversion.
333   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
334   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
335   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
336
337   if (Subtarget->is64Bit()) {
338     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
339     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
340   } else if (!TM.Options.UseSoftFloat) {
341     // Since AVX is a superset of SSE3, only check for SSE here.
342     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
343       // Expand FP_TO_UINT into a select.
344       // FIXME: We would like to use a Custom expander here eventually to do
345       // the optimal thing for SSE vs. the default expansion in the legalizer.
346       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
347     else
348       // With SSE3 we can use fisttpll to convert to a signed i64; without
349       // SSE, we're stuck with a fistpll.
350       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
351   }
352
353   if (isTargetFTOL()) {
354     // Use the _ftol2 runtime function, which has a pseudo-instruction
355     // to handle its weird calling convention.
356     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
357   }
358
359   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
360   if (!X86ScalarSSEf64) {
361     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
362     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
363     if (Subtarget->is64Bit()) {
364       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
365       // Without SSE, i64->f64 goes through memory.
366       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
367     }
368   }
369
370   // Scalar integer divide and remainder are lowered to use operations that
371   // produce two results, to match the available instructions. This exposes
372   // the two-result form to trivial CSE, which is able to combine x/y and x%y
373   // into a single instruction.
374   //
375   // Scalar integer multiply-high is also lowered to use two-result
376   // operations, to match the available instructions. However, plain multiply
377   // (low) operations are left as Legal, as there are single-result
378   // instructions for this in x86. Using the two-result multiply instructions
379   // when both high and low results are needed must be arranged by dagcombine.
380   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
381     MVT VT = IntVTs[i];
382     setOperationAction(ISD::MULHS, VT, Expand);
383     setOperationAction(ISD::MULHU, VT, Expand);
384     setOperationAction(ISD::SDIV, VT, Expand);
385     setOperationAction(ISD::UDIV, VT, Expand);
386     setOperationAction(ISD::SREM, VT, Expand);
387     setOperationAction(ISD::UREM, VT, Expand);
388
389     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
390     setOperationAction(ISD::ADDC, VT, Custom);
391     setOperationAction(ISD::ADDE, VT, Custom);
392     setOperationAction(ISD::SUBC, VT, Custom);
393     setOperationAction(ISD::SUBE, VT, Custom);
394   }
395
396   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
397   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
398   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
399   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
400   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
401   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
402   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
403   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
404   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
405   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
406   if (Subtarget->is64Bit())
407     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
408   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
409   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
410   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
411   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
412   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
413   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
414   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
415   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
416
417   // Promote the i8 variants and force them on up to i32 which has a shorter
418   // encoding.
419   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
420   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
421   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
422   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
423   if (Subtarget->hasBMI()) {
424     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
425     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
426     if (Subtarget->is64Bit())
427       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
428   } else {
429     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
430     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
431     if (Subtarget->is64Bit())
432       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
433   }
434
435   if (Subtarget->hasLZCNT()) {
436     // When promoting the i8 variants, force them to i32 for a shorter
437     // encoding.
438     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
439     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
440     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
441     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
442     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
443     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
444     if (Subtarget->is64Bit())
445       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
446   } else {
447     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
448     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
449     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
450     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
451     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
452     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
453     if (Subtarget->is64Bit()) {
454       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
455       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
456     }
457   }
458
459   if (Subtarget->hasPOPCNT()) {
460     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
461   } else {
462     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
463     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
464     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
465     if (Subtarget->is64Bit())
466       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
467   }
468
469   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
470   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
471
472   // These should be promoted to a larger select which is supported.
473   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
474   // X86 wants to expand cmov itself.
475   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
476   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
477   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
478   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
479   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
480   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
481   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
482   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
483   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
484   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
485   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
486   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
487   if (Subtarget->is64Bit()) {
488     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
489     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
490   }
491   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
492   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
493   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
494   // support continuation, user-level threading, and etc.. As a result, no
495   // other SjLj exception interfaces are implemented and please don't build
496   // your own exception handling based on them.
497   // LLVM/Clang supports zero-cost DWARF exception handling.
498   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
499   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
500
501   // Darwin ABI issue.
502   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
503   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
504   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
505   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
506   if (Subtarget->is64Bit())
507     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
508   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
509   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
510   if (Subtarget->is64Bit()) {
511     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
512     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
513     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
514     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
515     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
516   }
517   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
518   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
519   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
520   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
521   if (Subtarget->is64Bit()) {
522     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
523     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
524     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
525   }
526
527   if (Subtarget->hasSSE1())
528     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
529
530   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
531
532   // Expand certain atomics
533   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
534     MVT VT = IntVTs[i];
535     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
536     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
537     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
538   }
539
540   if (!Subtarget->is64Bit()) {
541     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
542     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
543     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
544     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
545     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
546     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
547     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
548     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
549     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
550     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
551     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
552     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
553   }
554
555   if (Subtarget->hasCmpxchg16b()) {
556     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
557   }
558
559   // FIXME - use subtarget debug flags
560   if (!Subtarget->isTargetDarwin() &&
561       !Subtarget->isTargetELF() &&
562       !Subtarget->isTargetCygMing()) {
563     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
564   }
565
566   if (Subtarget->is64Bit()) {
567     setExceptionPointerRegister(X86::RAX);
568     setExceptionSelectorRegister(X86::RDX);
569   } else {
570     setExceptionPointerRegister(X86::EAX);
571     setExceptionSelectorRegister(X86::EDX);
572   }
573   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
574   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
575
576   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
577   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
578
579   setOperationAction(ISD::TRAP, MVT::Other, Legal);
580   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
581
582   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
583   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
584   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
585   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
586     // TargetInfo::X86_64ABIBuiltinVaList
587     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
588     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
589   } else {
590     // TargetInfo::CharPtrBuiltinVaList
591     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
592     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
593   }
594
595   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
596   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
597
598   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
599     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
600                        MVT::i64 : MVT::i32, Custom);
601   else if (TM.Options.EnableSegmentedStacks)
602     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
603                        MVT::i64 : MVT::i32, Custom);
604   else
605     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
606                        MVT::i64 : MVT::i32, Expand);
607
608   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
609     // f32 and f64 use SSE.
610     // Set up the FP register classes.
611     addRegisterClass(MVT::f32, &X86::FR32RegClass);
612     addRegisterClass(MVT::f64, &X86::FR64RegClass);
613
614     // Use ANDPD to simulate FABS.
615     setOperationAction(ISD::FABS , MVT::f64, Custom);
616     setOperationAction(ISD::FABS , MVT::f32, Custom);
617
618     // Use XORP to simulate FNEG.
619     setOperationAction(ISD::FNEG , MVT::f64, Custom);
620     setOperationAction(ISD::FNEG , MVT::f32, Custom);
621
622     // Use ANDPD and ORPD to simulate FCOPYSIGN.
623     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
624     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
625
626     // Lower this to FGETSIGNx86 plus an AND.
627     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
628     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
629
630     // We don't support sin/cos/fmod
631     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
632     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
633     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
634     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
635     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
636     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
637
638     // Expand FP immediates into loads from the stack, except for the special
639     // cases we handle.
640     addLegalFPImmediate(APFloat(+0.0)); // xorpd
641     addLegalFPImmediate(APFloat(+0.0f)); // xorps
642   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
643     // Use SSE for f32, x87 for f64.
644     // Set up the FP register classes.
645     addRegisterClass(MVT::f32, &X86::FR32RegClass);
646     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
647
648     // Use ANDPS to simulate FABS.
649     setOperationAction(ISD::FABS , MVT::f32, Custom);
650
651     // Use XORP to simulate FNEG.
652     setOperationAction(ISD::FNEG , MVT::f32, Custom);
653
654     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
655
656     // Use ANDPS and ORPS to simulate FCOPYSIGN.
657     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
658     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
659
660     // We don't support sin/cos/fmod
661     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
662     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
663     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
664
665     // Special cases we handle for FP constants.
666     addLegalFPImmediate(APFloat(+0.0f)); // xorps
667     addLegalFPImmediate(APFloat(+0.0)); // FLD0
668     addLegalFPImmediate(APFloat(+1.0)); // FLD1
669     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
670     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
671
672     if (!TM.Options.UnsafeFPMath) {
673       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
674       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
675       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
676     }
677   } else if (!TM.Options.UseSoftFloat) {
678     // f32 and f64 in x87.
679     // Set up the FP register classes.
680     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
681     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
682
683     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
684     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
685     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
686     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
687
688     if (!TM.Options.UnsafeFPMath) {
689       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
690       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
691       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
692       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
694       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
695     }
696     addLegalFPImmediate(APFloat(+0.0)); // FLD0
697     addLegalFPImmediate(APFloat(+1.0)); // FLD1
698     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
699     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
700     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
701     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
702     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
703     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
704   }
705
706   // We don't support FMA.
707   setOperationAction(ISD::FMA, MVT::f64, Expand);
708   setOperationAction(ISD::FMA, MVT::f32, Expand);
709
710   // Long double always uses X87.
711   if (!TM.Options.UseSoftFloat) {
712     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
713     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
714     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
715     {
716       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
717       addLegalFPImmediate(TmpFlt);  // FLD0
718       TmpFlt.changeSign();
719       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
720
721       bool ignored;
722       APFloat TmpFlt2(+1.0);
723       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
724                       &ignored);
725       addLegalFPImmediate(TmpFlt2);  // FLD1
726       TmpFlt2.changeSign();
727       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
728     }
729
730     if (!TM.Options.UnsafeFPMath) {
731       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
732       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
733       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
734     }
735
736     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
737     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
738     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
739     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
740     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
741     setOperationAction(ISD::FMA, MVT::f80, Expand);
742   }
743
744   // Always use a library call for pow.
745   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
746   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
747   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
748
749   setOperationAction(ISD::FLOG, MVT::f80, Expand);
750   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
751   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
752   setOperationAction(ISD::FEXP, MVT::f80, Expand);
753   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
754
755   // First set operation action for all vector types to either promote
756   // (for widening) or expand (for scalarization). Then we will selectively
757   // turn on ones that can be effectively codegen'd.
758   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
759            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
760     MVT VT = (MVT::SimpleValueType)i;
761     setOperationAction(ISD::ADD , VT, Expand);
762     setOperationAction(ISD::SUB , VT, Expand);
763     setOperationAction(ISD::FADD, VT, Expand);
764     setOperationAction(ISD::FNEG, VT, Expand);
765     setOperationAction(ISD::FSUB, VT, Expand);
766     setOperationAction(ISD::MUL , VT, Expand);
767     setOperationAction(ISD::FMUL, VT, Expand);
768     setOperationAction(ISD::SDIV, VT, Expand);
769     setOperationAction(ISD::UDIV, VT, Expand);
770     setOperationAction(ISD::FDIV, VT, Expand);
771     setOperationAction(ISD::SREM, VT, Expand);
772     setOperationAction(ISD::UREM, VT, Expand);
773     setOperationAction(ISD::LOAD, VT, Expand);
774     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
775     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
776     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
777     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
778     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
779     setOperationAction(ISD::FABS, VT, Expand);
780     setOperationAction(ISD::FSIN, VT, Expand);
781     setOperationAction(ISD::FSINCOS, VT, Expand);
782     setOperationAction(ISD::FCOS, VT, Expand);
783     setOperationAction(ISD::FSINCOS, VT, Expand);
784     setOperationAction(ISD::FREM, VT, Expand);
785     setOperationAction(ISD::FMA,  VT, Expand);
786     setOperationAction(ISD::FPOWI, VT, Expand);
787     setOperationAction(ISD::FSQRT, VT, Expand);
788     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
789     setOperationAction(ISD::FFLOOR, VT, Expand);
790     setOperationAction(ISD::FCEIL, VT, Expand);
791     setOperationAction(ISD::FTRUNC, VT, Expand);
792     setOperationAction(ISD::FRINT, VT, Expand);
793     setOperationAction(ISD::FNEARBYINT, VT, Expand);
794     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
795     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
796     setOperationAction(ISD::SDIVREM, VT, Expand);
797     setOperationAction(ISD::UDIVREM, VT, Expand);
798     setOperationAction(ISD::FPOW, VT, Expand);
799     setOperationAction(ISD::CTPOP, VT, Expand);
800     setOperationAction(ISD::CTTZ, VT, Expand);
801     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
802     setOperationAction(ISD::CTLZ, VT, Expand);
803     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
804     setOperationAction(ISD::SHL, VT, Expand);
805     setOperationAction(ISD::SRA, VT, Expand);
806     setOperationAction(ISD::SRL, VT, Expand);
807     setOperationAction(ISD::ROTL, VT, Expand);
808     setOperationAction(ISD::ROTR, VT, Expand);
809     setOperationAction(ISD::BSWAP, VT, Expand);
810     setOperationAction(ISD::SETCC, VT, Expand);
811     setOperationAction(ISD::FLOG, VT, Expand);
812     setOperationAction(ISD::FLOG2, VT, Expand);
813     setOperationAction(ISD::FLOG10, VT, Expand);
814     setOperationAction(ISD::FEXP, VT, Expand);
815     setOperationAction(ISD::FEXP2, VT, Expand);
816     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
817     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
818     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
819     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
820     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
821     setOperationAction(ISD::TRUNCATE, VT, Expand);
822     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
823     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
824     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
825     setOperationAction(ISD::VSELECT, VT, Expand);
826     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
827              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
828       setTruncStoreAction(VT,
829                           (MVT::SimpleValueType)InnerVT, Expand);
830     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
831     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
832     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
833   }
834
835   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
836   // with -msoft-float, disable use of MMX as well.
837   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
838     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
839     // No operations on x86mmx supported, everything uses intrinsics.
840   }
841
842   // MMX-sized vectors (other than x86mmx) are expected to be expanded
843   // into smaller operations.
844   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
845   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
846   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
847   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
848   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
849   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
850   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
851   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
852   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
853   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
854   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
855   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
856   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
857   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
858   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
859   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
860   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
861   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
862   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
863   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
864   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
865   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
866   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
867   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
868   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
869   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
870   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
871   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
872   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
873
874   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
875     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
876
877     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
878     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
879     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
880     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
881     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
882     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
883     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
884     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
885     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
886     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
888     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
889   }
890
891   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
892     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
893
894     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
895     // registers cannot be used even for integer operations.
896     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
897     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
898     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
899     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
900
901     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
902     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
903     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
904     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
905     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
906     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
907     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
908     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
909     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
910     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
911     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
912     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
913     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
914     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
915     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
916     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
917     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
918     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
919
920     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
921     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
922     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
923     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
924
925     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
926     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
927     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
928     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
929     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
930
931     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
932     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
933       MVT VT = (MVT::SimpleValueType)i;
934       // Do not attempt to custom lower non-power-of-2 vectors
935       if (!isPowerOf2_32(VT.getVectorNumElements()))
936         continue;
937       // Do not attempt to custom lower non-128-bit vectors
938       if (!VT.is128BitVector())
939         continue;
940       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
941       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
942       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
943     }
944
945     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
946     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
947     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
948     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
949     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
950     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
951
952     if (Subtarget->is64Bit()) {
953       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
954       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
955     }
956
957     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
958     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
959       MVT VT = (MVT::SimpleValueType)i;
960
961       // Do not attempt to promote non-128-bit vectors
962       if (!VT.is128BitVector())
963         continue;
964
965       setOperationAction(ISD::AND,    VT, Promote);
966       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
967       setOperationAction(ISD::OR,     VT, Promote);
968       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
969       setOperationAction(ISD::XOR,    VT, Promote);
970       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
971       setOperationAction(ISD::LOAD,   VT, Promote);
972       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
973       setOperationAction(ISD::SELECT, VT, Promote);
974       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
975     }
976
977     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
978
979     // Custom lower v2i64 and v2f64 selects.
980     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
981     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
982     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
983     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
984
985     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
986     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
987
988     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
989     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
990     // As there is no 64-bit GPR available, we need build a special custom
991     // sequence to convert from v2i32 to v2f32.
992     if (!Subtarget->is64Bit())
993       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
994
995     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
996     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
997
998     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
999   }
1000
1001   if (Subtarget->hasSSE41()) {
1002     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1003     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1004     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1005     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1006     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1007     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1008     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1009     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1010     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1011     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1012
1013     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1014     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1015     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1016     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1017     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1018     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1019     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1020     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1021     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1022     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1023
1024     // FIXME: Do we need to handle scalar-to-vector here?
1025     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1026
1027     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
1028     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
1029     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1030     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
1031     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
1032
1033     // i8 and i16 vectors are custom , because the source register and source
1034     // source memory operand types are not the same width.  f32 vectors are
1035     // custom since the immediate controlling the insert encodes additional
1036     // information.
1037     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1038     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1039     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1040     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1041
1042     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1043     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1044     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1045     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1046
1047     // FIXME: these should be Legal but thats only for the case where
1048     // the index is constant.  For now custom expand to deal with that.
1049     if (Subtarget->is64Bit()) {
1050       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1051       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1052     }
1053   }
1054
1055   if (Subtarget->hasSSE2()) {
1056     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1057     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1058
1059     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1060     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1061
1062     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1063     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1064
1065     // In the customized shift lowering, the legal cases in AVX2 will be
1066     // recognized.
1067     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1068     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1069
1070     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1071     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1072
1073     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1074
1075     setOperationAction(ISD::SDIV,              MVT::v8i16, Custom);
1076     setOperationAction(ISD::SDIV,              MVT::v4i32, Custom);
1077   }
1078
1079   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1080     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1081     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1082     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1083     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1084     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1085     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1086
1087     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1088     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1089     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1090
1091     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1092     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1093     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1094     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1095     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1099     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1101     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1102     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1103
1104     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1105     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1106     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1107     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1108     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1109     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1110     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1111     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1112     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1113     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1114     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1115     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1116
1117     setOperationAction(ISD::TRUNCATE,           MVT::v8i16, Custom);
1118     setOperationAction(ISD::TRUNCATE,           MVT::v4i32, Custom);
1119
1120     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Custom);
1121
1122     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1123     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1124     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1125     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1126
1127     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i32, Custom);
1128     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1129     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1130
1131     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1132
1133     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1134     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1135
1136     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1137     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1138
1139     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1140     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1141
1142     setOperationAction(ISD::SDIV,              MVT::v16i16, Custom);
1143
1144     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1145     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1146     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1147     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1148
1149     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1150     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1151     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1152
1153     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1154     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1155     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1156     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1157
1158     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1159     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1160     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1161     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1162     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1163     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1164
1165     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1166       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1167       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1168       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1169       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1170       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1171       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1172     }
1173
1174     if (Subtarget->hasInt256()) {
1175       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1176       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1177       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1178       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1179
1180       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1181       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1182       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1183       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1184
1185       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1186       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1187       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1188       // Don't lower v32i8 because there is no 128-bit byte mul
1189
1190       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1191
1192       setOperationAction(ISD::SDIV,            MVT::v8i32, Custom);
1193     } else {
1194       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1195       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1196       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1197       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1198
1199       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1200       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1201       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1202       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1203
1204       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1205       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1206       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1207       // Don't lower v32i8 because there is no 128-bit byte mul
1208     }
1209
1210     // In the customized shift lowering, the legal cases in AVX2 will be
1211     // recognized.
1212     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1217
1218     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1219
1220     // Custom lower several nodes for 256-bit types.
1221     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1222              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1223       MVT VT = (MVT::SimpleValueType)i;
1224
1225       // Extract subvector is special because the value type
1226       // (result) is 128-bit but the source is 256-bit wide.
1227       if (VT.is128BitVector())
1228         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1229
1230       // Do not attempt to custom lower other non-256-bit vectors
1231       if (!VT.is256BitVector())
1232         continue;
1233
1234       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1235       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1244     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1245       MVT VT = (MVT::SimpleValueType)i;
1246
1247       // Do not attempt to promote non-256-bit vectors
1248       if (!VT.is256BitVector())
1249         continue;
1250
1251       setOperationAction(ISD::AND,    VT, Promote);
1252       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1253       setOperationAction(ISD::OR,     VT, Promote);
1254       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1255       setOperationAction(ISD::XOR,    VT, Promote);
1256       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1257       setOperationAction(ISD::LOAD,   VT, Promote);
1258       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1259       setOperationAction(ISD::SELECT, VT, Promote);
1260       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1261     }
1262   }
1263
1264   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1265   // of this type with custom code.
1266   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1267            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1268     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1269                        Custom);
1270   }
1271
1272   // We want to custom lower some of our intrinsics.
1273   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1274   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1275
1276   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1277   // handle type legalization for these operations here.
1278   //
1279   // FIXME: We really should do custom legalization for addition and
1280   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1281   // than generic legalization for 64-bit multiplication-with-overflow, though.
1282   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1283     // Add/Sub/Mul with overflow operations are custom lowered.
1284     MVT VT = IntVTs[i];
1285     setOperationAction(ISD::SADDO, VT, Custom);
1286     setOperationAction(ISD::UADDO, VT, Custom);
1287     setOperationAction(ISD::SSUBO, VT, Custom);
1288     setOperationAction(ISD::USUBO, VT, Custom);
1289     setOperationAction(ISD::SMULO, VT, Custom);
1290     setOperationAction(ISD::UMULO, VT, Custom);
1291   }
1292
1293   // There are no 8-bit 3-address imul/mul instructions
1294   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1295   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1296
1297   if (!Subtarget->is64Bit()) {
1298     // These libcalls are not available in 32-bit.
1299     setLibcallName(RTLIB::SHL_I128, 0);
1300     setLibcallName(RTLIB::SRL_I128, 0);
1301     setLibcallName(RTLIB::SRA_I128, 0);
1302   }
1303
1304   // Combine sin / cos into one node or libcall if possible.
1305   if (Subtarget->hasSinCos()) {
1306     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1307     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1308     if (Subtarget->isTargetDarwin()) {
1309       // For MacOSX, we don't want to the normal expansion of a libcall to
1310       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1311       // traffic.
1312       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1313       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1314     }
1315   }
1316
1317   // We have target-specific dag combine patterns for the following nodes:
1318   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1319   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1320   setTargetDAGCombine(ISD::VSELECT);
1321   setTargetDAGCombine(ISD::SELECT);
1322   setTargetDAGCombine(ISD::SHL);
1323   setTargetDAGCombine(ISD::SRA);
1324   setTargetDAGCombine(ISD::SRL);
1325   setTargetDAGCombine(ISD::OR);
1326   setTargetDAGCombine(ISD::AND);
1327   setTargetDAGCombine(ISD::ADD);
1328   setTargetDAGCombine(ISD::FADD);
1329   setTargetDAGCombine(ISD::FSUB);
1330   setTargetDAGCombine(ISD::FMA);
1331   setTargetDAGCombine(ISD::SUB);
1332   setTargetDAGCombine(ISD::LOAD);
1333   setTargetDAGCombine(ISD::STORE);
1334   setTargetDAGCombine(ISD::ZERO_EXTEND);
1335   setTargetDAGCombine(ISD::ANY_EXTEND);
1336   setTargetDAGCombine(ISD::SIGN_EXTEND);
1337   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1338   setTargetDAGCombine(ISD::TRUNCATE);
1339   setTargetDAGCombine(ISD::SINT_TO_FP);
1340   setTargetDAGCombine(ISD::SETCC);
1341   if (Subtarget->is64Bit())
1342     setTargetDAGCombine(ISD::MUL);
1343   setTargetDAGCombine(ISD::XOR);
1344
1345   computeRegisterProperties();
1346
1347   // On Darwin, -Os means optimize for size without hurting performance,
1348   // do not reduce the limit.
1349   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1350   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1351   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1352   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1353   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1354   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1355   setPrefLoopAlignment(4); // 2^4 bytes.
1356
1357   // Predictable cmov don't hurt on atom because it's in-order.
1358   PredictableSelectIsExpensive = !Subtarget->isAtom();
1359
1360   setPrefFunctionAlignment(4); // 2^4 bytes.
1361 }
1362
1363 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1364   if (!VT.isVector()) return MVT::i8;
1365   return VT.changeVectorElementTypeToInteger();
1366 }
1367
1368 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1369 /// the desired ByVal argument alignment.
1370 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1371   if (MaxAlign == 16)
1372     return;
1373   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1374     if (VTy->getBitWidth() == 128)
1375       MaxAlign = 16;
1376   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1377     unsigned EltAlign = 0;
1378     getMaxByValAlign(ATy->getElementType(), EltAlign);
1379     if (EltAlign > MaxAlign)
1380       MaxAlign = EltAlign;
1381   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1382     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1383       unsigned EltAlign = 0;
1384       getMaxByValAlign(STy->getElementType(i), EltAlign);
1385       if (EltAlign > MaxAlign)
1386         MaxAlign = EltAlign;
1387       if (MaxAlign == 16)
1388         break;
1389     }
1390   }
1391 }
1392
1393 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1394 /// function arguments in the caller parameter area. For X86, aggregates
1395 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1396 /// are at 4-byte boundaries.
1397 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1398   if (Subtarget->is64Bit()) {
1399     // Max of 8 and alignment of type.
1400     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1401     if (TyAlign > 8)
1402       return TyAlign;
1403     return 8;
1404   }
1405
1406   unsigned Align = 4;
1407   if (Subtarget->hasSSE1())
1408     getMaxByValAlign(Ty, Align);
1409   return Align;
1410 }
1411
1412 /// getOptimalMemOpType - Returns the target specific optimal type for load
1413 /// and store operations as a result of memset, memcpy, and memmove
1414 /// lowering. If DstAlign is zero that means it's safe to destination
1415 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1416 /// means there isn't a need to check it against alignment requirement,
1417 /// probably because the source does not need to be loaded. If 'IsMemset' is
1418 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1419 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1420 /// source is constant so it does not need to be loaded.
1421 /// It returns EVT::Other if the type should be determined using generic
1422 /// target-independent logic.
1423 EVT
1424 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1425                                        unsigned DstAlign, unsigned SrcAlign,
1426                                        bool IsMemset, bool ZeroMemset,
1427                                        bool MemcpyStrSrc,
1428                                        MachineFunction &MF) const {
1429   const Function *F = MF.getFunction();
1430   if ((!IsMemset || ZeroMemset) &&
1431       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1432                                        Attribute::NoImplicitFloat)) {
1433     if (Size >= 16 &&
1434         (Subtarget->isUnalignedMemAccessFast() ||
1435          ((DstAlign == 0 || DstAlign >= 16) &&
1436           (SrcAlign == 0 || SrcAlign >= 16)))) {
1437       if (Size >= 32) {
1438         if (Subtarget->hasInt256())
1439           return MVT::v8i32;
1440         if (Subtarget->hasFp256())
1441           return MVT::v8f32;
1442       }
1443       if (Subtarget->hasSSE2())
1444         return MVT::v4i32;
1445       if (Subtarget->hasSSE1())
1446         return MVT::v4f32;
1447     } else if (!MemcpyStrSrc && Size >= 8 &&
1448                !Subtarget->is64Bit() &&
1449                Subtarget->hasSSE2()) {
1450       // Do not use f64 to lower memcpy if source is string constant. It's
1451       // better to use i32 to avoid the loads.
1452       return MVT::f64;
1453     }
1454   }
1455   if (Subtarget->is64Bit() && Size >= 8)
1456     return MVT::i64;
1457   return MVT::i32;
1458 }
1459
1460 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1461   if (VT == MVT::f32)
1462     return X86ScalarSSEf32;
1463   else if (VT == MVT::f64)
1464     return X86ScalarSSEf64;
1465   return true;
1466 }
1467
1468 bool
1469 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
1470   if (Fast)
1471     *Fast = Subtarget->isUnalignedMemAccessFast();
1472   return true;
1473 }
1474
1475 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1476 /// current function.  The returned value is a member of the
1477 /// MachineJumpTableInfo::JTEntryKind enum.
1478 unsigned X86TargetLowering::getJumpTableEncoding() const {
1479   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1480   // symbol.
1481   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1482       Subtarget->isPICStyleGOT())
1483     return MachineJumpTableInfo::EK_Custom32;
1484
1485   // Otherwise, use the normal jump table encoding heuristics.
1486   return TargetLowering::getJumpTableEncoding();
1487 }
1488
1489 const MCExpr *
1490 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1491                                              const MachineBasicBlock *MBB,
1492                                              unsigned uid,MCContext &Ctx) const{
1493   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1494          Subtarget->isPICStyleGOT());
1495   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1496   // entries.
1497   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1498                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1499 }
1500
1501 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1502 /// jumptable.
1503 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1504                                                     SelectionDAG &DAG) const {
1505   if (!Subtarget->is64Bit())
1506     // This doesn't have SDLoc associated with it, but is not really the
1507     // same as a Register.
1508     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1509   return Table;
1510 }
1511
1512 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1513 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1514 /// MCExpr.
1515 const MCExpr *X86TargetLowering::
1516 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1517                              MCContext &Ctx) const {
1518   // X86-64 uses RIP relative addressing based on the jump table label.
1519   if (Subtarget->isPICStyleRIPRel())
1520     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1521
1522   // Otherwise, the reference is relative to the PIC base.
1523   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1524 }
1525
1526 // FIXME: Why this routine is here? Move to RegInfo!
1527 std::pair<const TargetRegisterClass*, uint8_t>
1528 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1529   const TargetRegisterClass *RRC = 0;
1530   uint8_t Cost = 1;
1531   switch (VT.SimpleTy) {
1532   default:
1533     return TargetLowering::findRepresentativeClass(VT);
1534   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1535     RRC = Subtarget->is64Bit() ?
1536       (const TargetRegisterClass*)&X86::GR64RegClass :
1537       (const TargetRegisterClass*)&X86::GR32RegClass;
1538     break;
1539   case MVT::x86mmx:
1540     RRC = &X86::VR64RegClass;
1541     break;
1542   case MVT::f32: case MVT::f64:
1543   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1544   case MVT::v4f32: case MVT::v2f64:
1545   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1546   case MVT::v4f64:
1547     RRC = &X86::VR128RegClass;
1548     break;
1549   }
1550   return std::make_pair(RRC, Cost);
1551 }
1552
1553 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1554                                                unsigned &Offset) const {
1555   if (!Subtarget->isTargetLinux())
1556     return false;
1557
1558   if (Subtarget->is64Bit()) {
1559     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1560     Offset = 0x28;
1561     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1562       AddressSpace = 256;
1563     else
1564       AddressSpace = 257;
1565   } else {
1566     // %gs:0x14 on i386
1567     Offset = 0x14;
1568     AddressSpace = 256;
1569   }
1570   return true;
1571 }
1572
1573 //===----------------------------------------------------------------------===//
1574 //               Return Value Calling Convention Implementation
1575 //===----------------------------------------------------------------------===//
1576
1577 #include "X86GenCallingConv.inc"
1578
1579 bool
1580 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1581                                   MachineFunction &MF, bool isVarArg,
1582                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1583                         LLVMContext &Context) const {
1584   SmallVector<CCValAssign, 16> RVLocs;
1585   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1586                  RVLocs, Context);
1587   return CCInfo.CheckReturn(Outs, RetCC_X86);
1588 }
1589
1590 SDValue
1591 X86TargetLowering::LowerReturn(SDValue Chain,
1592                                CallingConv::ID CallConv, bool isVarArg,
1593                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1594                                const SmallVectorImpl<SDValue> &OutVals,
1595                                SDLoc dl, SelectionDAG &DAG) const {
1596   MachineFunction &MF = DAG.getMachineFunction();
1597   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1598
1599   SmallVector<CCValAssign, 16> RVLocs;
1600   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1601                  RVLocs, *DAG.getContext());
1602   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1603
1604   SDValue Flag;
1605   SmallVector<SDValue, 6> RetOps;
1606   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1607   // Operand #1 = Bytes To Pop
1608   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1609                    MVT::i16));
1610
1611   // Copy the result values into the output registers.
1612   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1613     CCValAssign &VA = RVLocs[i];
1614     assert(VA.isRegLoc() && "Can only return in registers!");
1615     SDValue ValToCopy = OutVals[i];
1616     EVT ValVT = ValToCopy.getValueType();
1617
1618     // Promote values to the appropriate types
1619     if (VA.getLocInfo() == CCValAssign::SExt)
1620       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1621     else if (VA.getLocInfo() == CCValAssign::ZExt)
1622       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1623     else if (VA.getLocInfo() == CCValAssign::AExt)
1624       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1625     else if (VA.getLocInfo() == CCValAssign::BCvt)
1626       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1627
1628     // If this is x86-64, and we disabled SSE, we can't return FP values,
1629     // or SSE or MMX vectors.
1630     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1631          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1632           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1633       report_fatal_error("SSE register return with SSE disabled");
1634     }
1635     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1636     // llvm-gcc has never done it right and no one has noticed, so this
1637     // should be OK for now.
1638     if (ValVT == MVT::f64 &&
1639         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1640       report_fatal_error("SSE2 register return with SSE2 disabled");
1641
1642     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1643     // the RET instruction and handled by the FP Stackifier.
1644     if (VA.getLocReg() == X86::ST0 ||
1645         VA.getLocReg() == X86::ST1) {
1646       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1647       // change the value to the FP stack register class.
1648       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1649         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1650       RetOps.push_back(ValToCopy);
1651       // Don't emit a copytoreg.
1652       continue;
1653     }
1654
1655     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1656     // which is returned in RAX / RDX.
1657     if (Subtarget->is64Bit()) {
1658       if (ValVT == MVT::x86mmx) {
1659         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1660           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1661           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1662                                   ValToCopy);
1663           // If we don't have SSE2 available, convert to v4f32 so the generated
1664           // register is legal.
1665           if (!Subtarget->hasSSE2())
1666             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1667         }
1668       }
1669     }
1670
1671     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1672     Flag = Chain.getValue(1);
1673     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1674   }
1675
1676   // The x86-64 ABIs require that for returning structs by value we copy
1677   // the sret argument into %rax/%eax (depending on ABI) for the return.
1678   // Win32 requires us to put the sret argument to %eax as well.
1679   // We saved the argument into a virtual register in the entry block,
1680   // so now we copy the value out and into %rax/%eax.
1681   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1682       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
1683     MachineFunction &MF = DAG.getMachineFunction();
1684     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1685     unsigned Reg = FuncInfo->getSRetReturnReg();
1686     assert(Reg &&
1687            "SRetReturnReg should have been set in LowerFormalArguments().");
1688     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1689
1690     unsigned RetValReg
1691         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1692           X86::RAX : X86::EAX;
1693     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1694     Flag = Chain.getValue(1);
1695
1696     // RAX/EAX now acts like a return value.
1697     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1698   }
1699
1700   RetOps[0] = Chain;  // Update chain.
1701
1702   // Add the flag if we have it.
1703   if (Flag.getNode())
1704     RetOps.push_back(Flag);
1705
1706   return DAG.getNode(X86ISD::RET_FLAG, dl,
1707                      MVT::Other, &RetOps[0], RetOps.size());
1708 }
1709
1710 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1711   if (N->getNumValues() != 1)
1712     return false;
1713   if (!N->hasNUsesOfValue(1, 0))
1714     return false;
1715
1716   SDValue TCChain = Chain;
1717   SDNode *Copy = *N->use_begin();
1718   if (Copy->getOpcode() == ISD::CopyToReg) {
1719     // If the copy has a glue operand, we conservatively assume it isn't safe to
1720     // perform a tail call.
1721     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1722       return false;
1723     TCChain = Copy->getOperand(0);
1724   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1725     return false;
1726
1727   bool HasRet = false;
1728   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1729        UI != UE; ++UI) {
1730     if (UI->getOpcode() != X86ISD::RET_FLAG)
1731       return false;
1732     HasRet = true;
1733   }
1734
1735   if (!HasRet)
1736     return false;
1737
1738   Chain = TCChain;
1739   return true;
1740 }
1741
1742 MVT
1743 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1744                                             ISD::NodeType ExtendKind) const {
1745   MVT ReturnMVT;
1746   // TODO: Is this also valid on 32-bit?
1747   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1748     ReturnMVT = MVT::i8;
1749   else
1750     ReturnMVT = MVT::i32;
1751
1752   MVT MinVT = getRegisterType(ReturnMVT);
1753   return VT.bitsLT(MinVT) ? MinVT : VT;
1754 }
1755
1756 /// LowerCallResult - Lower the result values of a call into the
1757 /// appropriate copies out of appropriate physical registers.
1758 ///
1759 SDValue
1760 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1761                                    CallingConv::ID CallConv, bool isVarArg,
1762                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1763                                    SDLoc dl, SelectionDAG &DAG,
1764                                    SmallVectorImpl<SDValue> &InVals) const {
1765
1766   // Assign locations to each value returned by this call.
1767   SmallVector<CCValAssign, 16> RVLocs;
1768   bool Is64Bit = Subtarget->is64Bit();
1769   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1770                  getTargetMachine(), RVLocs, *DAG.getContext());
1771   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1772
1773   // Copy all of the result registers out of their specified physreg.
1774   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
1775     CCValAssign &VA = RVLocs[i];
1776     EVT CopyVT = VA.getValVT();
1777
1778     // If this is x86-64, and we disabled SSE, we can't return FP values
1779     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1780         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1781       report_fatal_error("SSE register return with SSE disabled");
1782     }
1783
1784     SDValue Val;
1785
1786     // If this is a call to a function that returns an fp value on the floating
1787     // point stack, we must guarantee the value is popped from the stack, so
1788     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1789     // if the return value is not used. We use the FpPOP_RETVAL instruction
1790     // instead.
1791     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1792       // If we prefer to use the value in xmm registers, copy it out as f80 and
1793       // use a truncate to move it from fp stack reg to xmm reg.
1794       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1795       SDValue Ops[] = { Chain, InFlag };
1796       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1797                                          MVT::Other, MVT::Glue, Ops), 1);
1798       Val = Chain.getValue(0);
1799
1800       // Round the f80 to the right size, which also moves it to the appropriate
1801       // xmm register.
1802       if (CopyVT != VA.getValVT())
1803         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1804                           // This truncation won't change the value.
1805                           DAG.getIntPtrConstant(1));
1806     } else {
1807       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1808                                  CopyVT, InFlag).getValue(1);
1809       Val = Chain.getValue(0);
1810     }
1811     InFlag = Chain.getValue(2);
1812     InVals.push_back(Val);
1813   }
1814
1815   return Chain;
1816 }
1817
1818 //===----------------------------------------------------------------------===//
1819 //                C & StdCall & Fast Calling Convention implementation
1820 //===----------------------------------------------------------------------===//
1821 //  StdCall calling convention seems to be standard for many Windows' API
1822 //  routines and around. It differs from C calling convention just a little:
1823 //  callee should clean up the stack, not caller. Symbols should be also
1824 //  decorated in some fancy way :) It doesn't support any vector arguments.
1825 //  For info on fast calling convention see Fast Calling Convention (tail call)
1826 //  implementation LowerX86_32FastCCCallTo.
1827
1828 /// CallIsStructReturn - Determines whether a call uses struct return
1829 /// semantics.
1830 enum StructReturnType {
1831   NotStructReturn,
1832   RegStructReturn,
1833   StackStructReturn
1834 };
1835 static StructReturnType
1836 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1837   if (Outs.empty())
1838     return NotStructReturn;
1839
1840   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
1841   if (!Flags.isSRet())
1842     return NotStructReturn;
1843   if (Flags.isInReg())
1844     return RegStructReturn;
1845   return StackStructReturn;
1846 }
1847
1848 /// ArgsAreStructReturn - Determines whether a function uses struct
1849 /// return semantics.
1850 static StructReturnType
1851 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1852   if (Ins.empty())
1853     return NotStructReturn;
1854
1855   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
1856   if (!Flags.isSRet())
1857     return NotStructReturn;
1858   if (Flags.isInReg())
1859     return RegStructReturn;
1860   return StackStructReturn;
1861 }
1862
1863 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1864 /// by "Src" to address "Dst" with size and alignment information specified by
1865 /// the specific parameter attribute. The copy will be passed as a byval
1866 /// function parameter.
1867 static SDValue
1868 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1869                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1870                           SDLoc dl) {
1871   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1872
1873   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1874                        /*isVolatile*/false, /*AlwaysInline=*/true,
1875                        MachinePointerInfo(), MachinePointerInfo());
1876 }
1877
1878 /// IsTailCallConvention - Return true if the calling convention is one that
1879 /// supports tail call optimization.
1880 static bool IsTailCallConvention(CallingConv::ID CC) {
1881   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
1882           CC == CallingConv::HiPE);
1883 }
1884
1885 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1886   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
1887     return false;
1888
1889   CallSite CS(CI);
1890   CallingConv::ID CalleeCC = CS.getCallingConv();
1891   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1892     return false;
1893
1894   return true;
1895 }
1896
1897 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1898 /// a tailcall target by changing its ABI.
1899 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
1900                                    bool GuaranteedTailCallOpt) {
1901   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1902 }
1903
1904 SDValue
1905 X86TargetLowering::LowerMemArgument(SDValue Chain,
1906                                     CallingConv::ID CallConv,
1907                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1908                                     SDLoc dl, SelectionDAG &DAG,
1909                                     const CCValAssign &VA,
1910                                     MachineFrameInfo *MFI,
1911                                     unsigned i) const {
1912   // Create the nodes corresponding to a load from this parameter slot.
1913   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1914   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
1915                               getTargetMachine().Options.GuaranteedTailCallOpt);
1916   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1917   EVT ValVT;
1918
1919   // If value is passed by pointer we have address passed instead of the value
1920   // itself.
1921   if (VA.getLocInfo() == CCValAssign::Indirect)
1922     ValVT = VA.getLocVT();
1923   else
1924     ValVT = VA.getValVT();
1925
1926   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1927   // changed with more analysis.
1928   // In case of tail call optimization mark all arguments mutable. Since they
1929   // could be overwritten by lowering of arguments in case of a tail call.
1930   if (Flags.isByVal()) {
1931     unsigned Bytes = Flags.getByValSize();
1932     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1933     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1934     return DAG.getFrameIndex(FI, getPointerTy());
1935   } else {
1936     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1937                                     VA.getLocMemOffset(), isImmutable);
1938     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1939     return DAG.getLoad(ValVT, dl, Chain, FIN,
1940                        MachinePointerInfo::getFixedStack(FI),
1941                        false, false, false, 0);
1942   }
1943 }
1944
1945 SDValue
1946 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1947                                         CallingConv::ID CallConv,
1948                                         bool isVarArg,
1949                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1950                                         SDLoc dl,
1951                                         SelectionDAG &DAG,
1952                                         SmallVectorImpl<SDValue> &InVals)
1953                                           const {
1954   MachineFunction &MF = DAG.getMachineFunction();
1955   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1956
1957   const Function* Fn = MF.getFunction();
1958   if (Fn->hasExternalLinkage() &&
1959       Subtarget->isTargetCygMing() &&
1960       Fn->getName() == "main")
1961     FuncInfo->setForceFramePointer(true);
1962
1963   MachineFrameInfo *MFI = MF.getFrameInfo();
1964   bool Is64Bit = Subtarget->is64Bit();
1965   bool IsWindows = Subtarget->isTargetWindows();
1966   bool IsWin64 = Subtarget->isTargetWin64();
1967
1968   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1969          "Var args not supported with calling convention fastcc, ghc or hipe");
1970
1971   // Assign locations to all of the incoming arguments.
1972   SmallVector<CCValAssign, 16> ArgLocs;
1973   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1974                  ArgLocs, *DAG.getContext());
1975
1976   // Allocate shadow area for Win64
1977   if (IsWin64) {
1978     CCInfo.AllocateStack(32, 8);
1979   }
1980
1981   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1982
1983   unsigned LastVal = ~0U;
1984   SDValue ArgValue;
1985   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1986     CCValAssign &VA = ArgLocs[i];
1987     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1988     // places.
1989     assert(VA.getValNo() != LastVal &&
1990            "Don't support value assigned to multiple locs yet");
1991     (void)LastVal;
1992     LastVal = VA.getValNo();
1993
1994     if (VA.isRegLoc()) {
1995       EVT RegVT = VA.getLocVT();
1996       const TargetRegisterClass *RC;
1997       if (RegVT == MVT::i32)
1998         RC = &X86::GR32RegClass;
1999       else if (Is64Bit && RegVT == MVT::i64)
2000         RC = &X86::GR64RegClass;
2001       else if (RegVT == MVT::f32)
2002         RC = &X86::FR32RegClass;
2003       else if (RegVT == MVT::f64)
2004         RC = &X86::FR64RegClass;
2005       else if (RegVT.is256BitVector())
2006         RC = &X86::VR256RegClass;
2007       else if (RegVT.is128BitVector())
2008         RC = &X86::VR128RegClass;
2009       else if (RegVT == MVT::x86mmx)
2010         RC = &X86::VR64RegClass;
2011       else
2012         llvm_unreachable("Unknown argument type!");
2013
2014       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2015       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2016
2017       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2018       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2019       // right size.
2020       if (VA.getLocInfo() == CCValAssign::SExt)
2021         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2022                                DAG.getValueType(VA.getValVT()));
2023       else if (VA.getLocInfo() == CCValAssign::ZExt)
2024         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2025                                DAG.getValueType(VA.getValVT()));
2026       else if (VA.getLocInfo() == CCValAssign::BCvt)
2027         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2028
2029       if (VA.isExtInLoc()) {
2030         // Handle MMX values passed in XMM regs.
2031         if (RegVT.isVector())
2032           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2033         else
2034           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2035       }
2036     } else {
2037       assert(VA.isMemLoc());
2038       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2039     }
2040
2041     // If value is passed via pointer - do a load.
2042     if (VA.getLocInfo() == CCValAssign::Indirect)
2043       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2044                              MachinePointerInfo(), false, false, false, 0);
2045
2046     InVals.push_back(ArgValue);
2047   }
2048
2049   // The x86-64 ABIs require that for returning structs by value we copy
2050   // the sret argument into %rax/%eax (depending on ABI) for the return.
2051   // Win32 requires us to put the sret argument to %eax as well.
2052   // Save the argument into a virtual register so that we can access it
2053   // from the return points.
2054   if (MF.getFunction()->hasStructRetAttr() &&
2055       (Subtarget->is64Bit() || Subtarget->isTargetWindows())) {
2056     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2057     unsigned Reg = FuncInfo->getSRetReturnReg();
2058     if (!Reg) {
2059       MVT PtrTy = getPointerTy();
2060       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2061       FuncInfo->setSRetReturnReg(Reg);
2062     }
2063     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2064     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2065   }
2066
2067   unsigned StackSize = CCInfo.getNextStackOffset();
2068   // Align stack specially for tail calls.
2069   if (FuncIsMadeTailCallSafe(CallConv,
2070                              MF.getTarget().Options.GuaranteedTailCallOpt))
2071     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2072
2073   // If the function takes variable number of arguments, make a frame index for
2074   // the start of the first vararg value... for expansion of llvm.va_start.
2075   if (isVarArg) {
2076     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2077                     CallConv != CallingConv::X86_ThisCall)) {
2078       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2079     }
2080     if (Is64Bit) {
2081       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2082
2083       // FIXME: We should really autogenerate these arrays
2084       static const uint16_t GPR64ArgRegsWin64[] = {
2085         X86::RCX, X86::RDX, X86::R8,  X86::R9
2086       };
2087       static const uint16_t GPR64ArgRegs64Bit[] = {
2088         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2089       };
2090       static const uint16_t XMMArgRegs64Bit[] = {
2091         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2092         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2093       };
2094       const uint16_t *GPR64ArgRegs;
2095       unsigned NumXMMRegs = 0;
2096
2097       if (IsWin64) {
2098         // The XMM registers which might contain var arg parameters are shadowed
2099         // in their paired GPR.  So we only need to save the GPR to their home
2100         // slots.
2101         TotalNumIntRegs = 4;
2102         GPR64ArgRegs = GPR64ArgRegsWin64;
2103       } else {
2104         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2105         GPR64ArgRegs = GPR64ArgRegs64Bit;
2106
2107         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2108                                                 TotalNumXMMRegs);
2109       }
2110       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2111                                                        TotalNumIntRegs);
2112
2113       bool NoImplicitFloatOps = Fn->getAttributes().
2114         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2115       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2116              "SSE register cannot be used when SSE is disabled!");
2117       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2118                NoImplicitFloatOps) &&
2119              "SSE register cannot be used when SSE is disabled!");
2120       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2121           !Subtarget->hasSSE1())
2122         // Kernel mode asks for SSE to be disabled, so don't push them
2123         // on the stack.
2124         TotalNumXMMRegs = 0;
2125
2126       if (IsWin64) {
2127         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2128         // Get to the caller-allocated home save location.  Add 8 to account
2129         // for the return address.
2130         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2131         FuncInfo->setRegSaveFrameIndex(
2132           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2133         // Fixup to set vararg frame on shadow area (4 x i64).
2134         if (NumIntRegs < 4)
2135           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2136       } else {
2137         // For X86-64, if there are vararg parameters that are passed via
2138         // registers, then we must store them to their spots on the stack so
2139         // they may be loaded by deferencing the result of va_next.
2140         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2141         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2142         FuncInfo->setRegSaveFrameIndex(
2143           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2144                                false));
2145       }
2146
2147       // Store the integer parameter registers.
2148       SmallVector<SDValue, 8> MemOps;
2149       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2150                                         getPointerTy());
2151       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2152       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2153         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2154                                   DAG.getIntPtrConstant(Offset));
2155         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2156                                      &X86::GR64RegClass);
2157         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2158         SDValue Store =
2159           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2160                        MachinePointerInfo::getFixedStack(
2161                          FuncInfo->getRegSaveFrameIndex(), Offset),
2162                        false, false, 0);
2163         MemOps.push_back(Store);
2164         Offset += 8;
2165       }
2166
2167       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2168         // Now store the XMM (fp + vector) parameter registers.
2169         SmallVector<SDValue, 11> SaveXMMOps;
2170         SaveXMMOps.push_back(Chain);
2171
2172         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2173         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2174         SaveXMMOps.push_back(ALVal);
2175
2176         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2177                                FuncInfo->getRegSaveFrameIndex()));
2178         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2179                                FuncInfo->getVarArgsFPOffset()));
2180
2181         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2182           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2183                                        &X86::VR128RegClass);
2184           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2185           SaveXMMOps.push_back(Val);
2186         }
2187         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2188                                      MVT::Other,
2189                                      &SaveXMMOps[0], SaveXMMOps.size()));
2190       }
2191
2192       if (!MemOps.empty())
2193         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2194                             &MemOps[0], MemOps.size());
2195     }
2196   }
2197
2198   // Some CCs need callee pop.
2199   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2200                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2201     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2202   } else {
2203     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2204     // If this is an sret function, the return should pop the hidden pointer.
2205     if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2206         argsAreStructReturn(Ins) == StackStructReturn)
2207       FuncInfo->setBytesToPopOnReturn(4);
2208   }
2209
2210   if (!Is64Bit) {
2211     // RegSaveFrameIndex is X86-64 only.
2212     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2213     if (CallConv == CallingConv::X86_FastCall ||
2214         CallConv == CallingConv::X86_ThisCall)
2215       // fastcc functions can't have varargs.
2216       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2217   }
2218
2219   FuncInfo->setArgumentStackSize(StackSize);
2220
2221   return Chain;
2222 }
2223
2224 SDValue
2225 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2226                                     SDValue StackPtr, SDValue Arg,
2227                                     SDLoc dl, SelectionDAG &DAG,
2228                                     const CCValAssign &VA,
2229                                     ISD::ArgFlagsTy Flags) const {
2230   unsigned LocMemOffset = VA.getLocMemOffset();
2231   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2232   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2233   if (Flags.isByVal())
2234     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2235
2236   return DAG.getStore(Chain, dl, Arg, PtrOff,
2237                       MachinePointerInfo::getStack(LocMemOffset),
2238                       false, false, 0);
2239 }
2240
2241 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2242 /// optimization is performed and it is required.
2243 SDValue
2244 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2245                                            SDValue &OutRetAddr, SDValue Chain,
2246                                            bool IsTailCall, bool Is64Bit,
2247                                            int FPDiff, SDLoc dl) const {
2248   // Adjust the Return address stack slot.
2249   EVT VT = getPointerTy();
2250   OutRetAddr = getReturnAddressFrameIndex(DAG);
2251
2252   // Load the "old" Return address.
2253   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2254                            false, false, false, 0);
2255   return SDValue(OutRetAddr.getNode(), 1);
2256 }
2257
2258 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2259 /// optimization is performed and it is required (FPDiff!=0).
2260 static SDValue
2261 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2262                          SDValue Chain, SDValue RetAddrFrIdx, EVT PtrVT,
2263                          unsigned SlotSize, int FPDiff, SDLoc dl) {
2264   // Store the return address to the appropriate stack slot.
2265   if (!FPDiff) return Chain;
2266   // Calculate the new stack slot for the return address.
2267   int NewReturnAddrFI =
2268     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2269   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2270   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2271                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2272                        false, false, 0);
2273   return Chain;
2274 }
2275
2276 SDValue
2277 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2278                              SmallVectorImpl<SDValue> &InVals) const {
2279   SelectionDAG &DAG                     = CLI.DAG;
2280   SDLoc &dl                          = CLI.DL;
2281   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2282   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2283   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2284   SDValue Chain                         = CLI.Chain;
2285   SDValue Callee                        = CLI.Callee;
2286   CallingConv::ID CallConv              = CLI.CallConv;
2287   bool &isTailCall                      = CLI.IsTailCall;
2288   bool isVarArg                         = CLI.IsVarArg;
2289
2290   MachineFunction &MF = DAG.getMachineFunction();
2291   bool Is64Bit        = Subtarget->is64Bit();
2292   bool IsWin64        = Subtarget->isTargetWin64();
2293   bool IsWindows      = Subtarget->isTargetWindows();
2294   StructReturnType SR = callIsStructReturn(Outs);
2295   bool IsSibcall      = false;
2296
2297   if (MF.getTarget().Options.DisableTailCalls)
2298     isTailCall = false;
2299
2300   if (isTailCall) {
2301     // Check if it's really possible to do a tail call.
2302     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2303                     isVarArg, SR != NotStructReturn,
2304                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2305                     Outs, OutVals, Ins, DAG);
2306
2307     // Sibcalls are automatically detected tailcalls which do not require
2308     // ABI changes.
2309     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2310       IsSibcall = true;
2311
2312     if (isTailCall)
2313       ++NumTailCalls;
2314   }
2315
2316   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2317          "Var args not supported with calling convention fastcc, ghc or hipe");
2318
2319   // Analyze operands of the call, assigning locations to each operand.
2320   SmallVector<CCValAssign, 16> ArgLocs;
2321   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2322                  ArgLocs, *DAG.getContext());
2323
2324   // Allocate shadow area for Win64
2325   if (IsWin64) {
2326     CCInfo.AllocateStack(32, 8);
2327   }
2328
2329   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2330
2331   // Get a count of how many bytes are to be pushed on the stack.
2332   unsigned NumBytes = CCInfo.getNextStackOffset();
2333   if (IsSibcall)
2334     // This is a sibcall. The memory operands are available in caller's
2335     // own caller's stack.
2336     NumBytes = 0;
2337   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2338            IsTailCallConvention(CallConv))
2339     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2340
2341   int FPDiff = 0;
2342   if (isTailCall && !IsSibcall) {
2343     // Lower arguments at fp - stackoffset + fpdiff.
2344     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2345     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2346
2347     FPDiff = NumBytesCallerPushed - NumBytes;
2348
2349     // Set the delta of movement of the returnaddr stackslot.
2350     // But only set if delta is greater than previous delta.
2351     if (FPDiff < X86Info->getTCReturnAddrDelta())
2352       X86Info->setTCReturnAddrDelta(FPDiff);
2353   }
2354
2355   if (!IsSibcall)
2356     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
2357                                  dl);
2358
2359   SDValue RetAddrFrIdx;
2360   // Load return address for tail calls.
2361   if (isTailCall && FPDiff)
2362     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2363                                     Is64Bit, FPDiff, dl);
2364
2365   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2366   SmallVector<SDValue, 8> MemOpChains;
2367   SDValue StackPtr;
2368
2369   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2370   // of tail call optimization arguments are handle later.
2371   const X86RegisterInfo *RegInfo =
2372     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2373   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2374     CCValAssign &VA = ArgLocs[i];
2375     EVT RegVT = VA.getLocVT();
2376     SDValue Arg = OutVals[i];
2377     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2378     bool isByVal = Flags.isByVal();
2379
2380     // Promote the value if needed.
2381     switch (VA.getLocInfo()) {
2382     default: llvm_unreachable("Unknown loc info!");
2383     case CCValAssign::Full: break;
2384     case CCValAssign::SExt:
2385       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2386       break;
2387     case CCValAssign::ZExt:
2388       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2389       break;
2390     case CCValAssign::AExt:
2391       if (RegVT.is128BitVector()) {
2392         // Special case: passing MMX values in XMM registers.
2393         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2394         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2395         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2396       } else
2397         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2398       break;
2399     case CCValAssign::BCvt:
2400       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2401       break;
2402     case CCValAssign::Indirect: {
2403       // Store the argument.
2404       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2405       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2406       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2407                            MachinePointerInfo::getFixedStack(FI),
2408                            false, false, 0);
2409       Arg = SpillSlot;
2410       break;
2411     }
2412     }
2413
2414     if (VA.isRegLoc()) {
2415       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2416       if (isVarArg && IsWin64) {
2417         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2418         // shadow reg if callee is a varargs function.
2419         unsigned ShadowReg = 0;
2420         switch (VA.getLocReg()) {
2421         case X86::XMM0: ShadowReg = X86::RCX; break;
2422         case X86::XMM1: ShadowReg = X86::RDX; break;
2423         case X86::XMM2: ShadowReg = X86::R8; break;
2424         case X86::XMM3: ShadowReg = X86::R9; break;
2425         }
2426         if (ShadowReg)
2427           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2428       }
2429     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2430       assert(VA.isMemLoc());
2431       if (StackPtr.getNode() == 0)
2432         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2433                                       getPointerTy());
2434       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2435                                              dl, DAG, VA, Flags));
2436     }
2437   }
2438
2439   if (!MemOpChains.empty())
2440     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2441                         &MemOpChains[0], MemOpChains.size());
2442
2443   if (Subtarget->isPICStyleGOT()) {
2444     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2445     // GOT pointer.
2446     if (!isTailCall) {
2447       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2448                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2449     } else {
2450       // If we are tail calling and generating PIC/GOT style code load the
2451       // address of the callee into ECX. The value in ecx is used as target of
2452       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2453       // for tail calls on PIC/GOT architectures. Normally we would just put the
2454       // address of GOT into ebx and then call target@PLT. But for tail calls
2455       // ebx would be restored (since ebx is callee saved) before jumping to the
2456       // target@PLT.
2457
2458       // Note: The actual moving to ECX is done further down.
2459       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2460       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2461           !G->getGlobal()->hasProtectedVisibility())
2462         Callee = LowerGlobalAddress(Callee, DAG);
2463       else if (isa<ExternalSymbolSDNode>(Callee))
2464         Callee = LowerExternalSymbol(Callee, DAG);
2465     }
2466   }
2467
2468   if (Is64Bit && isVarArg && !IsWin64) {
2469     // From AMD64 ABI document:
2470     // For calls that may call functions that use varargs or stdargs
2471     // (prototype-less calls or calls to functions containing ellipsis (...) in
2472     // the declaration) %al is used as hidden argument to specify the number
2473     // of SSE registers used. The contents of %al do not need to match exactly
2474     // the number of registers, but must be an ubound on the number of SSE
2475     // registers used and is in the range 0 - 8 inclusive.
2476
2477     // Count the number of XMM registers allocated.
2478     static const uint16_t XMMArgRegs[] = {
2479       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2480       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2481     };
2482     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2483     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2484            && "SSE registers cannot be used when SSE is disabled");
2485
2486     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2487                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2488   }
2489
2490   // For tail calls lower the arguments to the 'real' stack slot.
2491   if (isTailCall) {
2492     // Force all the incoming stack arguments to be loaded from the stack
2493     // before any new outgoing arguments are stored to the stack, because the
2494     // outgoing stack slots may alias the incoming argument stack slots, and
2495     // the alias isn't otherwise explicit. This is slightly more conservative
2496     // than necessary, because it means that each store effectively depends
2497     // on every argument instead of just those arguments it would clobber.
2498     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2499
2500     SmallVector<SDValue, 8> MemOpChains2;
2501     SDValue FIN;
2502     int FI = 0;
2503     if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2504       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2505         CCValAssign &VA = ArgLocs[i];
2506         if (VA.isRegLoc())
2507           continue;
2508         assert(VA.isMemLoc());
2509         SDValue Arg = OutVals[i];
2510         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2511         // Create frame index.
2512         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2513         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2514         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2515         FIN = DAG.getFrameIndex(FI, getPointerTy());
2516
2517         if (Flags.isByVal()) {
2518           // Copy relative to framepointer.
2519           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2520           if (StackPtr.getNode() == 0)
2521             StackPtr = DAG.getCopyFromReg(Chain, dl,
2522                                           RegInfo->getStackRegister(),
2523                                           getPointerTy());
2524           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2525
2526           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2527                                                            ArgChain,
2528                                                            Flags, DAG, dl));
2529         } else {
2530           // Store relative to framepointer.
2531           MemOpChains2.push_back(
2532             DAG.getStore(ArgChain, dl, Arg, FIN,
2533                          MachinePointerInfo::getFixedStack(FI),
2534                          false, false, 0));
2535         }
2536       }
2537     }
2538
2539     if (!MemOpChains2.empty())
2540       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2541                           &MemOpChains2[0], MemOpChains2.size());
2542
2543     // Store the return address to the appropriate stack slot.
2544     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2545                                      getPointerTy(), RegInfo->getSlotSize(),
2546                                      FPDiff, dl);
2547   }
2548
2549   // Build a sequence of copy-to-reg nodes chained together with token chain
2550   // and flag operands which copy the outgoing args into registers.
2551   SDValue InFlag;
2552   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2553     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2554                              RegsToPass[i].second, InFlag);
2555     InFlag = Chain.getValue(1);
2556   }
2557
2558   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2559     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2560     // In the 64-bit large code model, we have to make all calls
2561     // through a register, since the call instruction's 32-bit
2562     // pc-relative offset may not be large enough to hold the whole
2563     // address.
2564   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2565     // If the callee is a GlobalAddress node (quite common, every direct call
2566     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2567     // it.
2568
2569     // We should use extra load for direct calls to dllimported functions in
2570     // non-JIT mode.
2571     const GlobalValue *GV = G->getGlobal();
2572     if (!GV->hasDLLImportLinkage()) {
2573       unsigned char OpFlags = 0;
2574       bool ExtraLoad = false;
2575       unsigned WrapperKind = ISD::DELETED_NODE;
2576
2577       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2578       // external symbols most go through the PLT in PIC mode.  If the symbol
2579       // has hidden or protected visibility, or if it is static or local, then
2580       // we don't need to use the PLT - we can directly call it.
2581       if (Subtarget->isTargetELF() &&
2582           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2583           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2584         OpFlags = X86II::MO_PLT;
2585       } else if (Subtarget->isPICStyleStubAny() &&
2586                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2587                  (!Subtarget->getTargetTriple().isMacOSX() ||
2588                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2589         // PC-relative references to external symbols should go through $stub,
2590         // unless we're building with the leopard linker or later, which
2591         // automatically synthesizes these stubs.
2592         OpFlags = X86II::MO_DARWIN_STUB;
2593       } else if (Subtarget->isPICStyleRIPRel() &&
2594                  isa<Function>(GV) &&
2595                  cast<Function>(GV)->getAttributes().
2596                    hasAttribute(AttributeSet::FunctionIndex,
2597                                 Attribute::NonLazyBind)) {
2598         // If the function is marked as non-lazy, generate an indirect call
2599         // which loads from the GOT directly. This avoids runtime overhead
2600         // at the cost of eager binding (and one extra byte of encoding).
2601         OpFlags = X86II::MO_GOTPCREL;
2602         WrapperKind = X86ISD::WrapperRIP;
2603         ExtraLoad = true;
2604       }
2605
2606       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2607                                           G->getOffset(), OpFlags);
2608
2609       // Add a wrapper if needed.
2610       if (WrapperKind != ISD::DELETED_NODE)
2611         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2612       // Add extra indirection if needed.
2613       if (ExtraLoad)
2614         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2615                              MachinePointerInfo::getGOT(),
2616                              false, false, false, 0);
2617     }
2618   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2619     unsigned char OpFlags = 0;
2620
2621     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2622     // external symbols should go through the PLT.
2623     if (Subtarget->isTargetELF() &&
2624         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2625       OpFlags = X86II::MO_PLT;
2626     } else if (Subtarget->isPICStyleStubAny() &&
2627                (!Subtarget->getTargetTriple().isMacOSX() ||
2628                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2629       // PC-relative references to external symbols should go through $stub,
2630       // unless we're building with the leopard linker or later, which
2631       // automatically synthesizes these stubs.
2632       OpFlags = X86II::MO_DARWIN_STUB;
2633     }
2634
2635     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2636                                          OpFlags);
2637   }
2638
2639   // Returns a chain & a flag for retval copy to use.
2640   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2641   SmallVector<SDValue, 8> Ops;
2642
2643   if (!IsSibcall && isTailCall) {
2644     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2645                            DAG.getIntPtrConstant(0, true), InFlag, dl);
2646     InFlag = Chain.getValue(1);
2647   }
2648
2649   Ops.push_back(Chain);
2650   Ops.push_back(Callee);
2651
2652   if (isTailCall)
2653     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2654
2655   // Add argument registers to the end of the list so that they are known live
2656   // into the call.
2657   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2658     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2659                                   RegsToPass[i].second.getValueType()));
2660
2661   // Add a register mask operand representing the call-preserved registers.
2662   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2663   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2664   assert(Mask && "Missing call preserved mask for calling convention");
2665   Ops.push_back(DAG.getRegisterMask(Mask));
2666
2667   if (InFlag.getNode())
2668     Ops.push_back(InFlag);
2669
2670   if (isTailCall) {
2671     // We used to do:
2672     //// If this is the first return lowered for this function, add the regs
2673     //// to the liveout set for the function.
2674     // This isn't right, although it's probably harmless on x86; liveouts
2675     // should be computed from returns not tail calls.  Consider a void
2676     // function making a tail call to a function returning int.
2677     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
2678   }
2679
2680   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2681   InFlag = Chain.getValue(1);
2682
2683   // Create the CALLSEQ_END node.
2684   unsigned NumBytesForCalleeToPush;
2685   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2686                        getTargetMachine().Options.GuaranteedTailCallOpt))
2687     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2688   else if (!Is64Bit && !IsTailCallConvention(CallConv) && !IsWindows &&
2689            SR == StackStructReturn)
2690     // If this is a call to a struct-return function, the callee
2691     // pops the hidden struct pointer, so we have to push it back.
2692     // This is common for Darwin/X86, Linux & Mingw32 targets.
2693     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2694     NumBytesForCalleeToPush = 4;
2695   else
2696     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2697
2698   // Returns a flag for retval copy to use.
2699   if (!IsSibcall) {
2700     Chain = DAG.getCALLSEQ_END(Chain,
2701                                DAG.getIntPtrConstant(NumBytes, true),
2702                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2703                                                      true),
2704                                InFlag, dl);
2705     InFlag = Chain.getValue(1);
2706   }
2707
2708   // Handle result values, copying them out of physregs into vregs that we
2709   // return.
2710   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2711                          Ins, dl, DAG, InVals);
2712 }
2713
2714 //===----------------------------------------------------------------------===//
2715 //                Fast Calling Convention (tail call) implementation
2716 //===----------------------------------------------------------------------===//
2717
2718 //  Like std call, callee cleans arguments, convention except that ECX is
2719 //  reserved for storing the tail called function address. Only 2 registers are
2720 //  free for argument passing (inreg). Tail call optimization is performed
2721 //  provided:
2722 //                * tailcallopt is enabled
2723 //                * caller/callee are fastcc
2724 //  On X86_64 architecture with GOT-style position independent code only local
2725 //  (within module) calls are supported at the moment.
2726 //  To keep the stack aligned according to platform abi the function
2727 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2728 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2729 //  If a tail called function callee has more arguments than the caller the
2730 //  caller needs to make sure that there is room to move the RETADDR to. This is
2731 //  achieved by reserving an area the size of the argument delta right after the
2732 //  original REtADDR, but before the saved framepointer or the spilled registers
2733 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2734 //  stack layout:
2735 //    arg1
2736 //    arg2
2737 //    RETADDR
2738 //    [ new RETADDR
2739 //      move area ]
2740 //    (possible EBP)
2741 //    ESI
2742 //    EDI
2743 //    local1 ..
2744
2745 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2746 /// for a 16 byte align requirement.
2747 unsigned
2748 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2749                                                SelectionDAG& DAG) const {
2750   MachineFunction &MF = DAG.getMachineFunction();
2751   const TargetMachine &TM = MF.getTarget();
2752   const X86RegisterInfo *RegInfo =
2753     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
2754   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2755   unsigned StackAlignment = TFI.getStackAlignment();
2756   uint64_t AlignMask = StackAlignment - 1;
2757   int64_t Offset = StackSize;
2758   unsigned SlotSize = RegInfo->getSlotSize();
2759   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2760     // Number smaller than 12 so just add the difference.
2761     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2762   } else {
2763     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2764     Offset = ((~AlignMask) & Offset) + StackAlignment +
2765       (StackAlignment-SlotSize);
2766   }
2767   return Offset;
2768 }
2769
2770 /// MatchingStackOffset - Return true if the given stack call argument is
2771 /// already available in the same position (relatively) of the caller's
2772 /// incoming argument stack.
2773 static
2774 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2775                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2776                          const X86InstrInfo *TII) {
2777   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2778   int FI = INT_MAX;
2779   if (Arg.getOpcode() == ISD::CopyFromReg) {
2780     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2781     if (!TargetRegisterInfo::isVirtualRegister(VR))
2782       return false;
2783     MachineInstr *Def = MRI->getVRegDef(VR);
2784     if (!Def)
2785       return false;
2786     if (!Flags.isByVal()) {
2787       if (!TII->isLoadFromStackSlot(Def, FI))
2788         return false;
2789     } else {
2790       unsigned Opcode = Def->getOpcode();
2791       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2792           Def->getOperand(1).isFI()) {
2793         FI = Def->getOperand(1).getIndex();
2794         Bytes = Flags.getByValSize();
2795       } else
2796         return false;
2797     }
2798   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2799     if (Flags.isByVal())
2800       // ByVal argument is passed in as a pointer but it's now being
2801       // dereferenced. e.g.
2802       // define @foo(%struct.X* %A) {
2803       //   tail call @bar(%struct.X* byval %A)
2804       // }
2805       return false;
2806     SDValue Ptr = Ld->getBasePtr();
2807     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2808     if (!FINode)
2809       return false;
2810     FI = FINode->getIndex();
2811   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2812     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2813     FI = FINode->getIndex();
2814     Bytes = Flags.getByValSize();
2815   } else
2816     return false;
2817
2818   assert(FI != INT_MAX);
2819   if (!MFI->isFixedObjectIndex(FI))
2820     return false;
2821   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2822 }
2823
2824 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2825 /// for tail call optimization. Targets which want to do tail call
2826 /// optimization should implement this function.
2827 bool
2828 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2829                                                      CallingConv::ID CalleeCC,
2830                                                      bool isVarArg,
2831                                                      bool isCalleeStructRet,
2832                                                      bool isCallerStructRet,
2833                                                      Type *RetTy,
2834                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2835                                     const SmallVectorImpl<SDValue> &OutVals,
2836                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2837                                                      SelectionDAG &DAG) const {
2838   if (!IsTailCallConvention(CalleeCC) &&
2839       CalleeCC != CallingConv::C)
2840     return false;
2841
2842   // If -tailcallopt is specified, make fastcc functions tail-callable.
2843   const MachineFunction &MF = DAG.getMachineFunction();
2844   const Function *CallerF = DAG.getMachineFunction().getFunction();
2845
2846   // If the function return type is x86_fp80 and the callee return type is not,
2847   // then the FP_EXTEND of the call result is not a nop. It's not safe to
2848   // perform a tailcall optimization here.
2849   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
2850     return false;
2851
2852   CallingConv::ID CallerCC = CallerF->getCallingConv();
2853   bool CCMatch = CallerCC == CalleeCC;
2854
2855   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2856     if (IsTailCallConvention(CalleeCC) && CCMatch)
2857       return true;
2858     return false;
2859   }
2860
2861   // Look for obvious safe cases to perform tail call optimization that do not
2862   // require ABI changes. This is what gcc calls sibcall.
2863
2864   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2865   // emit a special epilogue.
2866   const X86RegisterInfo *RegInfo =
2867     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2868   if (RegInfo->needsStackRealignment(MF))
2869     return false;
2870
2871   // Also avoid sibcall optimization if either caller or callee uses struct
2872   // return semantics.
2873   if (isCalleeStructRet || isCallerStructRet)
2874     return false;
2875
2876   // An stdcall caller is expected to clean up its arguments; the callee
2877   // isn't going to do that.
2878   if (!CCMatch && CallerCC == CallingConv::X86_StdCall)
2879     return false;
2880
2881   // Do not sibcall optimize vararg calls unless all arguments are passed via
2882   // registers.
2883   if (isVarArg && !Outs.empty()) {
2884
2885     // Optimizing for varargs on Win64 is unlikely to be safe without
2886     // additional testing.
2887     if (Subtarget->isTargetWin64())
2888       return false;
2889
2890     SmallVector<CCValAssign, 16> ArgLocs;
2891     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2892                    getTargetMachine(), ArgLocs, *DAG.getContext());
2893
2894     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2895     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2896       if (!ArgLocs[i].isRegLoc())
2897         return false;
2898   }
2899
2900   // If the call result is in ST0 / ST1, it needs to be popped off the x87
2901   // stack.  Therefore, if it's not used by the call it is not safe to optimize
2902   // this into a sibcall.
2903   bool Unused = false;
2904   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2905     if (!Ins[i].Used) {
2906       Unused = true;
2907       break;
2908     }
2909   }
2910   if (Unused) {
2911     SmallVector<CCValAssign, 16> RVLocs;
2912     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2913                    getTargetMachine(), RVLocs, *DAG.getContext());
2914     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2915     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2916       CCValAssign &VA = RVLocs[i];
2917       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2918         return false;
2919     }
2920   }
2921
2922   // If the calling conventions do not match, then we'd better make sure the
2923   // results are returned in the same way as what the caller expects.
2924   if (!CCMatch) {
2925     SmallVector<CCValAssign, 16> RVLocs1;
2926     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2927                     getTargetMachine(), RVLocs1, *DAG.getContext());
2928     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2929
2930     SmallVector<CCValAssign, 16> RVLocs2;
2931     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2932                     getTargetMachine(), RVLocs2, *DAG.getContext());
2933     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2934
2935     if (RVLocs1.size() != RVLocs2.size())
2936       return false;
2937     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2938       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2939         return false;
2940       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2941         return false;
2942       if (RVLocs1[i].isRegLoc()) {
2943         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2944           return false;
2945       } else {
2946         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2947           return false;
2948       }
2949     }
2950   }
2951
2952   // If the callee takes no arguments then go on to check the results of the
2953   // call.
2954   if (!Outs.empty()) {
2955     // Check if stack adjustment is needed. For now, do not do this if any
2956     // argument is passed on the stack.
2957     SmallVector<CCValAssign, 16> ArgLocs;
2958     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2959                    getTargetMachine(), ArgLocs, *DAG.getContext());
2960
2961     // Allocate shadow area for Win64
2962     if (Subtarget->isTargetWin64()) {
2963       CCInfo.AllocateStack(32, 8);
2964     }
2965
2966     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2967     if (CCInfo.getNextStackOffset()) {
2968       MachineFunction &MF = DAG.getMachineFunction();
2969       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2970         return false;
2971
2972       // Check if the arguments are already laid out in the right way as
2973       // the caller's fixed stack objects.
2974       MachineFrameInfo *MFI = MF.getFrameInfo();
2975       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2976       const X86InstrInfo *TII =
2977         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
2978       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2979         CCValAssign &VA = ArgLocs[i];
2980         SDValue Arg = OutVals[i];
2981         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2982         if (VA.getLocInfo() == CCValAssign::Indirect)
2983           return false;
2984         if (!VA.isRegLoc()) {
2985           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2986                                    MFI, MRI, TII))
2987             return false;
2988         }
2989       }
2990     }
2991
2992     // If the tailcall address may be in a register, then make sure it's
2993     // possible to register allocate for it. In 32-bit, the call address can
2994     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2995     // callee-saved registers are restored. These happen to be the same
2996     // registers used to pass 'inreg' arguments so watch out for those.
2997     if (!Subtarget->is64Bit() &&
2998         ((!isa<GlobalAddressSDNode>(Callee) &&
2999           !isa<ExternalSymbolSDNode>(Callee)) ||
3000          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3001       unsigned NumInRegs = 0;
3002       // In PIC we need an extra register to formulate the address computation
3003       // for the callee.
3004       unsigned MaxInRegs =
3005           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3006
3007       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3008         CCValAssign &VA = ArgLocs[i];
3009         if (!VA.isRegLoc())
3010           continue;
3011         unsigned Reg = VA.getLocReg();
3012         switch (Reg) {
3013         default: break;
3014         case X86::EAX: case X86::EDX: case X86::ECX:
3015           if (++NumInRegs == MaxInRegs)
3016             return false;
3017           break;
3018         }
3019       }
3020     }
3021   }
3022
3023   return true;
3024 }
3025
3026 FastISel *
3027 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3028                                   const TargetLibraryInfo *libInfo) const {
3029   return X86::createFastISel(funcInfo, libInfo);
3030 }
3031
3032 //===----------------------------------------------------------------------===//
3033 //                           Other Lowering Hooks
3034 //===----------------------------------------------------------------------===//
3035
3036 static bool MayFoldLoad(SDValue Op) {
3037   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3038 }
3039
3040 static bool MayFoldIntoStore(SDValue Op) {
3041   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3042 }
3043
3044 static bool isTargetShuffle(unsigned Opcode) {
3045   switch(Opcode) {
3046   default: return false;
3047   case X86ISD::PSHUFD:
3048   case X86ISD::PSHUFHW:
3049   case X86ISD::PSHUFLW:
3050   case X86ISD::SHUFP:
3051   case X86ISD::PALIGNR:
3052   case X86ISD::MOVLHPS:
3053   case X86ISD::MOVLHPD:
3054   case X86ISD::MOVHLPS:
3055   case X86ISD::MOVLPS:
3056   case X86ISD::MOVLPD:
3057   case X86ISD::MOVSHDUP:
3058   case X86ISD::MOVSLDUP:
3059   case X86ISD::MOVDDUP:
3060   case X86ISD::MOVSS:
3061   case X86ISD::MOVSD:
3062   case X86ISD::UNPCKL:
3063   case X86ISD::UNPCKH:
3064   case X86ISD::VPERMILP:
3065   case X86ISD::VPERM2X128:
3066   case X86ISD::VPERMI:
3067     return true;
3068   }
3069 }
3070
3071 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3072                                     SDValue V1, SelectionDAG &DAG) {
3073   switch(Opc) {
3074   default: llvm_unreachable("Unknown x86 shuffle node");
3075   case X86ISD::MOVSHDUP:
3076   case X86ISD::MOVSLDUP:
3077   case X86ISD::MOVDDUP:
3078     return DAG.getNode(Opc, dl, VT, V1);
3079   }
3080 }
3081
3082 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3083                                     SDValue V1, unsigned TargetMask,
3084                                     SelectionDAG &DAG) {
3085   switch(Opc) {
3086   default: llvm_unreachable("Unknown x86 shuffle node");
3087   case X86ISD::PSHUFD:
3088   case X86ISD::PSHUFHW:
3089   case X86ISD::PSHUFLW:
3090   case X86ISD::VPERMILP:
3091   case X86ISD::VPERMI:
3092     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3093   }
3094 }
3095
3096 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3097                                     SDValue V1, SDValue V2, unsigned TargetMask,
3098                                     SelectionDAG &DAG) {
3099   switch(Opc) {
3100   default: llvm_unreachable("Unknown x86 shuffle node");
3101   case X86ISD::PALIGNR:
3102   case X86ISD::SHUFP:
3103   case X86ISD::VPERM2X128:
3104     return DAG.getNode(Opc, dl, VT, V1, V2,
3105                        DAG.getConstant(TargetMask, MVT::i8));
3106   }
3107 }
3108
3109 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3110                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3111   switch(Opc) {
3112   default: llvm_unreachable("Unknown x86 shuffle node");
3113   case X86ISD::MOVLHPS:
3114   case X86ISD::MOVLHPD:
3115   case X86ISD::MOVHLPS:
3116   case X86ISD::MOVLPS:
3117   case X86ISD::MOVLPD:
3118   case X86ISD::MOVSS:
3119   case X86ISD::MOVSD:
3120   case X86ISD::UNPCKL:
3121   case X86ISD::UNPCKH:
3122     return DAG.getNode(Opc, dl, VT, V1, V2);
3123   }
3124 }
3125
3126 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3127   MachineFunction &MF = DAG.getMachineFunction();
3128   const X86RegisterInfo *RegInfo =
3129     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
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   SDLoc dl(SVOp);
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, SDLoc(SVOp), 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, SDLoc 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,
4426                         array_lengthof(Ops));
4427     } else {
4428       // 256-bit logic and arithmetic instructions in AVX are all
4429       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4430       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4431       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4432       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops,
4433                         array_lengthof(Ops));
4434     }
4435   } else
4436     llvm_unreachable("Unexpected vector type");
4437
4438   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4439 }
4440
4441 /// getOnesVector - Returns a vector of specified type with all bits set.
4442 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4443 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4444 /// Then bitcast to their original type, ensuring they get CSE'd.
4445 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4446                              SDLoc dl) {
4447   assert(VT.isVector() && "Expected a vector type");
4448
4449   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4450   SDValue Vec;
4451   if (VT.is256BitVector()) {
4452     if (HasInt256) { // AVX2
4453       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4454       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops,
4455                         array_lengthof(Ops));
4456     } else { // AVX
4457       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4458       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4459     }
4460   } else if (VT.is128BitVector()) {
4461     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4462   } else
4463     llvm_unreachable("Unexpected vector type");
4464
4465   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4466 }
4467
4468 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4469 /// that point to V2 points to its first element.
4470 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4471   for (unsigned i = 0; i != NumElems; ++i) {
4472     if (Mask[i] > (int)NumElems) {
4473       Mask[i] = NumElems;
4474     }
4475   }
4476 }
4477
4478 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4479 /// operation of specified width.
4480 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4481                        SDValue V2) {
4482   unsigned NumElems = VT.getVectorNumElements();
4483   SmallVector<int, 8> Mask;
4484   Mask.push_back(NumElems);
4485   for (unsigned i = 1; i != NumElems; ++i)
4486     Mask.push_back(i);
4487   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4488 }
4489
4490 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4491 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4492                           SDValue V2) {
4493   unsigned NumElems = VT.getVectorNumElements();
4494   SmallVector<int, 8> Mask;
4495   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4496     Mask.push_back(i);
4497     Mask.push_back(i + NumElems);
4498   }
4499   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4500 }
4501
4502 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4503 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4504                           SDValue V2) {
4505   unsigned NumElems = VT.getVectorNumElements();
4506   SmallVector<int, 8> Mask;
4507   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4508     Mask.push_back(i + Half);
4509     Mask.push_back(i + NumElems + Half);
4510   }
4511   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4512 }
4513
4514 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4515 // a generic shuffle instruction because the target has no such instructions.
4516 // Generate shuffles which repeat i16 and i8 several times until they can be
4517 // represented by v4f32 and then be manipulated by target suported shuffles.
4518 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4519   EVT VT = V.getValueType();
4520   int NumElems = VT.getVectorNumElements();
4521   SDLoc dl(V);
4522
4523   while (NumElems > 4) {
4524     if (EltNo < NumElems/2) {
4525       V = getUnpackl(DAG, dl, VT, V, V);
4526     } else {
4527       V = getUnpackh(DAG, dl, VT, V, V);
4528       EltNo -= NumElems/2;
4529     }
4530     NumElems >>= 1;
4531   }
4532   return V;
4533 }
4534
4535 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4536 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4537   EVT VT = V.getValueType();
4538   SDLoc dl(V);
4539
4540   if (VT.is128BitVector()) {
4541     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4542     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4543     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4544                              &SplatMask[0]);
4545   } else if (VT.is256BitVector()) {
4546     // To use VPERMILPS to splat scalars, the second half of indicies must
4547     // refer to the higher part, which is a duplication of the lower one,
4548     // because VPERMILPS can only handle in-lane permutations.
4549     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4550                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4551
4552     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4553     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4554                              &SplatMask[0]);
4555   } else
4556     llvm_unreachable("Vector size not supported");
4557
4558   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4559 }
4560
4561 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4562 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4563   EVT SrcVT = SV->getValueType(0);
4564   SDValue V1 = SV->getOperand(0);
4565   SDLoc dl(SV);
4566
4567   int EltNo = SV->getSplatIndex();
4568   int NumElems = SrcVT.getVectorNumElements();
4569   bool Is256BitVec = SrcVT.is256BitVector();
4570
4571   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
4572          "Unknown how to promote splat for type");
4573
4574   // Extract the 128-bit part containing the splat element and update
4575   // the splat element index when it refers to the higher register.
4576   if (Is256BitVec) {
4577     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
4578     if (EltNo >= NumElems/2)
4579       EltNo -= NumElems/2;
4580   }
4581
4582   // All i16 and i8 vector types can't be used directly by a generic shuffle
4583   // instruction because the target has no such instruction. Generate shuffles
4584   // which repeat i16 and i8 several times until they fit in i32, and then can
4585   // be manipulated by target suported shuffles.
4586   EVT EltVT = SrcVT.getVectorElementType();
4587   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4588     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4589
4590   // Recreate the 256-bit vector and place the same 128-bit vector
4591   // into the low and high part. This is necessary because we want
4592   // to use VPERM* to shuffle the vectors
4593   if (Is256BitVec) {
4594     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
4595   }
4596
4597   return getLegalSplat(DAG, V1, EltNo);
4598 }
4599
4600 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4601 /// vector of zero or undef vector.  This produces a shuffle where the low
4602 /// element of V2 is swizzled into the zero/undef vector, landing at element
4603 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4604 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4605                                            bool IsZero,
4606                                            const X86Subtarget *Subtarget,
4607                                            SelectionDAG &DAG) {
4608   EVT VT = V2.getValueType();
4609   SDValue V1 = IsZero
4610     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4611   unsigned NumElems = VT.getVectorNumElements();
4612   SmallVector<int, 16> MaskVec;
4613   for (unsigned i = 0; i != NumElems; ++i)
4614     // If this is the insertion idx, put the low elt of V2 here.
4615     MaskVec.push_back(i == Idx ? NumElems : i);
4616   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4617 }
4618
4619 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4620 /// target specific opcode. Returns true if the Mask could be calculated.
4621 /// Sets IsUnary to true if only uses one source.
4622 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4623                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4624   unsigned NumElems = VT.getVectorNumElements();
4625   SDValue ImmN;
4626
4627   IsUnary = false;
4628   switch(N->getOpcode()) {
4629   case X86ISD::SHUFP:
4630     ImmN = N->getOperand(N->getNumOperands()-1);
4631     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4632     break;
4633   case X86ISD::UNPCKH:
4634     DecodeUNPCKHMask(VT, Mask);
4635     break;
4636   case X86ISD::UNPCKL:
4637     DecodeUNPCKLMask(VT, Mask);
4638     break;
4639   case X86ISD::MOVHLPS:
4640     DecodeMOVHLPSMask(NumElems, Mask);
4641     break;
4642   case X86ISD::MOVLHPS:
4643     DecodeMOVLHPSMask(NumElems, Mask);
4644     break;
4645   case X86ISD::PALIGNR:
4646     ImmN = N->getOperand(N->getNumOperands()-1);
4647     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4648     break;
4649   case X86ISD::PSHUFD:
4650   case X86ISD::VPERMILP:
4651     ImmN = N->getOperand(N->getNumOperands()-1);
4652     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4653     IsUnary = true;
4654     break;
4655   case X86ISD::PSHUFHW:
4656     ImmN = N->getOperand(N->getNumOperands()-1);
4657     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4658     IsUnary = true;
4659     break;
4660   case X86ISD::PSHUFLW:
4661     ImmN = N->getOperand(N->getNumOperands()-1);
4662     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4663     IsUnary = true;
4664     break;
4665   case X86ISD::VPERMI:
4666     ImmN = N->getOperand(N->getNumOperands()-1);
4667     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4668     IsUnary = true;
4669     break;
4670   case X86ISD::MOVSS:
4671   case X86ISD::MOVSD: {
4672     // The index 0 always comes from the first element of the second source,
4673     // this is why MOVSS and MOVSD are used in the first place. The other
4674     // elements come from the other positions of the first source vector
4675     Mask.push_back(NumElems);
4676     for (unsigned i = 1; i != NumElems; ++i) {
4677       Mask.push_back(i);
4678     }
4679     break;
4680   }
4681   case X86ISD::VPERM2X128:
4682     ImmN = N->getOperand(N->getNumOperands()-1);
4683     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4684     if (Mask.empty()) return false;
4685     break;
4686   case X86ISD::MOVDDUP:
4687   case X86ISD::MOVLHPD:
4688   case X86ISD::MOVLPD:
4689   case X86ISD::MOVLPS:
4690   case X86ISD::MOVSHDUP:
4691   case X86ISD::MOVSLDUP:
4692     // Not yet implemented
4693     return false;
4694   default: llvm_unreachable("unknown target shuffle node");
4695   }
4696
4697   return true;
4698 }
4699
4700 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4701 /// element of the result of the vector shuffle.
4702 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4703                                    unsigned Depth) {
4704   if (Depth == 6)
4705     return SDValue();  // Limit search depth.
4706
4707   SDValue V = SDValue(N, 0);
4708   EVT VT = V.getValueType();
4709   unsigned Opcode = V.getOpcode();
4710
4711   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4712   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4713     int Elt = SV->getMaskElt(Index);
4714
4715     if (Elt < 0)
4716       return DAG.getUNDEF(VT.getVectorElementType());
4717
4718     unsigned NumElems = VT.getVectorNumElements();
4719     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4720                                          : SV->getOperand(1);
4721     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4722   }
4723
4724   // Recurse into target specific vector shuffles to find scalars.
4725   if (isTargetShuffle(Opcode)) {
4726     MVT ShufVT = V.getValueType().getSimpleVT();
4727     unsigned NumElems = ShufVT.getVectorNumElements();
4728     SmallVector<int, 16> ShuffleMask;
4729     bool IsUnary;
4730
4731     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4732       return SDValue();
4733
4734     int Elt = ShuffleMask[Index];
4735     if (Elt < 0)
4736       return DAG.getUNDEF(ShufVT.getVectorElementType());
4737
4738     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4739                                          : N->getOperand(1);
4740     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4741                                Depth+1);
4742   }
4743
4744   // Actual nodes that may contain scalar elements
4745   if (Opcode == ISD::BITCAST) {
4746     V = V.getOperand(0);
4747     EVT SrcVT = V.getValueType();
4748     unsigned NumElems = VT.getVectorNumElements();
4749
4750     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4751       return SDValue();
4752   }
4753
4754   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4755     return (Index == 0) ? V.getOperand(0)
4756                         : DAG.getUNDEF(VT.getVectorElementType());
4757
4758   if (V.getOpcode() == ISD::BUILD_VECTOR)
4759     return V.getOperand(Index);
4760
4761   return SDValue();
4762 }
4763
4764 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4765 /// shuffle operation which come from a consecutively from a zero. The
4766 /// search can start in two different directions, from left or right.
4767 /// We count undefs as zeros until PreferredNum is reached.
4768 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
4769                                          unsigned NumElems, bool ZerosFromLeft,
4770                                          SelectionDAG &DAG,
4771                                          unsigned PreferredNum = -1U) {
4772   unsigned NumZeros = 0;
4773   for (unsigned i = 0; i != NumElems; ++i) {
4774     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
4775     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
4776     if (!Elt.getNode())
4777       break;
4778
4779     if (X86::isZeroNode(Elt))
4780       ++NumZeros;
4781     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
4782       NumZeros = std::min(NumZeros + 1, PreferredNum);
4783     else
4784       break;
4785   }
4786
4787   return NumZeros;
4788 }
4789
4790 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
4791 /// correspond consecutively to elements from one of the vector operands,
4792 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4793 static
4794 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
4795                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
4796                               unsigned NumElems, unsigned &OpNum) {
4797   bool SeenV1 = false;
4798   bool SeenV2 = false;
4799
4800   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
4801     int Idx = SVOp->getMaskElt(i);
4802     // Ignore undef indicies
4803     if (Idx < 0)
4804       continue;
4805
4806     if (Idx < (int)NumElems)
4807       SeenV1 = true;
4808     else
4809       SeenV2 = true;
4810
4811     // Only accept consecutive elements from the same vector
4812     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4813       return false;
4814   }
4815
4816   OpNum = SeenV1 ? 0 : 1;
4817   return true;
4818 }
4819
4820 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4821 /// logical left shift of a vector.
4822 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4823                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4824   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4825   unsigned NumZeros = getNumOfConsecutiveZeros(
4826       SVOp, NumElems, false /* check zeros from right */, DAG,
4827       SVOp->getMaskElt(0));
4828   unsigned OpSrc;
4829
4830   if (!NumZeros)
4831     return false;
4832
4833   // Considering the elements in the mask that are not consecutive zeros,
4834   // check if they consecutively come from only one of the source vectors.
4835   //
4836   //               V1 = {X, A, B, C}     0
4837   //                         \  \  \    /
4838   //   vector_shuffle V1, V2 <1, 2, 3, X>
4839   //
4840   if (!isShuffleMaskConsecutive(SVOp,
4841             0,                   // Mask Start Index
4842             NumElems-NumZeros,   // Mask End Index(exclusive)
4843             NumZeros,            // Where to start looking in the src vector
4844             NumElems,            // Number of elements in vector
4845             OpSrc))              // Which source operand ?
4846     return false;
4847
4848   isLeft = false;
4849   ShAmt = NumZeros;
4850   ShVal = SVOp->getOperand(OpSrc);
4851   return true;
4852 }
4853
4854 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
4855 /// logical left shift of a vector.
4856 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4857                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4858   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4859   unsigned NumZeros = getNumOfConsecutiveZeros(
4860       SVOp, NumElems, true /* check zeros from left */, DAG,
4861       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
4862   unsigned OpSrc;
4863
4864   if (!NumZeros)
4865     return false;
4866
4867   // Considering the elements in the mask that are not consecutive zeros,
4868   // check if they consecutively come from only one of the source vectors.
4869   //
4870   //                           0    { A, B, X, X } = V2
4871   //                          / \    /  /
4872   //   vector_shuffle V1, V2 <X, X, 4, 5>
4873   //
4874   if (!isShuffleMaskConsecutive(SVOp,
4875             NumZeros,     // Mask Start Index
4876             NumElems,     // Mask End Index(exclusive)
4877             0,            // Where to start looking in the src vector
4878             NumElems,     // Number of elements in vector
4879             OpSrc))       // Which source operand ?
4880     return false;
4881
4882   isLeft = true;
4883   ShAmt = NumZeros;
4884   ShVal = SVOp->getOperand(OpSrc);
4885   return true;
4886 }
4887
4888 /// isVectorShift - Returns true if the shuffle can be implemented as a
4889 /// logical left or right shift of a vector.
4890 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4891                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4892   // Although the logic below support any bitwidth size, there are no
4893   // shift instructions which handle more than 128-bit vectors.
4894   if (!SVOp->getValueType(0).is128BitVector())
4895     return false;
4896
4897   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4898       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4899     return true;
4900
4901   return false;
4902 }
4903
4904 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4905 ///
4906 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4907                                        unsigned NumNonZero, unsigned NumZero,
4908                                        SelectionDAG &DAG,
4909                                        const X86Subtarget* Subtarget,
4910                                        const TargetLowering &TLI) {
4911   if (NumNonZero > 8)
4912     return SDValue();
4913
4914   SDLoc dl(Op);
4915   SDValue V(0, 0);
4916   bool First = true;
4917   for (unsigned i = 0; i < 16; ++i) {
4918     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4919     if (ThisIsNonZero && First) {
4920       if (NumZero)
4921         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4922       else
4923         V = DAG.getUNDEF(MVT::v8i16);
4924       First = false;
4925     }
4926
4927     if ((i & 1) != 0) {
4928       SDValue ThisElt(0, 0), LastElt(0, 0);
4929       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4930       if (LastIsNonZero) {
4931         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4932                               MVT::i16, Op.getOperand(i-1));
4933       }
4934       if (ThisIsNonZero) {
4935         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4936         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4937                               ThisElt, DAG.getConstant(8, MVT::i8));
4938         if (LastIsNonZero)
4939           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4940       } else
4941         ThisElt = LastElt;
4942
4943       if (ThisElt.getNode())
4944         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4945                         DAG.getIntPtrConstant(i/2));
4946     }
4947   }
4948
4949   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4950 }
4951
4952 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4953 ///
4954 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4955                                      unsigned NumNonZero, unsigned NumZero,
4956                                      SelectionDAG &DAG,
4957                                      const X86Subtarget* Subtarget,
4958                                      const TargetLowering &TLI) {
4959   if (NumNonZero > 4)
4960     return SDValue();
4961
4962   SDLoc dl(Op);
4963   SDValue V(0, 0);
4964   bool First = true;
4965   for (unsigned i = 0; i < 8; ++i) {
4966     bool isNonZero = (NonZeros & (1 << i)) != 0;
4967     if (isNonZero) {
4968       if (First) {
4969         if (NumZero)
4970           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4971         else
4972           V = DAG.getUNDEF(MVT::v8i16);
4973         First = false;
4974       }
4975       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4976                       MVT::v8i16, V, Op.getOperand(i),
4977                       DAG.getIntPtrConstant(i));
4978     }
4979   }
4980
4981   return V;
4982 }
4983
4984 /// getVShift - Return a vector logical shift node.
4985 ///
4986 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4987                          unsigned NumBits, SelectionDAG &DAG,
4988                          const TargetLowering &TLI, SDLoc dl) {
4989   assert(VT.is128BitVector() && "Unknown type for VShift");
4990   EVT ShVT = MVT::v2i64;
4991   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4992   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4993   return DAG.getNode(ISD::BITCAST, dl, VT,
4994                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4995                              DAG.getConstant(NumBits,
4996                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
4997 }
4998
4999 SDValue
5000 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, SDLoc dl,
5001                                           SelectionDAG &DAG) const {
5002
5003   // Check if the scalar load can be widened into a vector load. And if
5004   // the address is "base + cst" see if the cst can be "absorbed" into
5005   // the shuffle mask.
5006   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5007     SDValue Ptr = LD->getBasePtr();
5008     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5009       return SDValue();
5010     EVT PVT = LD->getValueType(0);
5011     if (PVT != MVT::i32 && PVT != MVT::f32)
5012       return SDValue();
5013
5014     int FI = -1;
5015     int64_t Offset = 0;
5016     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5017       FI = FINode->getIndex();
5018       Offset = 0;
5019     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5020                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5021       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5022       Offset = Ptr.getConstantOperandVal(1);
5023       Ptr = Ptr.getOperand(0);
5024     } else {
5025       return SDValue();
5026     }
5027
5028     // FIXME: 256-bit vector instructions don't require a strict alignment,
5029     // improve this code to support it better.
5030     unsigned RequiredAlign = VT.getSizeInBits()/8;
5031     SDValue Chain = LD->getChain();
5032     // Make sure the stack object alignment is at least 16 or 32.
5033     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5034     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5035       if (MFI->isFixedObjectIndex(FI)) {
5036         // Can't change the alignment. FIXME: It's possible to compute
5037         // the exact stack offset and reference FI + adjust offset instead.
5038         // If someone *really* cares about this. That's the way to implement it.
5039         return SDValue();
5040       } else {
5041         MFI->setObjectAlignment(FI, RequiredAlign);
5042       }
5043     }
5044
5045     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5046     // Ptr + (Offset & ~15).
5047     if (Offset < 0)
5048       return SDValue();
5049     if ((Offset % RequiredAlign) & 3)
5050       return SDValue();
5051     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5052     if (StartOffset)
5053       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5054                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5055
5056     int EltNo = (Offset - StartOffset) >> 2;
5057     unsigned NumElems = VT.getVectorNumElements();
5058
5059     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5060     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5061                              LD->getPointerInfo().getWithOffset(StartOffset),
5062                              false, false, false, 0);
5063
5064     SmallVector<int, 8> Mask;
5065     for (unsigned i = 0; i != NumElems; ++i)
5066       Mask.push_back(EltNo);
5067
5068     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5069   }
5070
5071   return SDValue();
5072 }
5073
5074 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5075 /// vector of type 'VT', see if the elements can be replaced by a single large
5076 /// load which has the same value as a build_vector whose operands are 'elts'.
5077 ///
5078 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5079 ///
5080 /// FIXME: we'd also like to handle the case where the last elements are zero
5081 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5082 /// There's even a handy isZeroNode for that purpose.
5083 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5084                                         SDLoc &DL, SelectionDAG &DAG) {
5085   EVT EltVT = VT.getVectorElementType();
5086   unsigned NumElems = Elts.size();
5087
5088   LoadSDNode *LDBase = NULL;
5089   unsigned LastLoadedElt = -1U;
5090
5091   // For each element in the initializer, see if we've found a load or an undef.
5092   // If we don't find an initial load element, or later load elements are
5093   // non-consecutive, bail out.
5094   for (unsigned i = 0; i < NumElems; ++i) {
5095     SDValue Elt = Elts[i];
5096
5097     if (!Elt.getNode() ||
5098         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5099       return SDValue();
5100     if (!LDBase) {
5101       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5102         return SDValue();
5103       LDBase = cast<LoadSDNode>(Elt.getNode());
5104       LastLoadedElt = i;
5105       continue;
5106     }
5107     if (Elt.getOpcode() == ISD::UNDEF)
5108       continue;
5109
5110     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5111     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5112       return SDValue();
5113     LastLoadedElt = i;
5114   }
5115
5116   // If we have found an entire vector of loads and undefs, then return a large
5117   // load of the entire vector width starting at the base pointer.  If we found
5118   // consecutive loads for the low half, generate a vzext_load node.
5119   if (LastLoadedElt == NumElems - 1) {
5120     SDValue NewLd = SDValue();
5121     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5122       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5123                           LDBase->getPointerInfo(),
5124                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5125                           LDBase->isInvariant(), 0);
5126     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5127                         LDBase->getPointerInfo(),
5128                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5129                         LDBase->isInvariant(), LDBase->getAlignment());
5130
5131     if (LDBase->hasAnyUseOfValue(1)) {
5132       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5133                                      SDValue(LDBase, 1),
5134                                      SDValue(NewLd.getNode(), 1));
5135       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5136       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5137                              SDValue(NewLd.getNode(), 1));
5138     }
5139
5140     return NewLd;
5141   }
5142   if (NumElems == 4 && LastLoadedElt == 1 &&
5143       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5144     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5145     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5146     SDValue ResNode =
5147         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops,
5148                                 array_lengthof(Ops), MVT::i64,
5149                                 LDBase->getPointerInfo(),
5150                                 LDBase->getAlignment(),
5151                                 false/*isVolatile*/, true/*ReadMem*/,
5152                                 false/*WriteMem*/);
5153
5154     // Make sure the newly-created LOAD is in the same position as LDBase in
5155     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5156     // update uses of LDBase's output chain to use the TokenFactor.
5157     if (LDBase->hasAnyUseOfValue(1)) {
5158       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5159                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5160       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5161       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5162                              SDValue(ResNode.getNode(), 1));
5163     }
5164
5165     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5166   }
5167   return SDValue();
5168 }
5169
5170 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5171 /// to generate a splat value for the following cases:
5172 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5173 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5174 /// a scalar load, or a constant.
5175 /// The VBROADCAST node is returned when a pattern is found,
5176 /// or SDValue() otherwise.
5177 SDValue
5178 X86TargetLowering::LowerVectorBroadcast(SDValue Op, SelectionDAG &DAG) const {
5179   if (!Subtarget->hasFp256())
5180     return SDValue();
5181
5182   MVT VT = Op.getValueType().getSimpleVT();
5183   SDLoc dl(Op);
5184
5185   assert((VT.is128BitVector() || VT.is256BitVector()) &&
5186          "Unsupported vector type for broadcast.");
5187
5188   SDValue Ld;
5189   bool ConstSplatVal;
5190
5191   switch (Op.getOpcode()) {
5192     default:
5193       // Unknown pattern found.
5194       return SDValue();
5195
5196     case ISD::BUILD_VECTOR: {
5197       // The BUILD_VECTOR node must be a splat.
5198       if (!isSplatVector(Op.getNode()))
5199         return SDValue();
5200
5201       Ld = Op.getOperand(0);
5202       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5203                      Ld.getOpcode() == ISD::ConstantFP);
5204
5205       // The suspected load node has several users. Make sure that all
5206       // of its users are from the BUILD_VECTOR node.
5207       // Constants may have multiple users.
5208       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5209         return SDValue();
5210       break;
5211     }
5212
5213     case ISD::VECTOR_SHUFFLE: {
5214       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5215
5216       // Shuffles must have a splat mask where the first element is
5217       // broadcasted.
5218       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5219         return SDValue();
5220
5221       SDValue Sc = Op.getOperand(0);
5222       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5223           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5224
5225         if (!Subtarget->hasInt256())
5226           return SDValue();
5227
5228         // Use the register form of the broadcast instruction available on AVX2.
5229         if (VT.is256BitVector())
5230           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5231         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5232       }
5233
5234       Ld = Sc.getOperand(0);
5235       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5236                        Ld.getOpcode() == ISD::ConstantFP);
5237
5238       // The scalar_to_vector node and the suspected
5239       // load node must have exactly one user.
5240       // Constants may have multiple users.
5241       if (!ConstSplatVal && (!Sc.hasOneUse() || !Ld.hasOneUse()))
5242         return SDValue();
5243       break;
5244     }
5245   }
5246
5247   bool Is256 = VT.is256BitVector();
5248
5249   // Handle the broadcasting a single constant scalar from the constant pool
5250   // into a vector. On Sandybridge it is still better to load a constant vector
5251   // from the constant pool and not to broadcast it from a scalar.
5252   if (ConstSplatVal && Subtarget->hasInt256()) {
5253     EVT CVT = Ld.getValueType();
5254     assert(!CVT.isVector() && "Must not broadcast a vector type");
5255     unsigned ScalarSize = CVT.getSizeInBits();
5256
5257     if (ScalarSize == 32 || (Is256 && ScalarSize == 64)) {
5258       const Constant *C = 0;
5259       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5260         C = CI->getConstantIntValue();
5261       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5262         C = CF->getConstantFPValue();
5263
5264       assert(C && "Invalid constant type");
5265
5266       SDValue CP = DAG.getConstantPool(C, getPointerTy());
5267       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5268       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5269                        MachinePointerInfo::getConstantPool(),
5270                        false, false, false, Alignment);
5271
5272       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5273     }
5274   }
5275
5276   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5277   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5278
5279   // Handle AVX2 in-register broadcasts.
5280   if (!IsLoad && Subtarget->hasInt256() &&
5281       (ScalarSize == 32 || (Is256 && ScalarSize == 64)))
5282     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5283
5284   // The scalar source must be a normal load.
5285   if (!IsLoad)
5286     return SDValue();
5287
5288   if (ScalarSize == 32 || (Is256 && ScalarSize == 64))
5289     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5290
5291   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5292   // double since there is no vbroadcastsd xmm
5293   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5294     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5295       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5296   }
5297
5298   // Unsupported broadcast.
5299   return SDValue();
5300 }
5301
5302 SDValue
5303 X86TargetLowering::buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) const {
5304   EVT VT = Op.getValueType();
5305
5306   // Skip if insert_vec_elt is not supported.
5307   if (!isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5308     return SDValue();
5309
5310   SDLoc DL(Op);
5311   unsigned NumElems = Op.getNumOperands();
5312
5313   SDValue VecIn1;
5314   SDValue VecIn2;
5315   SmallVector<unsigned, 4> InsertIndices;
5316   SmallVector<int, 8> Mask(NumElems, -1);
5317
5318   for (unsigned i = 0; i != NumElems; ++i) {
5319     unsigned Opc = Op.getOperand(i).getOpcode();
5320
5321     if (Opc == ISD::UNDEF)
5322       continue;
5323
5324     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5325       // Quit if more than 1 elements need inserting.
5326       if (InsertIndices.size() > 1)
5327         return SDValue();
5328
5329       InsertIndices.push_back(i);
5330       continue;
5331     }
5332
5333     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5334     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5335
5336     // Quit if extracted from vector of different type.
5337     if (ExtractedFromVec.getValueType() != VT)
5338       return SDValue();
5339
5340     // Quit if non-constant index.
5341     if (!isa<ConstantSDNode>(ExtIdx))
5342       return SDValue();
5343
5344     if (VecIn1.getNode() == 0)
5345       VecIn1 = ExtractedFromVec;
5346     else if (VecIn1 != ExtractedFromVec) {
5347       if (VecIn2.getNode() == 0)
5348         VecIn2 = ExtractedFromVec;
5349       else if (VecIn2 != ExtractedFromVec)
5350         // Quit if more than 2 vectors to shuffle
5351         return SDValue();
5352     }
5353
5354     unsigned Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5355
5356     if (ExtractedFromVec == VecIn1)
5357       Mask[i] = Idx;
5358     else if (ExtractedFromVec == VecIn2)
5359       Mask[i] = Idx + NumElems;
5360   }
5361
5362   if (VecIn1.getNode() == 0)
5363     return SDValue();
5364
5365   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5366   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5367   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5368     unsigned Idx = InsertIndices[i];
5369     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5370                      DAG.getIntPtrConstant(Idx));
5371   }
5372
5373   return NV;
5374 }
5375
5376 SDValue
5377 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5378   SDLoc dl(Op);
5379
5380   MVT VT = Op.getValueType().getSimpleVT();
5381   MVT ExtVT = VT.getVectorElementType();
5382   unsigned NumElems = Op.getNumOperands();
5383
5384   // Vectors containing all zeros can be matched by pxor and xorps later
5385   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5386     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5387     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5388     if (VT == MVT::v4i32 || VT == MVT::v8i32)
5389       return Op;
5390
5391     return getZeroVector(VT, Subtarget, DAG, dl);
5392   }
5393
5394   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5395   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5396   // vpcmpeqd on 256-bit vectors.
5397   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5398     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5399       return Op;
5400
5401     return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5402   }
5403
5404   SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
5405   if (Broadcast.getNode())
5406     return Broadcast;
5407
5408   unsigned EVTBits = ExtVT.getSizeInBits();
5409
5410   unsigned NumZero  = 0;
5411   unsigned NumNonZero = 0;
5412   unsigned NonZeros = 0;
5413   bool IsAllConstants = true;
5414   SmallSet<SDValue, 8> Values;
5415   for (unsigned i = 0; i < NumElems; ++i) {
5416     SDValue Elt = Op.getOperand(i);
5417     if (Elt.getOpcode() == ISD::UNDEF)
5418       continue;
5419     Values.insert(Elt);
5420     if (Elt.getOpcode() != ISD::Constant &&
5421         Elt.getOpcode() != ISD::ConstantFP)
5422       IsAllConstants = false;
5423     if (X86::isZeroNode(Elt))
5424       NumZero++;
5425     else {
5426       NonZeros |= (1 << i);
5427       NumNonZero++;
5428     }
5429   }
5430
5431   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5432   if (NumNonZero == 0)
5433     return DAG.getUNDEF(VT);
5434
5435   // Special case for single non-zero, non-undef, element.
5436   if (NumNonZero == 1) {
5437     unsigned Idx = countTrailingZeros(NonZeros);
5438     SDValue Item = Op.getOperand(Idx);
5439
5440     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5441     // the value are obviously zero, truncate the value to i32 and do the
5442     // insertion that way.  Only do this if the value is non-constant or if the
5443     // value is a constant being inserted into element 0.  It is cheaper to do
5444     // a constant pool load than it is to do a movd + shuffle.
5445     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5446         (!IsAllConstants || Idx == 0)) {
5447       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5448         // Handle SSE only.
5449         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5450         EVT VecVT = MVT::v4i32;
5451         unsigned VecElts = 4;
5452
5453         // Truncate the value (which may itself be a constant) to i32, and
5454         // convert it to a vector with movd (S2V+shuffle to zero extend).
5455         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5456         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5457         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5458
5459         // Now we have our 32-bit value zero extended in the low element of
5460         // a vector.  If Idx != 0, swizzle it into place.
5461         if (Idx != 0) {
5462           SmallVector<int, 4> Mask;
5463           Mask.push_back(Idx);
5464           for (unsigned i = 1; i != VecElts; ++i)
5465             Mask.push_back(i);
5466           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
5467                                       &Mask[0]);
5468         }
5469         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5470       }
5471     }
5472
5473     // If we have a constant or non-constant insertion into the low element of
5474     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5475     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5476     // depending on what the source datatype is.
5477     if (Idx == 0) {
5478       if (NumZero == 0)
5479         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5480
5481       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5482           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5483         if (VT.is256BitVector()) {
5484           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5485           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5486                              Item, DAG.getIntPtrConstant(0));
5487         }
5488         assert(VT.is128BitVector() && "Expected an SSE value type!");
5489         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5490         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5491         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5492       }
5493
5494       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5495         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5496         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5497         if (VT.is256BitVector()) {
5498           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5499           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5500         } else {
5501           assert(VT.is128BitVector() && "Expected an SSE value type!");
5502           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5503         }
5504         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5505       }
5506     }
5507
5508     // Is it a vector logical left shift?
5509     if (NumElems == 2 && Idx == 1 &&
5510         X86::isZeroNode(Op.getOperand(0)) &&
5511         !X86::isZeroNode(Op.getOperand(1))) {
5512       unsigned NumBits = VT.getSizeInBits();
5513       return getVShift(true, VT,
5514                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5515                                    VT, Op.getOperand(1)),
5516                        NumBits/2, DAG, *this, dl);
5517     }
5518
5519     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5520       return SDValue();
5521
5522     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5523     // is a non-constant being inserted into an element other than the low one,
5524     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5525     // movd/movss) to move this into the low element, then shuffle it into
5526     // place.
5527     if (EVTBits == 32) {
5528       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5529
5530       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5531       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
5532       SmallVector<int, 8> MaskVec;
5533       for (unsigned i = 0; i != NumElems; ++i)
5534         MaskVec.push_back(i == Idx ? 0 : 1);
5535       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5536     }
5537   }
5538
5539   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5540   if (Values.size() == 1) {
5541     if (EVTBits == 32) {
5542       // Instead of a shuffle like this:
5543       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5544       // Check if it's possible to issue this instead.
5545       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5546       unsigned Idx = countTrailingZeros(NonZeros);
5547       SDValue Item = Op.getOperand(Idx);
5548       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5549         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5550     }
5551     return SDValue();
5552   }
5553
5554   // A vector full of immediates; various special cases are already
5555   // handled, so this is best done with a single constant-pool load.
5556   if (IsAllConstants)
5557     return SDValue();
5558
5559   // For AVX-length vectors, build the individual 128-bit pieces and use
5560   // shuffles to put them in place.
5561   if (VT.is256BitVector()) {
5562     SmallVector<SDValue, 32> V;
5563     for (unsigned i = 0; i != NumElems; ++i)
5564       V.push_back(Op.getOperand(i));
5565
5566     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5567
5568     // Build both the lower and upper subvector.
5569     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5570     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5571                                 NumElems/2);
5572
5573     // Recreate the wider vector with the lower and upper part.
5574     return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5575   }
5576
5577   // Let legalizer expand 2-wide build_vectors.
5578   if (EVTBits == 64) {
5579     if (NumNonZero == 1) {
5580       // One half is zero or undef.
5581       unsigned Idx = countTrailingZeros(NonZeros);
5582       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5583                                  Op.getOperand(Idx));
5584       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
5585     }
5586     return SDValue();
5587   }
5588
5589   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5590   if (EVTBits == 8 && NumElems == 16) {
5591     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5592                                         Subtarget, *this);
5593     if (V.getNode()) return V;
5594   }
5595
5596   if (EVTBits == 16 && NumElems == 8) {
5597     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5598                                       Subtarget, *this);
5599     if (V.getNode()) return V;
5600   }
5601
5602   // If element VT is == 32 bits, turn it into a number of shuffles.
5603   SmallVector<SDValue, 8> V(NumElems);
5604   if (NumElems == 4 && NumZero > 0) {
5605     for (unsigned i = 0; i < 4; ++i) {
5606       bool isZero = !(NonZeros & (1 << i));
5607       if (isZero)
5608         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
5609       else
5610         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5611     }
5612
5613     for (unsigned i = 0; i < 2; ++i) {
5614       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5615         default: break;
5616         case 0:
5617           V[i] = V[i*2];  // Must be a zero vector.
5618           break;
5619         case 1:
5620           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5621           break;
5622         case 2:
5623           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5624           break;
5625         case 3:
5626           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5627           break;
5628       }
5629     }
5630
5631     bool Reverse1 = (NonZeros & 0x3) == 2;
5632     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5633     int MaskVec[] = {
5634       Reverse1 ? 1 : 0,
5635       Reverse1 ? 0 : 1,
5636       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
5637       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
5638     };
5639     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5640   }
5641
5642   if (Values.size() > 1 && VT.is128BitVector()) {
5643     // Check for a build vector of consecutive loads.
5644     for (unsigned i = 0; i < NumElems; ++i)
5645       V[i] = Op.getOperand(i);
5646
5647     // Check for elements which are consecutive loads.
5648     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5649     if (LD.getNode())
5650       return LD;
5651
5652     // Check for a build vector from mostly shuffle plus few inserting.
5653     SDValue Sh = buildFromShuffleMostly(Op, DAG);
5654     if (Sh.getNode())
5655       return Sh;
5656
5657     // For SSE 4.1, use insertps to put the high elements into the low element.
5658     if (getSubtarget()->hasSSE41()) {
5659       SDValue Result;
5660       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5661         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5662       else
5663         Result = DAG.getUNDEF(VT);
5664
5665       for (unsigned i = 1; i < NumElems; ++i) {
5666         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5667         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5668                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5669       }
5670       return Result;
5671     }
5672
5673     // Otherwise, expand into a number of unpckl*, start by extending each of
5674     // our (non-undef) elements to the full vector width with the element in the
5675     // bottom slot of the vector (which generates no code for SSE).
5676     for (unsigned i = 0; i < NumElems; ++i) {
5677       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5678         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5679       else
5680         V[i] = DAG.getUNDEF(VT);
5681     }
5682
5683     // Next, we iteratively mix elements, e.g. for v4f32:
5684     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5685     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5686     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5687     unsigned EltStride = NumElems >> 1;
5688     while (EltStride != 0) {
5689       for (unsigned i = 0; i < EltStride; ++i) {
5690         // If V[i+EltStride] is undef and this is the first round of mixing,
5691         // then it is safe to just drop this shuffle: V[i] is already in the
5692         // right place, the one element (since it's the first round) being
5693         // inserted as undef can be dropped.  This isn't safe for successive
5694         // rounds because they will permute elements within both vectors.
5695         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5696             EltStride == NumElems/2)
5697           continue;
5698
5699         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5700       }
5701       EltStride >>= 1;
5702     }
5703     return V[0];
5704   }
5705   return SDValue();
5706 }
5707
5708 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5709 // to create 256-bit vectors from two other 128-bit ones.
5710 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5711   SDLoc dl(Op);
5712   MVT ResVT = Op.getValueType().getSimpleVT();
5713
5714   assert(ResVT.is256BitVector() && "Value type must be 256-bit wide");
5715
5716   SDValue V1 = Op.getOperand(0);
5717   SDValue V2 = Op.getOperand(1);
5718   unsigned NumElems = ResVT.getVectorNumElements();
5719
5720   return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
5721 }
5722
5723 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5724   assert(Op.getNumOperands() == 2);
5725
5726   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5727   // from two other 128-bit ones.
5728   return LowerAVXCONCAT_VECTORS(Op, DAG);
5729 }
5730
5731 // Try to lower a shuffle node into a simple blend instruction.
5732 static SDValue
5733 LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
5734                            const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5735   SDValue V1 = SVOp->getOperand(0);
5736   SDValue V2 = SVOp->getOperand(1);
5737   SDLoc dl(SVOp);
5738   MVT VT = SVOp->getValueType(0).getSimpleVT();
5739   MVT EltVT = VT.getVectorElementType();
5740   unsigned NumElems = VT.getVectorNumElements();
5741
5742   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
5743     return SDValue();
5744   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
5745     return SDValue();
5746
5747   // Check the mask for BLEND and build the value.
5748   unsigned MaskValue = 0;
5749   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
5750   unsigned NumLanes = (NumElems-1)/8 + 1;
5751   unsigned NumElemsInLane = NumElems / NumLanes;
5752
5753   // Blend for v16i16 should be symetric for the both lanes.
5754   for (unsigned i = 0; i < NumElemsInLane; ++i) {
5755
5756     int SndLaneEltIdx = (NumLanes == 2) ?
5757       SVOp->getMaskElt(i + NumElemsInLane) : -1;
5758     int EltIdx = SVOp->getMaskElt(i);
5759
5760     if ((EltIdx < 0 || EltIdx == (int)i) &&
5761         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
5762       continue;
5763
5764     if (((unsigned)EltIdx == (i + NumElems)) &&
5765         (SndLaneEltIdx < 0 ||
5766          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
5767       MaskValue |= (1<<i);
5768     else
5769       return SDValue();
5770   }
5771
5772   // Convert i32 vectors to floating point if it is not AVX2.
5773   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
5774   MVT BlendVT = VT;
5775   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
5776     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
5777                                NumElems);
5778     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
5779     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
5780   }
5781
5782   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
5783                             DAG.getConstant(MaskValue, MVT::i32));
5784   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
5785 }
5786
5787 // v8i16 shuffles - Prefer shuffles in the following order:
5788 // 1. [all]   pshuflw, pshufhw, optional move
5789 // 2. [ssse3] 1 x pshufb
5790 // 3. [ssse3] 2 x pshufb + 1 x por
5791 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5792 static SDValue
5793 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
5794                          SelectionDAG &DAG) {
5795   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5796   SDValue V1 = SVOp->getOperand(0);
5797   SDValue V2 = SVOp->getOperand(1);
5798   SDLoc dl(SVOp);
5799   SmallVector<int, 8> MaskVals;
5800
5801   // Determine if more than 1 of the words in each of the low and high quadwords
5802   // of the result come from the same quadword of one of the two inputs.  Undef
5803   // mask values count as coming from any quadword, for better codegen.
5804   unsigned LoQuad[] = { 0, 0, 0, 0 };
5805   unsigned HiQuad[] = { 0, 0, 0, 0 };
5806   std::bitset<4> InputQuads;
5807   for (unsigned i = 0; i < 8; ++i) {
5808     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5809     int EltIdx = SVOp->getMaskElt(i);
5810     MaskVals.push_back(EltIdx);
5811     if (EltIdx < 0) {
5812       ++Quad[0];
5813       ++Quad[1];
5814       ++Quad[2];
5815       ++Quad[3];
5816       continue;
5817     }
5818     ++Quad[EltIdx / 4];
5819     InputQuads.set(EltIdx / 4);
5820   }
5821
5822   int BestLoQuad = -1;
5823   unsigned MaxQuad = 1;
5824   for (unsigned i = 0; i < 4; ++i) {
5825     if (LoQuad[i] > MaxQuad) {
5826       BestLoQuad = i;
5827       MaxQuad = LoQuad[i];
5828     }
5829   }
5830
5831   int BestHiQuad = -1;
5832   MaxQuad = 1;
5833   for (unsigned i = 0; i < 4; ++i) {
5834     if (HiQuad[i] > MaxQuad) {
5835       BestHiQuad = i;
5836       MaxQuad = HiQuad[i];
5837     }
5838   }
5839
5840   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5841   // of the two input vectors, shuffle them into one input vector so only a
5842   // single pshufb instruction is necessary. If There are more than 2 input
5843   // quads, disable the next transformation since it does not help SSSE3.
5844   bool V1Used = InputQuads[0] || InputQuads[1];
5845   bool V2Used = InputQuads[2] || InputQuads[3];
5846   if (Subtarget->hasSSSE3()) {
5847     if (InputQuads.count() == 2 && V1Used && V2Used) {
5848       BestLoQuad = InputQuads[0] ? 0 : 1;
5849       BestHiQuad = InputQuads[2] ? 2 : 3;
5850     }
5851     if (InputQuads.count() > 2) {
5852       BestLoQuad = -1;
5853       BestHiQuad = -1;
5854     }
5855   }
5856
5857   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5858   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5859   // words from all 4 input quadwords.
5860   SDValue NewV;
5861   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5862     int MaskV[] = {
5863       BestLoQuad < 0 ? 0 : BestLoQuad,
5864       BestHiQuad < 0 ? 1 : BestHiQuad
5865     };
5866     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5867                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5868                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5869     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5870
5871     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5872     // source words for the shuffle, to aid later transformations.
5873     bool AllWordsInNewV = true;
5874     bool InOrder[2] = { true, true };
5875     for (unsigned i = 0; i != 8; ++i) {
5876       int idx = MaskVals[i];
5877       if (idx != (int)i)
5878         InOrder[i/4] = false;
5879       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5880         continue;
5881       AllWordsInNewV = false;
5882       break;
5883     }
5884
5885     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5886     if (AllWordsInNewV) {
5887       for (int i = 0; i != 8; ++i) {
5888         int idx = MaskVals[i];
5889         if (idx < 0)
5890           continue;
5891         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5892         if ((idx != i) && idx < 4)
5893           pshufhw = false;
5894         if ((idx != i) && idx > 3)
5895           pshuflw = false;
5896       }
5897       V1 = NewV;
5898       V2Used = false;
5899       BestLoQuad = 0;
5900       BestHiQuad = 1;
5901     }
5902
5903     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5904     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5905     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5906       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5907       unsigned TargetMask = 0;
5908       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5909                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5910       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5911       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
5912                              getShufflePSHUFLWImmediate(SVOp);
5913       V1 = NewV.getOperand(0);
5914       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5915     }
5916   }
5917
5918   // Promote splats to a larger type which usually leads to more efficient code.
5919   // FIXME: Is this true if pshufb is available?
5920   if (SVOp->isSplat())
5921     return PromoteSplat(SVOp, DAG);
5922
5923   // If we have SSSE3, and all words of the result are from 1 input vector,
5924   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5925   // is present, fall back to case 4.
5926   if (Subtarget->hasSSSE3()) {
5927     SmallVector<SDValue,16> pshufbMask;
5928
5929     // If we have elements from both input vectors, set the high bit of the
5930     // shuffle mask element to zero out elements that come from V2 in the V1
5931     // mask, and elements that come from V1 in the V2 mask, so that the two
5932     // results can be OR'd together.
5933     bool TwoInputs = V1Used && V2Used;
5934     for (unsigned i = 0; i != 8; ++i) {
5935       int EltIdx = MaskVals[i] * 2;
5936       int Idx0 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx;
5937       int Idx1 = (TwoInputs && (EltIdx >= 16)) ? 0x80 : EltIdx+1;
5938       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5939       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5940     }
5941     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5942     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5943                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5944                                  MVT::v16i8, &pshufbMask[0], 16));
5945     if (!TwoInputs)
5946       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5947
5948     // Calculate the shuffle mask for the second input, shuffle it, and
5949     // OR it with the first shuffled input.
5950     pshufbMask.clear();
5951     for (unsigned i = 0; i != 8; ++i) {
5952       int EltIdx = MaskVals[i] * 2;
5953       int Idx0 = (EltIdx < 16) ? 0x80 : EltIdx - 16;
5954       int Idx1 = (EltIdx < 16) ? 0x80 : EltIdx - 15;
5955       pshufbMask.push_back(DAG.getConstant(Idx0, MVT::i8));
5956       pshufbMask.push_back(DAG.getConstant(Idx1, MVT::i8));
5957     }
5958     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5959     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5960                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5961                                  MVT::v16i8, &pshufbMask[0], 16));
5962     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5963     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5964   }
5965
5966   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5967   // and update MaskVals with new element order.
5968   std::bitset<8> InOrder;
5969   if (BestLoQuad >= 0) {
5970     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
5971     for (int i = 0; i != 4; ++i) {
5972       int idx = MaskVals[i];
5973       if (idx < 0) {
5974         InOrder.set(i);
5975       } else if ((idx / 4) == BestLoQuad) {
5976         MaskV[i] = idx & 3;
5977         InOrder.set(i);
5978       }
5979     }
5980     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5981                                 &MaskV[0]);
5982
5983     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
5984       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
5985       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5986                                   NewV.getOperand(0),
5987                                   getShufflePSHUFLWImmediate(SVOp), DAG);
5988     }
5989   }
5990
5991   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5992   // and update MaskVals with the new element order.
5993   if (BestHiQuad >= 0) {
5994     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
5995     for (unsigned i = 4; i != 8; ++i) {
5996       int idx = MaskVals[i];
5997       if (idx < 0) {
5998         InOrder.set(i);
5999       } else if ((idx / 4) == BestHiQuad) {
6000         MaskV[i] = (idx & 3) + 4;
6001         InOrder.set(i);
6002       }
6003     }
6004     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6005                                 &MaskV[0]);
6006
6007     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3()) {
6008       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6009       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6010                                   NewV.getOperand(0),
6011                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6012     }
6013   }
6014
6015   // In case BestHi & BestLo were both -1, which means each quadword has a word
6016   // from each of the four input quadwords, calculate the InOrder bitvector now
6017   // before falling through to the insert/extract cleanup.
6018   if (BestLoQuad == -1 && BestHiQuad == -1) {
6019     NewV = V1;
6020     for (int i = 0; i != 8; ++i)
6021       if (MaskVals[i] < 0 || MaskVals[i] == i)
6022         InOrder.set(i);
6023   }
6024
6025   // The other elements are put in the right place using pextrw and pinsrw.
6026   for (unsigned i = 0; i != 8; ++i) {
6027     if (InOrder[i])
6028       continue;
6029     int EltIdx = MaskVals[i];
6030     if (EltIdx < 0)
6031       continue;
6032     SDValue ExtOp = (EltIdx < 8) ?
6033       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6034                   DAG.getIntPtrConstant(EltIdx)) :
6035       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6036                   DAG.getIntPtrConstant(EltIdx - 8));
6037     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6038                        DAG.getIntPtrConstant(i));
6039   }
6040   return NewV;
6041 }
6042
6043 // v16i8 shuffles - Prefer shuffles in the following order:
6044 // 1. [ssse3] 1 x pshufb
6045 // 2. [ssse3] 2 x pshufb + 1 x por
6046 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6047 static
6048 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6049                                  SelectionDAG &DAG,
6050                                  const X86TargetLowering &TLI) {
6051   SDValue V1 = SVOp->getOperand(0);
6052   SDValue V2 = SVOp->getOperand(1);
6053   SDLoc dl(SVOp);
6054   ArrayRef<int> MaskVals = SVOp->getMask();
6055
6056   // Promote splats to a larger type which usually leads to more efficient code.
6057   // FIXME: Is this true if pshufb is available?
6058   if (SVOp->isSplat())
6059     return PromoteSplat(SVOp, DAG);
6060
6061   // If we have SSSE3, case 1 is generated when all result bytes come from
6062   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6063   // present, fall back to case 3.
6064
6065   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6066   if (TLI.getSubtarget()->hasSSSE3()) {
6067     SmallVector<SDValue,16> pshufbMask;
6068
6069     // If all result elements are from one input vector, then only translate
6070     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6071     //
6072     // Otherwise, we have elements from both input vectors, and must zero out
6073     // elements that come from V2 in the first mask, and V1 in the second mask
6074     // so that we can OR them together.
6075     for (unsigned i = 0; i != 16; ++i) {
6076       int EltIdx = MaskVals[i];
6077       if (EltIdx < 0 || EltIdx >= 16)
6078         EltIdx = 0x80;
6079       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6080     }
6081     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6082                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6083                                  MVT::v16i8, &pshufbMask[0], 16));
6084
6085     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6086     // the 2nd operand if it's undefined or zero.
6087     if (V2.getOpcode() == ISD::UNDEF ||
6088         ISD::isBuildVectorAllZeros(V2.getNode()))
6089       return V1;
6090
6091     // Calculate the shuffle mask for the second input, shuffle it, and
6092     // OR it with the first shuffled input.
6093     pshufbMask.clear();
6094     for (unsigned i = 0; i != 16; ++i) {
6095       int EltIdx = MaskVals[i];
6096       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6097       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6098     }
6099     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6100                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6101                                  MVT::v16i8, &pshufbMask[0], 16));
6102     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6103   }
6104
6105   // No SSSE3 - Calculate in place words and then fix all out of place words
6106   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6107   // the 16 different words that comprise the two doublequadword input vectors.
6108   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6109   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6110   SDValue NewV = V1;
6111   for (int i = 0; i != 8; ++i) {
6112     int Elt0 = MaskVals[i*2];
6113     int Elt1 = MaskVals[i*2+1];
6114
6115     // This word of the result is all undef, skip it.
6116     if (Elt0 < 0 && Elt1 < 0)
6117       continue;
6118
6119     // This word of the result is already in the correct place, skip it.
6120     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6121       continue;
6122
6123     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6124     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6125     SDValue InsElt;
6126
6127     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6128     // using a single extract together, load it and store it.
6129     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6130       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6131                            DAG.getIntPtrConstant(Elt1 / 2));
6132       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6133                         DAG.getIntPtrConstant(i));
6134       continue;
6135     }
6136
6137     // If Elt1 is defined, extract it from the appropriate source.  If the
6138     // source byte is not also odd, shift the extracted word left 8 bits
6139     // otherwise clear the bottom 8 bits if we need to do an or.
6140     if (Elt1 >= 0) {
6141       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6142                            DAG.getIntPtrConstant(Elt1 / 2));
6143       if ((Elt1 & 1) == 0)
6144         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6145                              DAG.getConstant(8,
6146                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6147       else if (Elt0 >= 0)
6148         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6149                              DAG.getConstant(0xFF00, MVT::i16));
6150     }
6151     // If Elt0 is defined, extract it from the appropriate source.  If the
6152     // source byte is not also even, shift the extracted word right 8 bits. If
6153     // Elt1 was also defined, OR the extracted values together before
6154     // inserting them in the result.
6155     if (Elt0 >= 0) {
6156       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6157                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6158       if ((Elt0 & 1) != 0)
6159         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6160                               DAG.getConstant(8,
6161                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6162       else if (Elt1 >= 0)
6163         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6164                              DAG.getConstant(0x00FF, MVT::i16));
6165       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6166                          : InsElt0;
6167     }
6168     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6169                        DAG.getIntPtrConstant(i));
6170   }
6171   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6172 }
6173
6174 // v32i8 shuffles - Translate to VPSHUFB if possible.
6175 static
6176 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6177                                  const X86Subtarget *Subtarget,
6178                                  SelectionDAG &DAG) {
6179   MVT VT = SVOp->getValueType(0).getSimpleVT();
6180   SDValue V1 = SVOp->getOperand(0);
6181   SDValue V2 = SVOp->getOperand(1);
6182   SDLoc dl(SVOp);
6183   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6184
6185   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6186   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6187   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6188
6189   // VPSHUFB may be generated if
6190   // (1) one of input vector is undefined or zeroinitializer.
6191   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6192   // And (2) the mask indexes don't cross the 128-bit lane.
6193   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6194       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6195     return SDValue();
6196
6197   if (V1IsAllZero && !V2IsAllZero) {
6198     CommuteVectorShuffleMask(MaskVals, 32);
6199     V1 = V2;
6200   }
6201   SmallVector<SDValue, 32> pshufbMask;
6202   for (unsigned i = 0; i != 32; i++) {
6203     int EltIdx = MaskVals[i];
6204     if (EltIdx < 0 || EltIdx >= 32)
6205       EltIdx = 0x80;
6206     else {
6207       if ((EltIdx >= 16 && i < 16) || (EltIdx < 16 && i >= 16))
6208         // Cross lane is not allowed.
6209         return SDValue();
6210       EltIdx &= 0xf;
6211     }
6212     pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6213   }
6214   return DAG.getNode(X86ISD::PSHUFB, dl, MVT::v32i8, V1,
6215                       DAG.getNode(ISD::BUILD_VECTOR, dl,
6216                                   MVT::v32i8, &pshufbMask[0], 32));
6217 }
6218
6219 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6220 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6221 /// done when every pair / quad of shuffle mask elements point to elements in
6222 /// the right sequence. e.g.
6223 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6224 static
6225 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6226                                  SelectionDAG &DAG) {
6227   MVT VT = SVOp->getValueType(0).getSimpleVT();
6228   SDLoc dl(SVOp);
6229   unsigned NumElems = VT.getVectorNumElements();
6230   MVT NewVT;
6231   unsigned Scale;
6232   switch (VT.SimpleTy) {
6233   default: llvm_unreachable("Unexpected!");
6234   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6235   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6236   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6237   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6238   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6239   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
6240   }
6241
6242   SmallVector<int, 8> MaskVec;
6243   for (unsigned i = 0; i != NumElems; i += Scale) {
6244     int StartIdx = -1;
6245     for (unsigned j = 0; j != Scale; ++j) {
6246       int EltIdx = SVOp->getMaskElt(i+j);
6247       if (EltIdx < 0)
6248         continue;
6249       if (StartIdx < 0)
6250         StartIdx = (EltIdx / Scale);
6251       if (EltIdx != (int)(StartIdx*Scale + j))
6252         return SDValue();
6253     }
6254     MaskVec.push_back(StartIdx);
6255   }
6256
6257   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
6258   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
6259   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6260 }
6261
6262 /// getVZextMovL - Return a zero-extending vector move low node.
6263 ///
6264 static SDValue getVZextMovL(MVT VT, EVT OpVT,
6265                             SDValue SrcOp, SelectionDAG &DAG,
6266                             const X86Subtarget *Subtarget, SDLoc dl) {
6267   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6268     LoadSDNode *LD = NULL;
6269     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6270       LD = dyn_cast<LoadSDNode>(SrcOp);
6271     if (!LD) {
6272       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6273       // instead.
6274       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6275       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6276           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6277           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6278           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6279         // PR2108
6280         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6281         return DAG.getNode(ISD::BITCAST, dl, VT,
6282                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6283                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6284                                                    OpVT,
6285                                                    SrcOp.getOperand(0)
6286                                                           .getOperand(0))));
6287       }
6288     }
6289   }
6290
6291   return DAG.getNode(ISD::BITCAST, dl, VT,
6292                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6293                                  DAG.getNode(ISD::BITCAST, dl,
6294                                              OpVT, SrcOp)));
6295 }
6296
6297 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6298 /// which could not be matched by any known target speficic shuffle
6299 static SDValue
6300 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6301
6302   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
6303   if (NewOp.getNode())
6304     return NewOp;
6305
6306   MVT VT = SVOp->getValueType(0).getSimpleVT();
6307
6308   unsigned NumElems = VT.getVectorNumElements();
6309   unsigned NumLaneElems = NumElems / 2;
6310
6311   SDLoc dl(SVOp);
6312   MVT EltVT = VT.getVectorElementType();
6313   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
6314   SDValue Output[2];
6315
6316   SmallVector<int, 16> Mask;
6317   for (unsigned l = 0; l < 2; ++l) {
6318     // Build a shuffle mask for the output, discovering on the fly which
6319     // input vectors to use as shuffle operands (recorded in InputUsed).
6320     // If building a suitable shuffle vector proves too hard, then bail
6321     // out with UseBuildVector set.
6322     bool UseBuildVector = false;
6323     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
6324     unsigned LaneStart = l * NumLaneElems;
6325     for (unsigned i = 0; i != NumLaneElems; ++i) {
6326       // The mask element.  This indexes into the input.
6327       int Idx = SVOp->getMaskElt(i+LaneStart);
6328       if (Idx < 0) {
6329         // the mask element does not index into any input vector.
6330         Mask.push_back(-1);
6331         continue;
6332       }
6333
6334       // The input vector this mask element indexes into.
6335       int Input = Idx / NumLaneElems;
6336
6337       // Turn the index into an offset from the start of the input vector.
6338       Idx -= Input * NumLaneElems;
6339
6340       // Find or create a shuffle vector operand to hold this input.
6341       unsigned OpNo;
6342       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
6343         if (InputUsed[OpNo] == Input)
6344           // This input vector is already an operand.
6345           break;
6346         if (InputUsed[OpNo] < 0) {
6347           // Create a new operand for this input vector.
6348           InputUsed[OpNo] = Input;
6349           break;
6350         }
6351       }
6352
6353       if (OpNo >= array_lengthof(InputUsed)) {
6354         // More than two input vectors used!  Give up on trying to create a
6355         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
6356         UseBuildVector = true;
6357         break;
6358       }
6359
6360       // Add the mask index for the new shuffle vector.
6361       Mask.push_back(Idx + OpNo * NumLaneElems);
6362     }
6363
6364     if (UseBuildVector) {
6365       SmallVector<SDValue, 16> SVOps;
6366       for (unsigned i = 0; i != NumLaneElems; ++i) {
6367         // The mask element.  This indexes into the input.
6368         int Idx = SVOp->getMaskElt(i+LaneStart);
6369         if (Idx < 0) {
6370           SVOps.push_back(DAG.getUNDEF(EltVT));
6371           continue;
6372         }
6373
6374         // The input vector this mask element indexes into.
6375         int Input = Idx / NumElems;
6376
6377         // Turn the index into an offset from the start of the input vector.
6378         Idx -= Input * NumElems;
6379
6380         // Extract the vector element by hand.
6381         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6382                                     SVOp->getOperand(Input),
6383                                     DAG.getIntPtrConstant(Idx)));
6384       }
6385
6386       // Construct the output using a BUILD_VECTOR.
6387       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &SVOps[0],
6388                               SVOps.size());
6389     } else if (InputUsed[0] < 0) {
6390       // No input vectors were used! The result is undefined.
6391       Output[l] = DAG.getUNDEF(NVT);
6392     } else {
6393       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
6394                                         (InputUsed[0] % 2) * NumLaneElems,
6395                                         DAG, dl);
6396       // If only one input was used, use an undefined vector for the other.
6397       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
6398         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
6399                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
6400       // At least one input vector was used. Create a new shuffle vector.
6401       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
6402     }
6403
6404     Mask.clear();
6405   }
6406
6407   // Concatenate the result back
6408   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
6409 }
6410
6411 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6412 /// 4 elements, and match them with several different shuffle types.
6413 static SDValue
6414 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6415   SDValue V1 = SVOp->getOperand(0);
6416   SDValue V2 = SVOp->getOperand(1);
6417   SDLoc dl(SVOp);
6418   MVT VT = SVOp->getValueType(0).getSimpleVT();
6419
6420   assert(VT.is128BitVector() && "Unsupported vector size");
6421
6422   std::pair<int, int> Locs[4];
6423   int Mask1[] = { -1, -1, -1, -1 };
6424   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
6425
6426   unsigned NumHi = 0;
6427   unsigned NumLo = 0;
6428   for (unsigned i = 0; i != 4; ++i) {
6429     int Idx = PermMask[i];
6430     if (Idx < 0) {
6431       Locs[i] = std::make_pair(-1, -1);
6432     } else {
6433       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6434       if (Idx < 4) {
6435         Locs[i] = std::make_pair(0, NumLo);
6436         Mask1[NumLo] = Idx;
6437         NumLo++;
6438       } else {
6439         Locs[i] = std::make_pair(1, NumHi);
6440         if (2+NumHi < 4)
6441           Mask1[2+NumHi] = Idx;
6442         NumHi++;
6443       }
6444     }
6445   }
6446
6447   if (NumLo <= 2 && NumHi <= 2) {
6448     // If no more than two elements come from either vector. This can be
6449     // implemented with two shuffles. First shuffle gather the elements.
6450     // The second shuffle, which takes the first shuffle as both of its
6451     // vector operands, put the elements into the right order.
6452     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6453
6454     int Mask2[] = { -1, -1, -1, -1 };
6455
6456     for (unsigned i = 0; i != 4; ++i)
6457       if (Locs[i].first != -1) {
6458         unsigned Idx = (i < 2) ? 0 : 4;
6459         Idx += Locs[i].first * 2 + Locs[i].second;
6460         Mask2[i] = Idx;
6461       }
6462
6463     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6464   }
6465
6466   if (NumLo == 3 || NumHi == 3) {
6467     // Otherwise, we must have three elements from one vector, call it X, and
6468     // one element from the other, call it Y.  First, use a shufps to build an
6469     // intermediate vector with the one element from Y and the element from X
6470     // that will be in the same half in the final destination (the indexes don't
6471     // matter). Then, use a shufps to build the final vector, taking the half
6472     // containing the element from Y from the intermediate, and the other half
6473     // from X.
6474     if (NumHi == 3) {
6475       // Normalize it so the 3 elements come from V1.
6476       CommuteVectorShuffleMask(PermMask, 4);
6477       std::swap(V1, V2);
6478     }
6479
6480     // Find the element from V2.
6481     unsigned HiIndex;
6482     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6483       int Val = PermMask[HiIndex];
6484       if (Val < 0)
6485         continue;
6486       if (Val >= 4)
6487         break;
6488     }
6489
6490     Mask1[0] = PermMask[HiIndex];
6491     Mask1[1] = -1;
6492     Mask1[2] = PermMask[HiIndex^1];
6493     Mask1[3] = -1;
6494     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6495
6496     if (HiIndex >= 2) {
6497       Mask1[0] = PermMask[0];
6498       Mask1[1] = PermMask[1];
6499       Mask1[2] = HiIndex & 1 ? 6 : 4;
6500       Mask1[3] = HiIndex & 1 ? 4 : 6;
6501       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6502     }
6503
6504     Mask1[0] = HiIndex & 1 ? 2 : 0;
6505     Mask1[1] = HiIndex & 1 ? 0 : 2;
6506     Mask1[2] = PermMask[2];
6507     Mask1[3] = PermMask[3];
6508     if (Mask1[2] >= 0)
6509       Mask1[2] += 4;
6510     if (Mask1[3] >= 0)
6511       Mask1[3] += 4;
6512     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6513   }
6514
6515   // Break it into (shuffle shuffle_hi, shuffle_lo).
6516   int LoMask[] = { -1, -1, -1, -1 };
6517   int HiMask[] = { -1, -1, -1, -1 };
6518
6519   int *MaskPtr = LoMask;
6520   unsigned MaskIdx = 0;
6521   unsigned LoIdx = 0;
6522   unsigned HiIdx = 2;
6523   for (unsigned i = 0; i != 4; ++i) {
6524     if (i == 2) {
6525       MaskPtr = HiMask;
6526       MaskIdx = 1;
6527       LoIdx = 0;
6528       HiIdx = 2;
6529     }
6530     int Idx = PermMask[i];
6531     if (Idx < 0) {
6532       Locs[i] = std::make_pair(-1, -1);
6533     } else if (Idx < 4) {
6534       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6535       MaskPtr[LoIdx] = Idx;
6536       LoIdx++;
6537     } else {
6538       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6539       MaskPtr[HiIdx] = Idx;
6540       HiIdx++;
6541     }
6542   }
6543
6544   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6545   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6546   int MaskOps[] = { -1, -1, -1, -1 };
6547   for (unsigned i = 0; i != 4; ++i)
6548     if (Locs[i].first != -1)
6549       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
6550   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6551 }
6552
6553 static bool MayFoldVectorLoad(SDValue V) {
6554   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6555     V = V.getOperand(0);
6556
6557   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6558     V = V.getOperand(0);
6559   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6560       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6561     // BUILD_VECTOR (load), undef
6562     V = V.getOperand(0);
6563
6564   return MayFoldLoad(V);
6565 }
6566
6567 static
6568 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
6569   EVT VT = Op.getValueType();
6570
6571   // Canonizalize to v2f64.
6572   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6573   return DAG.getNode(ISD::BITCAST, dl, VT,
6574                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6575                                           V1, DAG));
6576 }
6577
6578 static
6579 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
6580                         bool HasSSE2) {
6581   SDValue V1 = Op.getOperand(0);
6582   SDValue V2 = Op.getOperand(1);
6583   EVT VT = Op.getValueType();
6584
6585   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6586
6587   if (HasSSE2 && VT == MVT::v2f64)
6588     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6589
6590   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6591   return DAG.getNode(ISD::BITCAST, dl, VT,
6592                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6593                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6594                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6595 }
6596
6597 static
6598 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
6599   SDValue V1 = Op.getOperand(0);
6600   SDValue V2 = Op.getOperand(1);
6601   EVT VT = Op.getValueType();
6602
6603   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6604          "unsupported shuffle type");
6605
6606   if (V2.getOpcode() == ISD::UNDEF)
6607     V2 = V1;
6608
6609   // v4i32 or v4f32
6610   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6611 }
6612
6613 static
6614 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
6615   SDValue V1 = Op.getOperand(0);
6616   SDValue V2 = Op.getOperand(1);
6617   EVT VT = Op.getValueType();
6618   unsigned NumElems = VT.getVectorNumElements();
6619
6620   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6621   // operand of these instructions is only memory, so check if there's a
6622   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6623   // same masks.
6624   bool CanFoldLoad = false;
6625
6626   // Trivial case, when V2 comes from a load.
6627   if (MayFoldVectorLoad(V2))
6628     CanFoldLoad = true;
6629
6630   // When V1 is a load, it can be folded later into a store in isel, example:
6631   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6632   //    turns into:
6633   //  (MOVLPSmr addr:$src1, VR128:$src2)
6634   // So, recognize this potential and also use MOVLPS or MOVLPD
6635   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6636     CanFoldLoad = true;
6637
6638   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6639   if (CanFoldLoad) {
6640     if (HasSSE2 && NumElems == 2)
6641       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6642
6643     if (NumElems == 4)
6644       // If we don't care about the second element, proceed to use movss.
6645       if (SVOp->getMaskElt(1) != -1)
6646         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6647   }
6648
6649   // movl and movlp will both match v2i64, but v2i64 is never matched by
6650   // movl earlier because we make it strict to avoid messing with the movlp load
6651   // folding logic (see the code above getMOVLP call). Match it here then,
6652   // this is horrible, but will stay like this until we move all shuffle
6653   // matching to x86 specific nodes. Note that for the 1st condition all
6654   // types are matched with movsd.
6655   if (HasSSE2) {
6656     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6657     // as to remove this logic from here, as much as possible
6658     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
6659       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6660     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6661   }
6662
6663   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6664
6665   // Invert the operand order and use SHUFPS to match it.
6666   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
6667                               getShuffleSHUFImmediate(SVOp), DAG);
6668 }
6669
6670 // Reduce a vector shuffle to zext.
6671 SDValue
6672 X86TargetLowering::LowerVectorIntExtend(SDValue Op, SelectionDAG &DAG) const {
6673   // PMOVZX is only available from SSE41.
6674   if (!Subtarget->hasSSE41())
6675     return SDValue();
6676
6677   EVT VT = Op.getValueType();
6678
6679   // Only AVX2 support 256-bit vector integer extending.
6680   if (!Subtarget->hasInt256() && VT.is256BitVector())
6681     return SDValue();
6682
6683   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6684   SDLoc DL(Op);
6685   SDValue V1 = Op.getOperand(0);
6686   SDValue V2 = Op.getOperand(1);
6687   unsigned NumElems = VT.getVectorNumElements();
6688
6689   // Extending is an unary operation and the element type of the source vector
6690   // won't be equal to or larger than i64.
6691   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
6692       VT.getVectorElementType() == MVT::i64)
6693     return SDValue();
6694
6695   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
6696   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
6697   while ((1U << Shift) < NumElems) {
6698     if (SVOp->getMaskElt(1U << Shift) == 1)
6699       break;
6700     Shift += 1;
6701     // The maximal ratio is 8, i.e. from i8 to i64.
6702     if (Shift > 3)
6703       return SDValue();
6704   }
6705
6706   // Check the shuffle mask.
6707   unsigned Mask = (1U << Shift) - 1;
6708   for (unsigned i = 0; i != NumElems; ++i) {
6709     int EltIdx = SVOp->getMaskElt(i);
6710     if ((i & Mask) != 0 && EltIdx != -1)
6711       return SDValue();
6712     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
6713       return SDValue();
6714   }
6715
6716   LLVMContext *Context = DAG.getContext();
6717   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
6718   EVT NeVT = EVT::getIntegerVT(*Context, NBits);
6719   EVT NVT = EVT::getVectorVT(*Context, NeVT, NumElems >> Shift);
6720
6721   if (!isTypeLegal(NVT))
6722     return SDValue();
6723
6724   // Simplify the operand as it's prepared to be fed into shuffle.
6725   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
6726   if (V1.getOpcode() == ISD::BITCAST &&
6727       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
6728       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6729       V1.getOperand(0)
6730         .getOperand(0).getValueType().getSizeInBits() == SignificantBits) {
6731     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
6732     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
6733     ConstantSDNode *CIdx =
6734       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
6735     // If it's foldable, i.e. normal load with single use, we will let code
6736     // selection to fold it. Otherwise, we will short the conversion sequence.
6737     if (CIdx && CIdx->getZExtValue() == 0 &&
6738         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
6739       if (V.getValueSizeInBits() > V1.getValueSizeInBits()) {
6740         // The "ext_vec_elt" node is wider than the result node.
6741         // In this case we should extract subvector from V.
6742         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
6743         unsigned Ratio = V.getValueSizeInBits() / V1.getValueSizeInBits();
6744         EVT FullVT = V.getValueType();
6745         EVT SubVecVT = EVT::getVectorVT(*Context,
6746                                         FullVT.getVectorElementType(),
6747                                         FullVT.getVectorNumElements()/Ratio);
6748         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
6749                         DAG.getIntPtrConstant(0));
6750       }
6751       V1 = DAG.getNode(ISD::BITCAST, DL, V1.getValueType(), V);
6752     }
6753   }
6754
6755   return DAG.getNode(ISD::BITCAST, DL, VT,
6756                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
6757 }
6758
6759 SDValue
6760 X86TargetLowering::NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG) const {
6761   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6762   MVT VT = Op.getValueType().getSimpleVT();
6763   SDLoc dl(Op);
6764   SDValue V1 = Op.getOperand(0);
6765   SDValue V2 = Op.getOperand(1);
6766
6767   if (isZeroShuffle(SVOp))
6768     return getZeroVector(VT, Subtarget, DAG, dl);
6769
6770   // Handle splat operations
6771   if (SVOp->isSplat()) {
6772     // Use vbroadcast whenever the splat comes from a foldable load
6773     SDValue Broadcast = LowerVectorBroadcast(Op, DAG);
6774     if (Broadcast.getNode())
6775       return Broadcast;
6776   }
6777
6778   // Check integer expanding shuffles.
6779   SDValue NewOp = LowerVectorIntExtend(Op, DAG);
6780   if (NewOp.getNode())
6781     return NewOp;
6782
6783   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6784   // do it!
6785   if (VT == MVT::v8i16  || VT == MVT::v16i8 ||
6786       VT == MVT::v16i16 || VT == MVT::v32i8) {
6787     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6788     if (NewOp.getNode())
6789       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6790   } else if ((VT == MVT::v4i32 ||
6791              (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
6792     // FIXME: Figure out a cleaner way to do this.
6793     // Try to make use of movq to zero out the top part.
6794     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6795       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6796       if (NewOp.getNode()) {
6797         MVT NewVT = NewOp.getValueType().getSimpleVT();
6798         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
6799                                NewVT, true, false))
6800           return getVZextMovL(VT, NewVT, NewOp.getOperand(0),
6801                               DAG, Subtarget, dl);
6802       }
6803     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6804       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
6805       if (NewOp.getNode()) {
6806         MVT NewVT = NewOp.getValueType().getSimpleVT();
6807         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
6808           return getVZextMovL(VT, NewVT, NewOp.getOperand(1),
6809                               DAG, Subtarget, dl);
6810       }
6811     }
6812   }
6813   return SDValue();
6814 }
6815
6816 SDValue
6817 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6818   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6819   SDValue V1 = Op.getOperand(0);
6820   SDValue V2 = Op.getOperand(1);
6821   MVT VT = Op.getValueType().getSimpleVT();
6822   SDLoc dl(Op);
6823   unsigned NumElems = VT.getVectorNumElements();
6824   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6825   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6826   bool V1IsSplat = false;
6827   bool V2IsSplat = false;
6828   bool HasSSE2 = Subtarget->hasSSE2();
6829   bool HasFp256    = Subtarget->hasFp256();
6830   bool HasInt256   = Subtarget->hasInt256();
6831   MachineFunction &MF = DAG.getMachineFunction();
6832   bool OptForSize = MF.getFunction()->getAttributes().
6833     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6834
6835   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6836
6837   if (V1IsUndef && V2IsUndef)
6838     return DAG.getUNDEF(VT);
6839
6840   assert(!V1IsUndef && "Op 1 of shuffle should not be undef");
6841
6842   // Vector shuffle lowering takes 3 steps:
6843   //
6844   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6845   //    narrowing and commutation of operands should be handled.
6846   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6847   //    shuffle nodes.
6848   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6849   //    so the shuffle can be broken into other shuffles and the legalizer can
6850   //    try the lowering again.
6851   //
6852   // The general idea is that no vector_shuffle operation should be left to
6853   // be matched during isel, all of them must be converted to a target specific
6854   // node here.
6855
6856   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6857   // narrowing and commutation of operands should be handled. The actual code
6858   // doesn't include all of those, work in progress...
6859   SDValue NewOp = NormalizeVectorShuffle(Op, DAG);
6860   if (NewOp.getNode())
6861     return NewOp;
6862
6863   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
6864
6865   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6866   // unpckh_undef). Only use pshufd if speed is more important than size.
6867   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
6868     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
6869   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
6870     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6871
6872   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
6873       V2IsUndef && MayFoldVectorLoad(V1))
6874     return getMOVDDup(Op, dl, V1, DAG);
6875
6876   if (isMOVHLPS_v_undef_Mask(M, VT))
6877     return getMOVHighToLow(Op, dl, DAG);
6878
6879   // Use to match splats
6880   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
6881       (VT == MVT::v2f64 || VT == MVT::v2i64))
6882     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
6883
6884   if (isPSHUFDMask(M, VT)) {
6885     // The actual implementation will match the mask in the if above and then
6886     // during isel it can match several different instructions, not only pshufd
6887     // as its name says, sad but true, emulate the behavior for now...
6888     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6889       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6890
6891     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
6892
6893     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
6894       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6895
6896     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
6897       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
6898                                   DAG);
6899
6900     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
6901                                 TargetMask, DAG);
6902   }
6903
6904   if (isPALIGNRMask(M, VT, Subtarget))
6905     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
6906                                 getShufflePALIGNRImmediate(SVOp),
6907                                 DAG);
6908
6909   // Check if this can be converted into a logical shift.
6910   bool isLeft = false;
6911   unsigned ShAmt = 0;
6912   SDValue ShVal;
6913   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6914   if (isShift && ShVal.hasOneUse()) {
6915     // If the shifted value has multiple uses, it may be cheaper to use
6916     // v_set0 + movlhps or movhlps, etc.
6917     MVT EltVT = VT.getVectorElementType();
6918     ShAmt *= EltVT.getSizeInBits();
6919     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6920   }
6921
6922   if (isMOVLMask(M, VT)) {
6923     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6924       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6925     if (!isMOVLPMask(M, VT)) {
6926       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
6927         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6928
6929       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6930         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6931     }
6932   }
6933
6934   // FIXME: fold these into legal mask.
6935   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
6936     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
6937
6938   if (isMOVHLPSMask(M, VT))
6939     return getMOVHighToLow(Op, dl, DAG);
6940
6941   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
6942     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6943
6944   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
6945     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6946
6947   if (isMOVLPMask(M, VT))
6948     return getMOVLP(Op, dl, DAG, HasSSE2);
6949
6950   if (ShouldXformToMOVHLPS(M, VT) ||
6951       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
6952     return CommuteVectorShuffle(SVOp, DAG);
6953
6954   if (isShift) {
6955     // No better options. Use a vshldq / vsrldq.
6956     MVT EltVT = VT.getVectorElementType();
6957     ShAmt *= EltVT.getSizeInBits();
6958     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6959   }
6960
6961   bool Commuted = false;
6962   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6963   // 1,1,1,1 -> v8i16 though.
6964   V1IsSplat = isSplatVector(V1.getNode());
6965   V2IsSplat = isSplatVector(V2.getNode());
6966
6967   // Canonicalize the splat or undef, if present, to be on the RHS.
6968   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
6969     CommuteVectorShuffleMask(M, NumElems);
6970     std::swap(V1, V2);
6971     std::swap(V1IsSplat, V2IsSplat);
6972     Commuted = true;
6973   }
6974
6975   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
6976     // Shuffling low element of v1 into undef, just return v1.
6977     if (V2IsUndef)
6978       return V1;
6979     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6980     // the instruction selector will not match, so get a canonical MOVL with
6981     // swapped operands to undo the commute.
6982     return getMOVL(DAG, dl, VT, V2, V1);
6983   }
6984
6985   if (isUNPCKLMask(M, VT, HasInt256))
6986     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6987
6988   if (isUNPCKHMask(M, VT, HasInt256))
6989     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
6990
6991   if (V2IsSplat) {
6992     // Normalize mask so all entries that point to V2 points to its first
6993     // element then try to match unpck{h|l} again. If match, return a
6994     // new vector_shuffle with the corrected mask.p
6995     SmallVector<int, 8> NewMask(M.begin(), M.end());
6996     NormalizeMask(NewMask, NumElems);
6997     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
6998       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
6999     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7000       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7001   }
7002
7003   if (Commuted) {
7004     // Commute is back and try unpck* again.
7005     // FIXME: this seems wrong.
7006     CommuteVectorShuffleMask(M, NumElems);
7007     std::swap(V1, V2);
7008     std::swap(V1IsSplat, V2IsSplat);
7009     Commuted = false;
7010
7011     if (isUNPCKLMask(M, VT, HasInt256))
7012       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7013
7014     if (isUNPCKHMask(M, VT, HasInt256))
7015       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7016   }
7017
7018   // Normalize the node to match x86 shuffle ops if needed
7019   if (!V2IsUndef && (isSHUFPMask(M, VT, HasFp256, /* Commuted */ true)))
7020     return CommuteVectorShuffle(SVOp, DAG);
7021
7022   // The checks below are all present in isShuffleMaskLegal, but they are
7023   // inlined here right now to enable us to directly emit target specific
7024   // nodes, and remove one by one until they don't return Op anymore.
7025
7026   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7027       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7028     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7029       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7030   }
7031
7032   if (isPSHUFHWMask(M, VT, HasInt256))
7033     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7034                                 getShufflePSHUFHWImmediate(SVOp),
7035                                 DAG);
7036
7037   if (isPSHUFLWMask(M, VT, HasInt256))
7038     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7039                                 getShufflePSHUFLWImmediate(SVOp),
7040                                 DAG);
7041
7042   if (isSHUFPMask(M, VT, HasFp256))
7043     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7044                                 getShuffleSHUFImmediate(SVOp), DAG);
7045
7046   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7047     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7048   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7049     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7050
7051   //===--------------------------------------------------------------------===//
7052   // Generate target specific nodes for 128 or 256-bit shuffles only
7053   // supported in the AVX instruction set.
7054   //
7055
7056   // Handle VMOVDDUPY permutations
7057   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7058     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7059
7060   // Handle VPERMILPS/D* permutations
7061   if (isVPERMILPMask(M, VT, HasFp256)) {
7062     if (HasInt256 && VT == MVT::v8i32)
7063       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7064                                   getShuffleSHUFImmediate(SVOp), DAG);
7065     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7066                                 getShuffleSHUFImmediate(SVOp), DAG);
7067   }
7068
7069   // Handle VPERM2F128/VPERM2I128 permutations
7070   if (isVPERM2X128Mask(M, VT, HasFp256))
7071     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7072                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7073
7074   SDValue BlendOp = LowerVECTOR_SHUFFLEtoBlend(SVOp, Subtarget, DAG);
7075   if (BlendOp.getNode())
7076     return BlendOp;
7077
7078   if (V2IsUndef && HasInt256 && (VT == MVT::v8i32 || VT == MVT::v8f32)) {
7079     SmallVector<SDValue, 8> permclMask;
7080     for (unsigned i = 0; i != 8; ++i) {
7081       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MVT::i32));
7082     }
7083     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32,
7084                                &permclMask[0], 8);
7085     // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7086     return DAG.getNode(X86ISD::VPERMV, dl, VT,
7087                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7088   }
7089
7090   if (V2IsUndef && HasInt256 && (VT == MVT::v4i64 || VT == MVT::v4f64))
7091     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1,
7092                                 getShuffleCLImmediate(SVOp), DAG);
7093
7094   //===--------------------------------------------------------------------===//
7095   // Since no target specific shuffle was selected for this generic one,
7096   // lower it into other known shuffles. FIXME: this isn't true yet, but
7097   // this is the plan.
7098   //
7099
7100   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7101   if (VT == MVT::v8i16) {
7102     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7103     if (NewOp.getNode())
7104       return NewOp;
7105   }
7106
7107   if (VT == MVT::v16i8) {
7108     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7109     if (NewOp.getNode())
7110       return NewOp;
7111   }
7112
7113   if (VT == MVT::v32i8) {
7114     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7115     if (NewOp.getNode())
7116       return NewOp;
7117   }
7118
7119   // Handle all 128-bit wide vectors with 4 elements, and match them with
7120   // several different shuffle types.
7121   if (NumElems == 4 && VT.is128BitVector())
7122     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7123
7124   // Handle general 256-bit shuffles
7125   if (VT.is256BitVector())
7126     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7127
7128   return SDValue();
7129 }
7130
7131 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7132   MVT VT = Op.getValueType().getSimpleVT();
7133   SDLoc dl(Op);
7134
7135   if (!Op.getOperand(0).getValueType().getSimpleVT().is128BitVector())
7136     return SDValue();
7137
7138   if (VT.getSizeInBits() == 8) {
7139     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7140                                   Op.getOperand(0), Op.getOperand(1));
7141     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7142                                   DAG.getValueType(VT));
7143     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7144   }
7145
7146   if (VT.getSizeInBits() == 16) {
7147     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7148     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7149     if (Idx == 0)
7150       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7151                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7152                                      DAG.getNode(ISD::BITCAST, dl,
7153                                                  MVT::v4i32,
7154                                                  Op.getOperand(0)),
7155                                      Op.getOperand(1)));
7156     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7157                                   Op.getOperand(0), Op.getOperand(1));
7158     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7159                                   DAG.getValueType(VT));
7160     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7161   }
7162
7163   if (VT == MVT::f32) {
7164     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7165     // the result back to FR32 register. It's only worth matching if the
7166     // result has a single use which is a store or a bitcast to i32.  And in
7167     // the case of a store, it's not worth it if the index is a constant 0,
7168     // because a MOVSSmr can be used instead, which is smaller and faster.
7169     if (!Op.hasOneUse())
7170       return SDValue();
7171     SDNode *User = *Op.getNode()->use_begin();
7172     if ((User->getOpcode() != ISD::STORE ||
7173          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7174           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7175         (User->getOpcode() != ISD::BITCAST ||
7176          User->getValueType(0) != MVT::i32))
7177       return SDValue();
7178     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7179                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7180                                               Op.getOperand(0)),
7181                                               Op.getOperand(1));
7182     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7183   }
7184
7185   if (VT == MVT::i32 || VT == MVT::i64) {
7186     // ExtractPS/pextrq works with constant index.
7187     if (isa<ConstantSDNode>(Op.getOperand(1)))
7188       return Op;
7189   }
7190   return SDValue();
7191 }
7192
7193 SDValue
7194 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7195                                            SelectionDAG &DAG) const {
7196   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7197     return SDValue();
7198
7199   SDValue Vec = Op.getOperand(0);
7200   MVT VecVT = Vec.getValueType().getSimpleVT();
7201
7202   // If this is a 256-bit vector result, first extract the 128-bit vector and
7203   // then extract the element from the 128-bit vector.
7204   if (VecVT.is256BitVector()) {
7205     SDLoc dl(Op.getNode());
7206     unsigned NumElems = VecVT.getVectorNumElements();
7207     SDValue Idx = Op.getOperand(1);
7208     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7209
7210     // Get the 128-bit vector.
7211     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
7212
7213     if (IdxVal >= NumElems/2)
7214       IdxVal -= NumElems/2;
7215     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7216                        DAG.getConstant(IdxVal, MVT::i32));
7217   }
7218
7219   assert(VecVT.is128BitVector() && "Unexpected vector length");
7220
7221   if (Subtarget->hasSSE41()) {
7222     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7223     if (Res.getNode())
7224       return Res;
7225   }
7226
7227   MVT VT = Op.getValueType().getSimpleVT();
7228   SDLoc dl(Op);
7229   // TODO: handle v16i8.
7230   if (VT.getSizeInBits() == 16) {
7231     SDValue Vec = Op.getOperand(0);
7232     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7233     if (Idx == 0)
7234       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7235                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7236                                      DAG.getNode(ISD::BITCAST, dl,
7237                                                  MVT::v4i32, Vec),
7238                                      Op.getOperand(1)));
7239     // Transform it so it match pextrw which produces a 32-bit result.
7240     MVT EltVT = MVT::i32;
7241     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7242                                   Op.getOperand(0), Op.getOperand(1));
7243     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7244                                   DAG.getValueType(VT));
7245     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7246   }
7247
7248   if (VT.getSizeInBits() == 32) {
7249     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7250     if (Idx == 0)
7251       return Op;
7252
7253     // SHUFPS the element to the lowest double word, then movss.
7254     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7255     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7256     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7257                                        DAG.getUNDEF(VVT), Mask);
7258     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7259                        DAG.getIntPtrConstant(0));
7260   }
7261
7262   if (VT.getSizeInBits() == 64) {
7263     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7264     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7265     //        to match extract_elt for f64.
7266     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7267     if (Idx == 0)
7268       return Op;
7269
7270     // UNPCKHPD the element to the lowest double word, then movsd.
7271     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7272     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7273     int Mask[2] = { 1, -1 };
7274     MVT VVT = Op.getOperand(0).getValueType().getSimpleVT();
7275     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7276                                        DAG.getUNDEF(VVT), Mask);
7277     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7278                        DAG.getIntPtrConstant(0));
7279   }
7280
7281   return SDValue();
7282 }
7283
7284 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
7285   MVT VT = Op.getValueType().getSimpleVT();
7286   MVT EltVT = VT.getVectorElementType();
7287   SDLoc dl(Op);
7288
7289   SDValue N0 = Op.getOperand(0);
7290   SDValue N1 = Op.getOperand(1);
7291   SDValue N2 = Op.getOperand(2);
7292
7293   if (!VT.is128BitVector())
7294     return SDValue();
7295
7296   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7297       isa<ConstantSDNode>(N2)) {
7298     unsigned Opc;
7299     if (VT == MVT::v8i16)
7300       Opc = X86ISD::PINSRW;
7301     else if (VT == MVT::v16i8)
7302       Opc = X86ISD::PINSRB;
7303     else
7304       Opc = X86ISD::PINSRB;
7305
7306     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7307     // argument.
7308     if (N1.getValueType() != MVT::i32)
7309       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7310     if (N2.getValueType() != MVT::i32)
7311       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7312     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7313   }
7314
7315   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7316     // Bits [7:6] of the constant are the source select.  This will always be
7317     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7318     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7319     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7320     // Bits [5:4] of the constant are the destination select.  This is the
7321     //  value of the incoming immediate.
7322     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7323     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7324     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7325     // Create this as a scalar to vector..
7326     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7327     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7328   }
7329
7330   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
7331     // PINSR* works with constant index.
7332     return Op;
7333   }
7334   return SDValue();
7335 }
7336
7337 SDValue
7338 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7339   MVT VT = Op.getValueType().getSimpleVT();
7340   MVT EltVT = VT.getVectorElementType();
7341
7342   SDLoc dl(Op);
7343   SDValue N0 = Op.getOperand(0);
7344   SDValue N1 = Op.getOperand(1);
7345   SDValue N2 = Op.getOperand(2);
7346
7347   // If this is a 256-bit vector result, first extract the 128-bit vector,
7348   // insert the element into the extracted half and then place it back.
7349   if (VT.is256BitVector()) {
7350     if (!isa<ConstantSDNode>(N2))
7351       return SDValue();
7352
7353     // Get the desired 128-bit vector half.
7354     unsigned NumElems = VT.getVectorNumElements();
7355     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7356     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
7357
7358     // Insert the element into the desired half.
7359     bool Upper = IdxVal >= NumElems/2;
7360     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
7361                  DAG.getConstant(Upper ? IdxVal-NumElems/2 : IdxVal, MVT::i32));
7362
7363     // Insert the changed part back to the 256-bit vector
7364     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
7365   }
7366
7367   if (Subtarget->hasSSE41())
7368     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7369
7370   if (EltVT == MVT::i8)
7371     return SDValue();
7372
7373   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7374     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7375     // as its second argument.
7376     if (N1.getValueType() != MVT::i32)
7377       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7378     if (N2.getValueType() != MVT::i32)
7379       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7380     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7381   }
7382   return SDValue();
7383 }
7384
7385 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
7386   LLVMContext *Context = DAG.getContext();
7387   SDLoc dl(Op);
7388   MVT OpVT = Op.getValueType().getSimpleVT();
7389
7390   // If this is a 256-bit vector result, first insert into a 128-bit
7391   // vector and then insert into the 256-bit vector.
7392   if (!OpVT.is128BitVector()) {
7393     // Insert into a 128-bit vector.
7394     EVT VT128 = EVT::getVectorVT(*Context,
7395                                  OpVT.getVectorElementType(),
7396                                  OpVT.getVectorNumElements() / 2);
7397
7398     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7399
7400     // Insert the 128-bit vector.
7401     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
7402   }
7403
7404   if (OpVT == MVT::v1i64 &&
7405       Op.getOperand(0).getValueType() == MVT::i64)
7406     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7407
7408   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7409   assert(OpVT.is128BitVector() && "Expected an SSE type!");
7410   return DAG.getNode(ISD::BITCAST, dl, OpVT,
7411                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7412 }
7413
7414 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7415 // a simple subregister reference or explicit instructions to grab
7416 // upper bits of a vector.
7417 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7418                                       SelectionDAG &DAG) {
7419   if (Subtarget->hasFp256()) {
7420     SDLoc dl(Op.getNode());
7421     SDValue Vec = Op.getNode()->getOperand(0);
7422     SDValue Idx = Op.getNode()->getOperand(1);
7423
7424     if (Op.getNode()->getValueType(0).is128BitVector() &&
7425         Vec.getNode()->getValueType(0).is256BitVector() &&
7426         isa<ConstantSDNode>(Idx)) {
7427       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7428       return Extract128BitVector(Vec, IdxVal, DAG, dl);
7429     }
7430   }
7431   return SDValue();
7432 }
7433
7434 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7435 // simple superregister reference or explicit instructions to insert
7436 // the upper bits of a vector.
7437 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
7438                                      SelectionDAG &DAG) {
7439   if (Subtarget->hasFp256()) {
7440     SDLoc dl(Op.getNode());
7441     SDValue Vec = Op.getNode()->getOperand(0);
7442     SDValue SubVec = Op.getNode()->getOperand(1);
7443     SDValue Idx = Op.getNode()->getOperand(2);
7444
7445     if (Op.getNode()->getValueType(0).is256BitVector() &&
7446         SubVec.getNode()->getValueType(0).is128BitVector() &&
7447         isa<ConstantSDNode>(Idx)) {
7448       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7449       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
7450     }
7451   }
7452   return SDValue();
7453 }
7454
7455 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7456 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7457 // one of the above mentioned nodes. It has to be wrapped because otherwise
7458 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7459 // be used to form addressing mode. These wrapped nodes will be selected
7460 // into MOV32ri.
7461 SDValue
7462 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7463   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7464
7465   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7466   // global base reg.
7467   unsigned char OpFlag = 0;
7468   unsigned WrapperKind = X86ISD::Wrapper;
7469   CodeModel::Model M = getTargetMachine().getCodeModel();
7470
7471   if (Subtarget->isPICStyleRIPRel() &&
7472       (M == CodeModel::Small || M == CodeModel::Kernel))
7473     WrapperKind = X86ISD::WrapperRIP;
7474   else if (Subtarget->isPICStyleGOT())
7475     OpFlag = X86II::MO_GOTOFF;
7476   else if (Subtarget->isPICStyleStubPIC())
7477     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7478
7479   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7480                                              CP->getAlignment(),
7481                                              CP->getOffset(), OpFlag);
7482   SDLoc DL(CP);
7483   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7484   // With PIC, the address is actually $g + Offset.
7485   if (OpFlag) {
7486     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7487                          DAG.getNode(X86ISD::GlobalBaseReg,
7488                                      SDLoc(), getPointerTy()),
7489                          Result);
7490   }
7491
7492   return Result;
7493 }
7494
7495 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7496   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7497
7498   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7499   // global base reg.
7500   unsigned char OpFlag = 0;
7501   unsigned WrapperKind = X86ISD::Wrapper;
7502   CodeModel::Model M = getTargetMachine().getCodeModel();
7503
7504   if (Subtarget->isPICStyleRIPRel() &&
7505       (M == CodeModel::Small || M == CodeModel::Kernel))
7506     WrapperKind = X86ISD::WrapperRIP;
7507   else if (Subtarget->isPICStyleGOT())
7508     OpFlag = X86II::MO_GOTOFF;
7509   else if (Subtarget->isPICStyleStubPIC())
7510     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7511
7512   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7513                                           OpFlag);
7514   SDLoc DL(JT);
7515   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7516
7517   // With PIC, the address is actually $g + Offset.
7518   if (OpFlag)
7519     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7520                          DAG.getNode(X86ISD::GlobalBaseReg,
7521                                      SDLoc(), getPointerTy()),
7522                          Result);
7523
7524   return Result;
7525 }
7526
7527 SDValue
7528 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7529   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7530
7531   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7532   // global base reg.
7533   unsigned char OpFlag = 0;
7534   unsigned WrapperKind = X86ISD::Wrapper;
7535   CodeModel::Model M = getTargetMachine().getCodeModel();
7536
7537   if (Subtarget->isPICStyleRIPRel() &&
7538       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7539     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7540       OpFlag = X86II::MO_GOTPCREL;
7541     WrapperKind = X86ISD::WrapperRIP;
7542   } else if (Subtarget->isPICStyleGOT()) {
7543     OpFlag = X86II::MO_GOT;
7544   } else if (Subtarget->isPICStyleStubPIC()) {
7545     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7546   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7547     OpFlag = X86II::MO_DARWIN_NONLAZY;
7548   }
7549
7550   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7551
7552   SDLoc DL(Op);
7553   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7554
7555   // With PIC, the address is actually $g + Offset.
7556   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7557       !Subtarget->is64Bit()) {
7558     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7559                          DAG.getNode(X86ISD::GlobalBaseReg,
7560                                      SDLoc(), getPointerTy()),
7561                          Result);
7562   }
7563
7564   // For symbols that require a load from a stub to get the address, emit the
7565   // load.
7566   if (isGlobalStubReference(OpFlag))
7567     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7568                          MachinePointerInfo::getGOT(), false, false, false, 0);
7569
7570   return Result;
7571 }
7572
7573 SDValue
7574 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7575   // Create the TargetBlockAddressAddress node.
7576   unsigned char OpFlags =
7577     Subtarget->ClassifyBlockAddressReference();
7578   CodeModel::Model M = getTargetMachine().getCodeModel();
7579   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7580   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
7581   SDLoc dl(Op);
7582   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
7583                                              OpFlags);
7584
7585   if (Subtarget->isPICStyleRIPRel() &&
7586       (M == CodeModel::Small || M == CodeModel::Kernel))
7587     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7588   else
7589     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7590
7591   // With PIC, the address is actually $g + Offset.
7592   if (isGlobalRelativeToPICBase(OpFlags)) {
7593     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7594                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7595                          Result);
7596   }
7597
7598   return Result;
7599 }
7600
7601 SDValue
7602 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
7603                                       int64_t Offset, SelectionDAG &DAG) const {
7604   // Create the TargetGlobalAddress node, folding in the constant
7605   // offset if it is legal.
7606   unsigned char OpFlags =
7607     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7608   CodeModel::Model M = getTargetMachine().getCodeModel();
7609   SDValue Result;
7610   if (OpFlags == X86II::MO_NO_FLAG &&
7611       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7612     // A direct static reference to a global.
7613     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7614     Offset = 0;
7615   } else {
7616     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7617   }
7618
7619   if (Subtarget->isPICStyleRIPRel() &&
7620       (M == CodeModel::Small || M == CodeModel::Kernel))
7621     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7622   else
7623     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7624
7625   // With PIC, the address is actually $g + Offset.
7626   if (isGlobalRelativeToPICBase(OpFlags)) {
7627     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7628                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7629                          Result);
7630   }
7631
7632   // For globals that require a load from a stub to get the address, emit the
7633   // load.
7634   if (isGlobalStubReference(OpFlags))
7635     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7636                          MachinePointerInfo::getGOT(), false, false, false, 0);
7637
7638   // If there was a non-zero offset that we didn't fold, create an explicit
7639   // addition for it.
7640   if (Offset != 0)
7641     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7642                          DAG.getConstant(Offset, getPointerTy()));
7643
7644   return Result;
7645 }
7646
7647 SDValue
7648 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7649   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7650   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7651   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
7652 }
7653
7654 static SDValue
7655 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7656            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7657            unsigned char OperandFlags, bool LocalDynamic = false) {
7658   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7659   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7660   SDLoc dl(GA);
7661   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7662                                            GA->getValueType(0),
7663                                            GA->getOffset(),
7664                                            OperandFlags);
7665
7666   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
7667                                            : X86ISD::TLSADDR;
7668
7669   if (InFlag) {
7670     SDValue Ops[] = { Chain,  TGA, *InFlag };
7671     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7672   } else {
7673     SDValue Ops[]  = { Chain, TGA };
7674     Chain = DAG.getNode(CallType, dl, NodeTys, Ops, array_lengthof(Ops));
7675   }
7676
7677   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7678   MFI->setAdjustsStack(true);
7679
7680   SDValue Flag = Chain.getValue(1);
7681   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7682 }
7683
7684 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7685 static SDValue
7686 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7687                                 const EVT PtrVT) {
7688   SDValue InFlag;
7689   SDLoc dl(GA);  // ? function entry point might be better
7690   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7691                                    DAG.getNode(X86ISD::GlobalBaseReg,
7692                                                SDLoc(), PtrVT), InFlag);
7693   InFlag = Chain.getValue(1);
7694
7695   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7696 }
7697
7698 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7699 static SDValue
7700 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7701                                 const EVT PtrVT) {
7702   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7703                     X86::RAX, X86II::MO_TLSGD);
7704 }
7705
7706 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
7707                                            SelectionDAG &DAG,
7708                                            const EVT PtrVT,
7709                                            bool is64Bit) {
7710   SDLoc dl(GA);
7711
7712   // Get the start address of the TLS block for this module.
7713   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
7714       .getInfo<X86MachineFunctionInfo>();
7715   MFI->incNumLocalDynamicTLSAccesses();
7716
7717   SDValue Base;
7718   if (is64Bit) {
7719     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX,
7720                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
7721   } else {
7722     SDValue InFlag;
7723     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7724         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
7725     InFlag = Chain.getValue(1);
7726     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
7727                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
7728   }
7729
7730   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
7731   // of Base.
7732
7733   // Build x@dtpoff.
7734   unsigned char OperandFlags = X86II::MO_DTPOFF;
7735   unsigned WrapperKind = X86ISD::Wrapper;
7736   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7737                                            GA->getValueType(0),
7738                                            GA->getOffset(), OperandFlags);
7739   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7740
7741   // Add x@dtpoff with the base.
7742   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
7743 }
7744
7745 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
7746 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7747                                    const EVT PtrVT, TLSModel::Model model,
7748                                    bool is64Bit, bool isPIC) {
7749   SDLoc dl(GA);
7750
7751   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7752   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7753                                                          is64Bit ? 257 : 256));
7754
7755   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7756                                       DAG.getIntPtrConstant(0),
7757                                       MachinePointerInfo(Ptr),
7758                                       false, false, false, 0);
7759
7760   unsigned char OperandFlags = 0;
7761   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7762   // initialexec.
7763   unsigned WrapperKind = X86ISD::Wrapper;
7764   if (model == TLSModel::LocalExec) {
7765     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7766   } else if (model == TLSModel::InitialExec) {
7767     if (is64Bit) {
7768       OperandFlags = X86II::MO_GOTTPOFF;
7769       WrapperKind = X86ISD::WrapperRIP;
7770     } else {
7771       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
7772     }
7773   } else {
7774     llvm_unreachable("Unexpected model");
7775   }
7776
7777   // emit "addl x@ntpoff,%eax" (local exec)
7778   // or "addl x@indntpoff,%eax" (initial exec)
7779   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
7780   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7781                                            GA->getValueType(0),
7782                                            GA->getOffset(), OperandFlags);
7783   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7784
7785   if (model == TLSModel::InitialExec) {
7786     if (isPIC && !is64Bit) {
7787       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
7788                           DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
7789                            Offset);
7790     }
7791
7792     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7793                          MachinePointerInfo::getGOT(), false, false, false,
7794                          0);
7795   }
7796
7797   // The address of the thread local variable is the add of the thread
7798   // pointer with the offset of the variable.
7799   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7800 }
7801
7802 SDValue
7803 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7804
7805   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7806   const GlobalValue *GV = GA->getGlobal();
7807
7808   if (Subtarget->isTargetELF()) {
7809     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
7810
7811     switch (model) {
7812       case TLSModel::GeneralDynamic:
7813         if (Subtarget->is64Bit())
7814           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7815         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7816       case TLSModel::LocalDynamic:
7817         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
7818                                            Subtarget->is64Bit());
7819       case TLSModel::InitialExec:
7820       case TLSModel::LocalExec:
7821         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7822                                    Subtarget->is64Bit(),
7823                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
7824     }
7825     llvm_unreachable("Unknown TLS model.");
7826   }
7827
7828   if (Subtarget->isTargetDarwin()) {
7829     // Darwin only has one model of TLS.  Lower to that.
7830     unsigned char OpFlag = 0;
7831     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7832                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7833
7834     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7835     // global base reg.
7836     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7837                   !Subtarget->is64Bit();
7838     if (PIC32)
7839       OpFlag = X86II::MO_TLVP_PIC_BASE;
7840     else
7841       OpFlag = X86II::MO_TLVP;
7842     SDLoc DL(Op);
7843     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7844                                                 GA->getValueType(0),
7845                                                 GA->getOffset(), OpFlag);
7846     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7847
7848     // With PIC32, the address is actually $g + Offset.
7849     if (PIC32)
7850       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7851                            DAG.getNode(X86ISD::GlobalBaseReg,
7852                                        SDLoc(), getPointerTy()),
7853                            Offset);
7854
7855     // Lowering the machine isd will make sure everything is in the right
7856     // location.
7857     SDValue Chain = DAG.getEntryNode();
7858     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7859     SDValue Args[] = { Chain, Offset };
7860     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7861
7862     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7863     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7864     MFI->setAdjustsStack(true);
7865
7866     // And our return value (tls address) is in the standard call return value
7867     // location.
7868     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7869     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7870                               Chain.getValue(1));
7871   }
7872
7873   if (Subtarget->isTargetWindows() || Subtarget->isTargetMingw()) {
7874     // Just use the implicit TLS architecture
7875     // Need to generate someting similar to:
7876     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
7877     //                                  ; from TEB
7878     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
7879     //   mov     rcx, qword [rdx+rcx*8]
7880     //   mov     eax, .tls$:tlsvar
7881     //   [rax+rcx] contains the address
7882     // Windows 64bit: gs:0x58
7883     // Windows 32bit: fs:__tls_array
7884
7885     // If GV is an alias then use the aliasee for determining
7886     // thread-localness.
7887     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7888       GV = GA->resolveAliasedGlobal(false);
7889     SDLoc dl(GA);
7890     SDValue Chain = DAG.getEntryNode();
7891
7892     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
7893     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
7894     // use its literal value of 0x2C.
7895     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
7896                                         ? Type::getInt8PtrTy(*DAG.getContext(),
7897                                                              256)
7898                                         : Type::getInt32PtrTy(*DAG.getContext(),
7899                                                               257));
7900
7901     SDValue TlsArray = Subtarget->is64Bit() ? DAG.getIntPtrConstant(0x58) :
7902       (Subtarget->isTargetMingw() ? DAG.getIntPtrConstant(0x2C) :
7903         DAG.getExternalSymbol("_tls_array", getPointerTy()));
7904
7905     SDValue ThreadPointer = DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
7906                                         MachinePointerInfo(Ptr),
7907                                         false, false, false, 0);
7908
7909     // Load the _tls_index variable
7910     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
7911     if (Subtarget->is64Bit())
7912       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
7913                            IDX, MachinePointerInfo(), MVT::i32,
7914                            false, false, 0);
7915     else
7916       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
7917                         false, false, false, 0);
7918
7919     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
7920                                     getPointerTy());
7921     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
7922
7923     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
7924     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
7925                       false, false, false, 0);
7926
7927     // Get the offset of start of .tls section
7928     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7929                                              GA->getValueType(0),
7930                                              GA->getOffset(), X86II::MO_SECREL);
7931     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
7932
7933     // The address of the thread local variable is the add of the thread
7934     // pointer with the offset of the variable.
7935     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
7936   }
7937
7938   llvm_unreachable("TLS not implemented for this target.");
7939 }
7940
7941 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
7942 /// and take a 2 x i32 value to shift plus a shift amount.
7943 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const{
7944   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7945   EVT VT = Op.getValueType();
7946   unsigned VTBits = VT.getSizeInBits();
7947   SDLoc dl(Op);
7948   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7949   SDValue ShOpLo = Op.getOperand(0);
7950   SDValue ShOpHi = Op.getOperand(1);
7951   SDValue ShAmt  = Op.getOperand(2);
7952   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7953                                      DAG.getConstant(VTBits - 1, MVT::i8))
7954                        : DAG.getConstant(0, VT);
7955
7956   SDValue Tmp2, Tmp3;
7957   if (Op.getOpcode() == ISD::SHL_PARTS) {
7958     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7959     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7960   } else {
7961     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7962     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7963   }
7964
7965   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7966                                 DAG.getConstant(VTBits, MVT::i8));
7967   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7968                              AndNode, DAG.getConstant(0, MVT::i8));
7969
7970   SDValue Hi, Lo;
7971   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7972   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7973   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7974
7975   if (Op.getOpcode() == ISD::SHL_PARTS) {
7976     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7977     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7978   } else {
7979     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7980     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7981   }
7982
7983   SDValue Ops[2] = { Lo, Hi };
7984   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
7985 }
7986
7987 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7988                                            SelectionDAG &DAG) const {
7989   EVT SrcVT = Op.getOperand(0).getValueType();
7990
7991   if (SrcVT.isVector())
7992     return SDValue();
7993
7994   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7995          "Unknown SINT_TO_FP to lower!");
7996
7997   // These are really Legal; return the operand so the caller accepts it as
7998   // Legal.
7999   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
8000     return Op;
8001   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
8002       Subtarget->is64Bit()) {
8003     return Op;
8004   }
8005
8006   SDLoc dl(Op);
8007   unsigned Size = SrcVT.getSizeInBits()/8;
8008   MachineFunction &MF = DAG.getMachineFunction();
8009   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
8010   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8011   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8012                                StackSlot,
8013                                MachinePointerInfo::getFixedStack(SSFI),
8014                                false, false, 0);
8015   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
8016 }
8017
8018 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
8019                                      SDValue StackSlot,
8020                                      SelectionDAG &DAG) const {
8021   // Build the FILD
8022   SDLoc DL(Op);
8023   SDVTList Tys;
8024   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
8025   if (useSSE)
8026     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
8027   else
8028     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
8029
8030   unsigned ByteSize = SrcVT.getSizeInBits()/8;
8031
8032   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
8033   MachineMemOperand *MMO;
8034   if (FI) {
8035     int SSFI = FI->getIndex();
8036     MMO =
8037       DAG.getMachineFunction()
8038       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8039                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
8040   } else {
8041     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
8042     StackSlot = StackSlot.getOperand(1);
8043   }
8044   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
8045   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
8046                                            X86ISD::FILD, DL,
8047                                            Tys, Ops, array_lengthof(Ops),
8048                                            SrcVT, MMO);
8049
8050   if (useSSE) {
8051     Chain = Result.getValue(1);
8052     SDValue InFlag = Result.getValue(2);
8053
8054     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
8055     // shouldn't be necessary except that RFP cannot be live across
8056     // multiple blocks. When stackifier is fixed, they can be uncoupled.
8057     MachineFunction &MF = DAG.getMachineFunction();
8058     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
8059     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
8060     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8061     Tys = DAG.getVTList(MVT::Other);
8062     SDValue Ops[] = {
8063       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
8064     };
8065     MachineMemOperand *MMO =
8066       DAG.getMachineFunction()
8067       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8068                             MachineMemOperand::MOStore, SSFISize, SSFISize);
8069
8070     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
8071                                     Ops, array_lengthof(Ops),
8072                                     Op.getValueType(), MMO);
8073     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
8074                          MachinePointerInfo::getFixedStack(SSFI),
8075                          false, false, false, 0);
8076   }
8077
8078   return Result;
8079 }
8080
8081 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
8082 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
8083                                                SelectionDAG &DAG) const {
8084   // This algorithm is not obvious. Here it is what we're trying to output:
8085   /*
8086      movq       %rax,  %xmm0
8087      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
8088      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
8089      #ifdef __SSE3__
8090        haddpd   %xmm0, %xmm0
8091      #else
8092        pshufd   $0x4e, %xmm0, %xmm1
8093        addpd    %xmm1, %xmm0
8094      #endif
8095   */
8096
8097   SDLoc dl(Op);
8098   LLVMContext *Context = DAG.getContext();
8099
8100   // Build some magic constants.
8101   const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
8102   Constant *C0 = ConstantDataVector::get(*Context, CV0);
8103   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
8104
8105   SmallVector<Constant*,2> CV1;
8106   CV1.push_back(
8107     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8108                                       APInt(64, 0x4330000000000000ULL))));
8109   CV1.push_back(
8110     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8111                                       APInt(64, 0x4530000000000000ULL))));
8112   Constant *C1 = ConstantVector::get(CV1);
8113   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
8114
8115   // Load the 64-bit value into an XMM register.
8116   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
8117                             Op.getOperand(0));
8118   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
8119                               MachinePointerInfo::getConstantPool(),
8120                               false, false, false, 16);
8121   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
8122                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
8123                               CLod0);
8124
8125   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
8126                               MachinePointerInfo::getConstantPool(),
8127                               false, false, false, 16);
8128   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
8129   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
8130   SDValue Result;
8131
8132   if (Subtarget->hasSSE3()) {
8133     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
8134     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
8135   } else {
8136     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
8137     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
8138                                            S2F, 0x4E, DAG);
8139     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
8140                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
8141                          Sub);
8142   }
8143
8144   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
8145                      DAG.getIntPtrConstant(0));
8146 }
8147
8148 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
8149 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
8150                                                SelectionDAG &DAG) const {
8151   SDLoc dl(Op);
8152   // FP constant to bias correct the final result.
8153   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
8154                                    MVT::f64);
8155
8156   // Load the 32-bit value into an XMM register.
8157   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
8158                              Op.getOperand(0));
8159
8160   // Zero out the upper parts of the register.
8161   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
8162
8163   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8164                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
8165                      DAG.getIntPtrConstant(0));
8166
8167   // Or the load with the bias.
8168   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
8169                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8170                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8171                                                    MVT::v2f64, Load)),
8172                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8173                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8174                                                    MVT::v2f64, Bias)));
8175   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8176                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
8177                    DAG.getIntPtrConstant(0));
8178
8179   // Subtract the bias.
8180   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
8181
8182   // Handle final rounding.
8183   EVT DestVT = Op.getValueType();
8184
8185   if (DestVT.bitsLT(MVT::f64))
8186     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
8187                        DAG.getIntPtrConstant(0));
8188   if (DestVT.bitsGT(MVT::f64))
8189     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
8190
8191   // Handle final rounding.
8192   return Sub;
8193 }
8194
8195 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
8196                                                SelectionDAG &DAG) const {
8197   SDValue N0 = Op.getOperand(0);
8198   EVT SVT = N0.getValueType();
8199   SDLoc dl(Op);
8200
8201   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
8202           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
8203          "Custom UINT_TO_FP is not supported!");
8204
8205   EVT NVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
8206                              SVT.getVectorNumElements());
8207   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
8208                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
8209 }
8210
8211 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
8212                                            SelectionDAG &DAG) const {
8213   SDValue N0 = Op.getOperand(0);
8214   SDLoc dl(Op);
8215
8216   if (Op.getValueType().isVector())
8217     return lowerUINT_TO_FP_vec(Op, DAG);
8218
8219   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8220   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8221   // the optimization here.
8222   if (DAG.SignBitIsZero(N0))
8223     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8224
8225   EVT SrcVT = N0.getValueType();
8226   EVT DstVT = Op.getValueType();
8227   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8228     return LowerUINT_TO_FP_i64(Op, DAG);
8229   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8230     return LowerUINT_TO_FP_i32(Op, DAG);
8231   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
8232     return SDValue();
8233
8234   // Make a 64-bit buffer, and use it to build an FILD.
8235   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8236   if (SrcVT == MVT::i32) {
8237     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8238     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8239                                      getPointerTy(), StackSlot, WordOff);
8240     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8241                                   StackSlot, MachinePointerInfo(),
8242                                   false, false, 0);
8243     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8244                                   OffsetSlot, MachinePointerInfo(),
8245                                   false, false, 0);
8246     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8247     return Fild;
8248   }
8249
8250   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8251   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8252                                StackSlot, MachinePointerInfo(),
8253                                false, false, 0);
8254   // For i64 source, we need to add the appropriate power of 2 if the input
8255   // was negative.  This is the same as the optimization in
8256   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8257   // we must be careful to do the computation in x87 extended precision, not
8258   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8259   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8260   MachineMemOperand *MMO =
8261     DAG.getMachineFunction()
8262     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8263                           MachineMemOperand::MOLoad, 8, 8);
8264
8265   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8266   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8267   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
8268                                          array_lengthof(Ops), MVT::i64, MMO);
8269
8270   APInt FF(32, 0x5F800000ULL);
8271
8272   // Check whether the sign bit is set.
8273   SDValue SignSet = DAG.getSetCC(dl,
8274                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
8275                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8276                                  ISD::SETLT);
8277
8278   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8279   SDValue FudgePtr = DAG.getConstantPool(
8280                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8281                                          getPointerTy());
8282
8283   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8284   SDValue Zero = DAG.getIntPtrConstant(0);
8285   SDValue Four = DAG.getIntPtrConstant(4);
8286   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8287                                Zero, Four);
8288   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8289
8290   // Load the value out, extending it from f32 to f80.
8291   // FIXME: Avoid the extend by constructing the right constant pool?
8292   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8293                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8294                                  MVT::f32, false, false, 4);
8295   // Extend everything to 80 bits to force it to be done on x87.
8296   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8297   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8298 }
8299
8300 std::pair<SDValue,SDValue>
8301 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
8302                                     bool IsSigned, bool IsReplace) const {
8303   SDLoc DL(Op);
8304
8305   EVT DstTy = Op.getValueType();
8306
8307   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
8308     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8309     DstTy = MVT::i64;
8310   }
8311
8312   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8313          DstTy.getSimpleVT() >= MVT::i16 &&
8314          "Unknown FP_TO_INT to lower!");
8315
8316   // These are really Legal.
8317   if (DstTy == MVT::i32 &&
8318       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8319     return std::make_pair(SDValue(), SDValue());
8320   if (Subtarget->is64Bit() &&
8321       DstTy == MVT::i64 &&
8322       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8323     return std::make_pair(SDValue(), SDValue());
8324
8325   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
8326   // stack slot, or into the FTOL runtime function.
8327   MachineFunction &MF = DAG.getMachineFunction();
8328   unsigned MemSize = DstTy.getSizeInBits()/8;
8329   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8330   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8331
8332   unsigned Opc;
8333   if (!IsSigned && isIntegerTypeFTOL(DstTy))
8334     Opc = X86ISD::WIN_FTOL;
8335   else
8336     switch (DstTy.getSimpleVT().SimpleTy) {
8337     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8338     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8339     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8340     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8341     }
8342
8343   SDValue Chain = DAG.getEntryNode();
8344   SDValue Value = Op.getOperand(0);
8345   EVT TheVT = Op.getOperand(0).getValueType();
8346   // FIXME This causes a redundant load/store if the SSE-class value is already
8347   // in memory, such as if it is on the callstack.
8348   if (isScalarFPTypeInSSEReg(TheVT)) {
8349     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8350     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8351                          MachinePointerInfo::getFixedStack(SSFI),
8352                          false, false, 0);
8353     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8354     SDValue Ops[] = {
8355       Chain, StackSlot, DAG.getValueType(TheVT)
8356     };
8357
8358     MachineMemOperand *MMO =
8359       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8360                               MachineMemOperand::MOLoad, MemSize, MemSize);
8361     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops,
8362                                     array_lengthof(Ops), DstTy, MMO);
8363     Chain = Value.getValue(1);
8364     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8365     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8366   }
8367
8368   MachineMemOperand *MMO =
8369     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8370                             MachineMemOperand::MOStore, MemSize, MemSize);
8371
8372   if (Opc != X86ISD::WIN_FTOL) {
8373     // Build the FP_TO_INT*_IN_MEM
8374     SDValue Ops[] = { Chain, Value, StackSlot };
8375     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8376                                            Ops, array_lengthof(Ops), DstTy,
8377                                            MMO);
8378     return std::make_pair(FIST, StackSlot);
8379   } else {
8380     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
8381       DAG.getVTList(MVT::Other, MVT::Glue),
8382       Chain, Value);
8383     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
8384       MVT::i32, ftol.getValue(1));
8385     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
8386       MVT::i32, eax.getValue(2));
8387     SDValue Ops[] = { eax, edx };
8388     SDValue pair = IsReplace
8389       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops, array_lengthof(Ops))
8390       : DAG.getMergeValues(Ops, array_lengthof(Ops), DL);
8391     return std::make_pair(pair, SDValue());
8392   }
8393 }
8394
8395 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
8396                               const X86Subtarget *Subtarget) {
8397   MVT VT = Op->getValueType(0).getSimpleVT();
8398   SDValue In = Op->getOperand(0);
8399   MVT InVT = In.getValueType().getSimpleVT();
8400   SDLoc dl(Op);
8401
8402   // Optimize vectors in AVX mode:
8403   //
8404   //   v8i16 -> v8i32
8405   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
8406   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
8407   //   Concat upper and lower parts.
8408   //
8409   //   v4i32 -> v4i64
8410   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
8411   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
8412   //   Concat upper and lower parts.
8413   //
8414
8415   if (((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
8416       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
8417     return SDValue();
8418
8419   if (Subtarget->hasInt256())
8420     return DAG.getNode(X86ISD::VZEXT_MOVL, dl, VT, In);
8421
8422   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
8423   SDValue Undef = DAG.getUNDEF(InVT);
8424   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
8425   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8426   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
8427
8428   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
8429                              VT.getVectorNumElements()/2);
8430
8431   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
8432   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
8433
8434   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
8435 }
8436
8437 SDValue X86TargetLowering::LowerANY_EXTEND(SDValue Op,
8438                                            SelectionDAG &DAG) const {
8439   if (Subtarget->hasFp256()) {
8440     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8441     if (Res.getNode())
8442       return Res;
8443   }
8444
8445   return SDValue();
8446 }
8447 SDValue X86TargetLowering::LowerZERO_EXTEND(SDValue Op,
8448                                             SelectionDAG &DAG) const {
8449   SDLoc DL(Op);
8450   MVT VT = Op.getValueType().getSimpleVT();
8451   SDValue In = Op.getOperand(0);
8452   MVT SVT = In.getValueType().getSimpleVT();
8453
8454   if (Subtarget->hasFp256()) {
8455     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
8456     if (Res.getNode())
8457       return Res;
8458   }
8459
8460   if (!VT.is256BitVector() || !SVT.is128BitVector() ||
8461       VT.getVectorNumElements() != SVT.getVectorNumElements())
8462     return SDValue();
8463
8464   assert(Subtarget->hasFp256() && "256-bit vector is observed without AVX!");
8465
8466   // AVX2 has better support of integer extending.
8467   if (Subtarget->hasInt256())
8468     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
8469
8470   SDValue Lo = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32, In);
8471   static const int Mask[] = {4, 5, 6, 7, -1, -1, -1, -1};
8472   SDValue Hi = DAG.getNode(X86ISD::VZEXT, DL, MVT::v4i32,
8473                            DAG.getVectorShuffle(MVT::v8i16, DL, In,
8474                                                 DAG.getUNDEF(MVT::v8i16),
8475                                                 &Mask[0]));
8476
8477   return DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i32, Lo, Hi);
8478 }
8479
8480 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
8481   SDLoc DL(Op);
8482   MVT VT = Op.getValueType().getSimpleVT();
8483   SDValue In = Op.getOperand(0);
8484   MVT SVT = In.getValueType().getSimpleVT();
8485
8486   if ((VT == MVT::v4i32) && (SVT == MVT::v4i64)) {
8487     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
8488     if (Subtarget->hasInt256()) {
8489       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
8490       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
8491       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
8492                                 ShufMask);
8493       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
8494                          DAG.getIntPtrConstant(0));
8495     }
8496
8497     // On AVX, v4i64 -> v4i32 becomes a sequence that uses PSHUFD and MOVLHPS.
8498     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8499                                DAG.getIntPtrConstant(0));
8500     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8501                                DAG.getIntPtrConstant(2));
8502
8503     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8504     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8505
8506     // The PSHUFD mask:
8507     static const int ShufMask1[] = {0, 2, 0, 0};
8508     SDValue Undef = DAG.getUNDEF(VT);
8509     OpLo = DAG.getVectorShuffle(VT, DL, OpLo, Undef, ShufMask1);
8510     OpHi = DAG.getVectorShuffle(VT, DL, OpHi, Undef, ShufMask1);
8511
8512     // The MOVLHPS mask:
8513     static const int ShufMask2[] = {0, 1, 4, 5};
8514     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask2);
8515   }
8516
8517   if ((VT == MVT::v8i16) && (SVT == MVT::v8i32)) {
8518     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
8519     if (Subtarget->hasInt256()) {
8520       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
8521
8522       SmallVector<SDValue,32> pshufbMask;
8523       for (unsigned i = 0; i < 2; ++i) {
8524         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
8525         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
8526         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
8527         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
8528         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
8529         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
8530         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
8531         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
8532         for (unsigned j = 0; j < 8; ++j)
8533           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
8534       }
8535       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8,
8536                                &pshufbMask[0], 32);
8537       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
8538       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
8539
8540       static const int ShufMask[] = {0,  2,  -1,  -1};
8541       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
8542                                 &ShufMask[0]);
8543       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
8544                        DAG.getIntPtrConstant(0));
8545       return DAG.getNode(ISD::BITCAST, DL, VT, In);
8546     }
8547
8548     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8549                                DAG.getIntPtrConstant(0));
8550
8551     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
8552                                DAG.getIntPtrConstant(4));
8553
8554     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
8555     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
8556
8557     // The PSHUFB mask:
8558     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
8559                                    -1, -1, -1, -1, -1, -1, -1, -1};
8560
8561     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
8562     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
8563     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
8564
8565     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
8566     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
8567
8568     // The MOVLHPS Mask:
8569     static const int ShufMask2[] = {0, 1, 4, 5};
8570     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
8571     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
8572   }
8573
8574   // Handle truncation of V256 to V128 using shuffles.
8575   if (!VT.is128BitVector() || !SVT.is256BitVector())
8576     return SDValue();
8577
8578   assert(VT.getVectorNumElements() != SVT.getVectorNumElements() &&
8579          "Invalid op");
8580   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
8581
8582   unsigned NumElems = VT.getVectorNumElements();
8583   EVT NVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8584                              NumElems * 2);
8585
8586   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
8587   // Prepare truncation shuffle mask
8588   for (unsigned i = 0; i != NumElems; ++i)
8589     MaskVec[i] = i * 2;
8590   SDValue V = DAG.getVectorShuffle(NVT, DL,
8591                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
8592                                    DAG.getUNDEF(NVT), &MaskVec[0]);
8593   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
8594                      DAG.getIntPtrConstant(0));
8595 }
8596
8597 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8598                                            SelectionDAG &DAG) const {
8599   MVT VT = Op.getValueType().getSimpleVT();
8600   if (VT.isVector()) {
8601     if (VT == MVT::v8i16)
8602       return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT,
8603                          DAG.getNode(ISD::FP_TO_SINT, SDLoc(Op),
8604                                      MVT::v8i32, Op.getOperand(0)));
8605     return SDValue();
8606   }
8607
8608   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8609     /*IsSigned=*/ true, /*IsReplace=*/ false);
8610   SDValue FIST = Vals.first, StackSlot = Vals.second;
8611   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8612   if (FIST.getNode() == 0) return Op;
8613
8614   if (StackSlot.getNode())
8615     // Load the result.
8616     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8617                        FIST, StackSlot, MachinePointerInfo(),
8618                        false, false, false, 0);
8619
8620   // The node is the result.
8621   return FIST;
8622 }
8623
8624 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8625                                            SelectionDAG &DAG) const {
8626   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
8627     /*IsSigned=*/ false, /*IsReplace=*/ false);
8628   SDValue FIST = Vals.first, StackSlot = Vals.second;
8629   assert(FIST.getNode() && "Unexpected failure");
8630
8631   if (StackSlot.getNode())
8632     // Load the result.
8633     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
8634                        FIST, StackSlot, MachinePointerInfo(),
8635                        false, false, false, 0);
8636
8637   // The node is the result.
8638   return FIST;
8639 }
8640
8641 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
8642   SDLoc DL(Op);
8643   MVT VT = Op.getValueType().getSimpleVT();
8644   SDValue In = Op.getOperand(0);
8645   MVT SVT = In.getValueType().getSimpleVT();
8646
8647   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
8648
8649   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
8650                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
8651                                  In, DAG.getUNDEF(SVT)));
8652 }
8653
8654 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
8655   LLVMContext *Context = DAG.getContext();
8656   SDLoc dl(Op);
8657   MVT VT = Op.getValueType().getSimpleVT();
8658   MVT EltVT = VT;
8659   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8660   if (VT.isVector()) {
8661     EltVT = VT.getVectorElementType();
8662     NumElts = VT.getVectorNumElements();
8663   }
8664   Constant *C;
8665   if (EltVT == MVT::f64)
8666     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8667                                           APInt(64, ~(1ULL << 63))));
8668   else
8669     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8670                                           APInt(32, ~(1U << 31))));
8671   C = ConstantVector::getSplat(NumElts, C);
8672   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8673   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8674   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8675                              MachinePointerInfo::getConstantPool(),
8676                              false, false, false, Alignment);
8677   if (VT.isVector()) {
8678     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8679     return DAG.getNode(ISD::BITCAST, dl, VT,
8680                        DAG.getNode(ISD::AND, dl, ANDVT,
8681                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
8682                                                Op.getOperand(0)),
8683                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
8684   }
8685   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8686 }
8687
8688 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8689   LLVMContext *Context = DAG.getContext();
8690   SDLoc dl(Op);
8691   MVT VT = Op.getValueType().getSimpleVT();
8692   MVT EltVT = VT;
8693   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
8694   if (VT.isVector()) {
8695     EltVT = VT.getVectorElementType();
8696     NumElts = VT.getVectorNumElements();
8697   }
8698   Constant *C;
8699   if (EltVT == MVT::f64)
8700     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
8701                                           APInt(64, 1ULL << 63)));
8702   else
8703     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
8704                                           APInt(32, 1U << 31)));
8705   C = ConstantVector::getSplat(NumElts, C);
8706   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy());
8707   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
8708   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8709                              MachinePointerInfo::getConstantPool(),
8710                              false, false, false, Alignment);
8711   if (VT.isVector()) {
8712     MVT XORVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8713     return DAG.getNode(ISD::BITCAST, dl, VT,
8714                        DAG.getNode(ISD::XOR, dl, XORVT,
8715                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
8716                                                Op.getOperand(0)),
8717                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
8718   }
8719
8720   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8721 }
8722
8723 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8724   LLVMContext *Context = DAG.getContext();
8725   SDValue Op0 = Op.getOperand(0);
8726   SDValue Op1 = Op.getOperand(1);
8727   SDLoc dl(Op);
8728   MVT VT = Op.getValueType().getSimpleVT();
8729   MVT SrcVT = Op1.getValueType().getSimpleVT();
8730
8731   // If second operand is smaller, extend it first.
8732   if (SrcVT.bitsLT(VT)) {
8733     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8734     SrcVT = VT;
8735   }
8736   // And if it is bigger, shrink it first.
8737   if (SrcVT.bitsGT(VT)) {
8738     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8739     SrcVT = VT;
8740   }
8741
8742   // At this point the operands and the result should have the same
8743   // type, and that won't be f80 since that is not custom lowered.
8744
8745   // First get the sign bit of second operand.
8746   SmallVector<Constant*,4> CV;
8747   if (SrcVT == MVT::f64) {
8748     const fltSemantics &Sem = APFloat::IEEEdouble;
8749     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
8750     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8751   } else {
8752     const fltSemantics &Sem = APFloat::IEEEsingle;
8753     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
8754     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8755     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8756     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8757   }
8758   Constant *C = ConstantVector::get(CV);
8759   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8760   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8761                               MachinePointerInfo::getConstantPool(),
8762                               false, false, false, 16);
8763   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8764
8765   // Shift sign bit right or left if the two operands have different types.
8766   if (SrcVT.bitsGT(VT)) {
8767     // Op0 is MVT::f32, Op1 is MVT::f64.
8768     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8769     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8770                           DAG.getConstant(32, MVT::i32));
8771     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8772     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8773                           DAG.getIntPtrConstant(0));
8774   }
8775
8776   // Clear first operand sign bit.
8777   CV.clear();
8778   if (VT == MVT::f64) {
8779     const fltSemantics &Sem = APFloat::IEEEdouble;
8780     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8781                                                    APInt(64, ~(1ULL << 63)))));
8782     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
8783   } else {
8784     const fltSemantics &Sem = APFloat::IEEEsingle;
8785     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
8786                                                    APInt(32, ~(1U << 31)))));
8787     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8788     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8789     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
8790   }
8791   C = ConstantVector::get(CV);
8792   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8793   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8794                               MachinePointerInfo::getConstantPool(),
8795                               false, false, false, 16);
8796   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8797
8798   // Or the value with the sign bit.
8799   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8800 }
8801
8802 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
8803   SDValue N0 = Op.getOperand(0);
8804   SDLoc dl(Op);
8805   MVT VT = Op.getValueType().getSimpleVT();
8806
8807   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8808   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8809                                   DAG.getConstant(1, VT));
8810   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8811 }
8812
8813 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
8814 //
8815 SDValue X86TargetLowering::LowerVectorAllZeroTest(SDValue Op,
8816                                                   SelectionDAG &DAG) const {
8817   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
8818
8819   if (!Subtarget->hasSSE41())
8820     return SDValue();
8821
8822   if (!Op->hasOneUse())
8823     return SDValue();
8824
8825   SDNode *N = Op.getNode();
8826   SDLoc DL(N);
8827
8828   SmallVector<SDValue, 8> Opnds;
8829   DenseMap<SDValue, unsigned> VecInMap;
8830   EVT VT = MVT::Other;
8831
8832   // Recognize a special case where a vector is casted into wide integer to
8833   // test all 0s.
8834   Opnds.push_back(N->getOperand(0));
8835   Opnds.push_back(N->getOperand(1));
8836
8837   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
8838     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
8839     // BFS traverse all OR'd operands.
8840     if (I->getOpcode() == ISD::OR) {
8841       Opnds.push_back(I->getOperand(0));
8842       Opnds.push_back(I->getOperand(1));
8843       // Re-evaluate the number of nodes to be traversed.
8844       e += 2; // 2 more nodes (LHS and RHS) are pushed.
8845       continue;
8846     }
8847
8848     // Quit if a non-EXTRACT_VECTOR_ELT
8849     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8850       return SDValue();
8851
8852     // Quit if without a constant index.
8853     SDValue Idx = I->getOperand(1);
8854     if (!isa<ConstantSDNode>(Idx))
8855       return SDValue();
8856
8857     SDValue ExtractedFromVec = I->getOperand(0);
8858     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
8859     if (M == VecInMap.end()) {
8860       VT = ExtractedFromVec.getValueType();
8861       // Quit if not 128/256-bit vector.
8862       if (!VT.is128BitVector() && !VT.is256BitVector())
8863         return SDValue();
8864       // Quit if not the same type.
8865       if (VecInMap.begin() != VecInMap.end() &&
8866           VT != VecInMap.begin()->first.getValueType())
8867         return SDValue();
8868       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
8869     }
8870     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
8871   }
8872
8873   assert((VT.is128BitVector() || VT.is256BitVector()) &&
8874          "Not extracted from 128-/256-bit vector.");
8875
8876   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
8877   SmallVector<SDValue, 8> VecIns;
8878
8879   for (DenseMap<SDValue, unsigned>::const_iterator
8880         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
8881     // Quit if not all elements are used.
8882     if (I->second != FullMask)
8883       return SDValue();
8884     VecIns.push_back(I->first);
8885   }
8886
8887   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
8888
8889   // Cast all vectors into TestVT for PTEST.
8890   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
8891     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
8892
8893   // If more than one full vectors are evaluated, OR them first before PTEST.
8894   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
8895     // Each iteration will OR 2 nodes and append the result until there is only
8896     // 1 node left, i.e. the final OR'd value of all vectors.
8897     SDValue LHS = VecIns[Slot];
8898     SDValue RHS = VecIns[Slot + 1];
8899     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
8900   }
8901
8902   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
8903                      VecIns.back(), VecIns.back());
8904 }
8905
8906 /// Emit nodes that will be selected as "test Op0,Op0", or something
8907 /// equivalent.
8908 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8909                                     SelectionDAG &DAG) const {
8910   SDLoc dl(Op);
8911
8912   // CF and OF aren't always set the way we want. Determine which
8913   // of these we need.
8914   bool NeedCF = false;
8915   bool NeedOF = false;
8916   switch (X86CC) {
8917   default: break;
8918   case X86::COND_A: case X86::COND_AE:
8919   case X86::COND_B: case X86::COND_BE:
8920     NeedCF = true;
8921     break;
8922   case X86::COND_G: case X86::COND_GE:
8923   case X86::COND_L: case X86::COND_LE:
8924   case X86::COND_O: case X86::COND_NO:
8925     NeedOF = true;
8926     break;
8927   }
8928
8929   // See if we can use the EFLAGS value from the operand instead of
8930   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8931   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8932   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8933     // Emit a CMP with 0, which is the TEST pattern.
8934     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8935                        DAG.getConstant(0, Op.getValueType()));
8936
8937   unsigned Opcode = 0;
8938   unsigned NumOperands = 0;
8939
8940   // Truncate operations may prevent the merge of the SETCC instruction
8941   // and the arithmetic intruction before it. Attempt to truncate the operands
8942   // of the arithmetic instruction and use a reduced bit-width instruction.
8943   bool NeedTruncation = false;
8944   SDValue ArithOp = Op;
8945   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
8946     SDValue Arith = Op->getOperand(0);
8947     // Both the trunc and the arithmetic op need to have one user each.
8948     if (Arith->hasOneUse())
8949       switch (Arith.getOpcode()) {
8950         default: break;
8951         case ISD::ADD:
8952         case ISD::SUB:
8953         case ISD::AND:
8954         case ISD::OR:
8955         case ISD::XOR: {
8956           NeedTruncation = true;
8957           ArithOp = Arith;
8958         }
8959       }
8960   }
8961
8962   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
8963   // which may be the result of a CAST.  We use the variable 'Op', which is the
8964   // non-casted variable when we check for possible users.
8965   switch (ArithOp.getOpcode()) {
8966   case ISD::ADD:
8967     // Due to an isel shortcoming, be conservative if this add is likely to be
8968     // selected as part of a load-modify-store instruction. When the root node
8969     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8970     // uses of other nodes in the match, such as the ADD in this case. This
8971     // leads to the ADD being left around and reselected, with the result being
8972     // two adds in the output.  Alas, even if none our users are stores, that
8973     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8974     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8975     // climbing the DAG back to the root, and it doesn't seem to be worth the
8976     // effort.
8977     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8978          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8979       if (UI->getOpcode() != ISD::CopyToReg &&
8980           UI->getOpcode() != ISD::SETCC &&
8981           UI->getOpcode() != ISD::STORE)
8982         goto default_case;
8983
8984     if (ConstantSDNode *C =
8985         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
8986       // An add of one will be selected as an INC.
8987       if (C->getAPIntValue() == 1) {
8988         Opcode = X86ISD::INC;
8989         NumOperands = 1;
8990         break;
8991       }
8992
8993       // An add of negative one (subtract of one) will be selected as a DEC.
8994       if (C->getAPIntValue().isAllOnesValue()) {
8995         Opcode = X86ISD::DEC;
8996         NumOperands = 1;
8997         break;
8998       }
8999     }
9000
9001     // Otherwise use a regular EFLAGS-setting add.
9002     Opcode = X86ISD::ADD;
9003     NumOperands = 2;
9004     break;
9005   case ISD::AND: {
9006     // If the primary and result isn't used, don't bother using X86ISD::AND,
9007     // because a TEST instruction will be better.
9008     bool NonFlagUse = false;
9009     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9010            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9011       SDNode *User = *UI;
9012       unsigned UOpNo = UI.getOperandNo();
9013       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
9014         // Look pass truncate.
9015         UOpNo = User->use_begin().getOperandNo();
9016         User = *User->use_begin();
9017       }
9018
9019       if (User->getOpcode() != ISD::BRCOND &&
9020           User->getOpcode() != ISD::SETCC &&
9021           !(User->getOpcode() == ISD::SELECT && UOpNo == 0)) {
9022         NonFlagUse = true;
9023         break;
9024       }
9025     }
9026
9027     if (!NonFlagUse)
9028       break;
9029   }
9030     // FALL THROUGH
9031   case ISD::SUB:
9032   case ISD::OR:
9033   case ISD::XOR:
9034     // Due to the ISEL shortcoming noted above, be conservative if this op is
9035     // likely to be selected as part of a load-modify-store instruction.
9036     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9037            UE = Op.getNode()->use_end(); UI != UE; ++UI)
9038       if (UI->getOpcode() == ISD::STORE)
9039         goto default_case;
9040
9041     // Otherwise use a regular EFLAGS-setting instruction.
9042     switch (ArithOp.getOpcode()) {
9043     default: llvm_unreachable("unexpected operator!");
9044     case ISD::SUB: Opcode = X86ISD::SUB; break;
9045     case ISD::XOR: Opcode = X86ISD::XOR; break;
9046     case ISD::AND: Opcode = X86ISD::AND; break;
9047     case ISD::OR: {
9048       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
9049         SDValue EFLAGS = LowerVectorAllZeroTest(Op, DAG);
9050         if (EFLAGS.getNode())
9051           return EFLAGS;
9052       }
9053       Opcode = X86ISD::OR;
9054       break;
9055     }
9056     }
9057
9058     NumOperands = 2;
9059     break;
9060   case X86ISD::ADD:
9061   case X86ISD::SUB:
9062   case X86ISD::INC:
9063   case X86ISD::DEC:
9064   case X86ISD::OR:
9065   case X86ISD::XOR:
9066   case X86ISD::AND:
9067     return SDValue(Op.getNode(), 1);
9068   default:
9069   default_case:
9070     break;
9071   }
9072
9073   // If we found that truncation is beneficial, perform the truncation and
9074   // update 'Op'.
9075   if (NeedTruncation) {
9076     EVT VT = Op.getValueType();
9077     SDValue WideVal = Op->getOperand(0);
9078     EVT WideVT = WideVal.getValueType();
9079     unsigned ConvertedOp = 0;
9080     // Use a target machine opcode to prevent further DAGCombine
9081     // optimizations that may separate the arithmetic operations
9082     // from the setcc node.
9083     switch (WideVal.getOpcode()) {
9084       default: break;
9085       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
9086       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
9087       case ISD::AND: ConvertedOp = X86ISD::AND; break;
9088       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
9089       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
9090     }
9091
9092     if (ConvertedOp) {
9093       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9094       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
9095         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
9096         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
9097         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
9098       }
9099     }
9100   }
9101
9102   if (Opcode == 0)
9103     // Emit a CMP with 0, which is the TEST pattern.
9104     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
9105                        DAG.getConstant(0, Op.getValueType()));
9106
9107   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
9108   SmallVector<SDValue, 4> Ops;
9109   for (unsigned i = 0; i != NumOperands; ++i)
9110     Ops.push_back(Op.getOperand(i));
9111
9112   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
9113   DAG.ReplaceAllUsesWith(Op, New);
9114   return SDValue(New.getNode(), 1);
9115 }
9116
9117 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
9118 /// equivalent.
9119 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
9120                                    SelectionDAG &DAG) const {
9121   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
9122     if (C->getAPIntValue() == 0)
9123       return EmitTest(Op0, X86CC, DAG);
9124
9125   SDLoc dl(Op0);
9126   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
9127        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
9128     // Use SUB instead of CMP to enable CSE between SUB and CMP.
9129     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
9130     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
9131                               Op0, Op1);
9132     return SDValue(Sub.getNode(), 1);
9133   }
9134   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
9135 }
9136
9137 /// Convert a comparison if required by the subtarget.
9138 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
9139                                                  SelectionDAG &DAG) const {
9140   // If the subtarget does not support the FUCOMI instruction, floating-point
9141   // comparisons have to be converted.
9142   if (Subtarget->hasCMov() ||
9143       Cmp.getOpcode() != X86ISD::CMP ||
9144       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
9145       !Cmp.getOperand(1).getValueType().isFloatingPoint())
9146     return Cmp;
9147
9148   // The instruction selector will select an FUCOM instruction instead of
9149   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
9150   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
9151   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
9152   SDLoc dl(Cmp);
9153   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
9154   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
9155   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
9156                             DAG.getConstant(8, MVT::i8));
9157   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
9158   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
9159 }
9160
9161 static bool isAllOnes(SDValue V) {
9162   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9163   return C && C->isAllOnesValue();
9164 }
9165
9166 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
9167 /// if it's possible.
9168 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
9169                                      SDLoc dl, SelectionDAG &DAG) const {
9170   SDValue Op0 = And.getOperand(0);
9171   SDValue Op1 = And.getOperand(1);
9172   if (Op0.getOpcode() == ISD::TRUNCATE)
9173     Op0 = Op0.getOperand(0);
9174   if (Op1.getOpcode() == ISD::TRUNCATE)
9175     Op1 = Op1.getOperand(0);
9176
9177   SDValue LHS, RHS;
9178   if (Op1.getOpcode() == ISD::SHL)
9179     std::swap(Op0, Op1);
9180   if (Op0.getOpcode() == ISD::SHL) {
9181     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
9182       if (And00C->getZExtValue() == 1) {
9183         // If we looked past a truncate, check that it's only truncating away
9184         // known zeros.
9185         unsigned BitWidth = Op0.getValueSizeInBits();
9186         unsigned AndBitWidth = And.getValueSizeInBits();
9187         if (BitWidth > AndBitWidth) {
9188           APInt Zeros, Ones;
9189           DAG.ComputeMaskedBits(Op0, Zeros, Ones);
9190           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
9191             return SDValue();
9192         }
9193         LHS = Op1;
9194         RHS = Op0.getOperand(1);
9195       }
9196   } else if (Op1.getOpcode() == ISD::Constant) {
9197     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
9198     uint64_t AndRHSVal = AndRHS->getZExtValue();
9199     SDValue AndLHS = Op0;
9200
9201     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
9202       LHS = AndLHS.getOperand(0);
9203       RHS = AndLHS.getOperand(1);
9204     }
9205
9206     // Use BT if the immediate can't be encoded in a TEST instruction.
9207     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
9208       LHS = AndLHS;
9209       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
9210     }
9211   }
9212
9213   if (LHS.getNode()) {
9214     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
9215     // instruction.  Since the shift amount is in-range-or-undefined, we know
9216     // that doing a bittest on the i32 value is ok.  We extend to i32 because
9217     // the encoding for the i16 version is larger than the i32 version.
9218     // Also promote i16 to i32 for performance / code size reason.
9219     if (LHS.getValueType() == MVT::i8 ||
9220         LHS.getValueType() == MVT::i16)
9221       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
9222
9223     // If the operand types disagree, extend the shift amount to match.  Since
9224     // BT ignores high bits (like shifts) we can use anyextend.
9225     if (LHS.getValueType() != RHS.getValueType())
9226       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
9227
9228     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
9229     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
9230     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9231                        DAG.getConstant(Cond, MVT::i8), BT);
9232   }
9233
9234   return SDValue();
9235 }
9236
9237 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
9238 // ones, and then concatenate the result back.
9239 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
9240   MVT VT = Op.getValueType().getSimpleVT();
9241
9242   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
9243          "Unsupported value type for operation");
9244
9245   unsigned NumElems = VT.getVectorNumElements();
9246   SDLoc dl(Op);
9247   SDValue CC = Op.getOperand(2);
9248
9249   // Extract the LHS vectors
9250   SDValue LHS = Op.getOperand(0);
9251   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
9252   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
9253
9254   // Extract the RHS vectors
9255   SDValue RHS = Op.getOperand(1);
9256   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
9257   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
9258
9259   // Issue the operation on the smaller types and concatenate the result back
9260   MVT EltVT = VT.getVectorElementType();
9261   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
9262   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9263                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
9264                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
9265 }
9266
9267 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
9268                            SelectionDAG &DAG) {
9269   SDValue Cond;
9270   SDValue Op0 = Op.getOperand(0);
9271   SDValue Op1 = Op.getOperand(1);
9272   SDValue CC = Op.getOperand(2);
9273   MVT VT = Op.getValueType().getSimpleVT();
9274   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
9275   bool isFP = Op.getOperand(1).getValueType().getSimpleVT().isFloatingPoint();
9276   SDLoc dl(Op);
9277
9278   if (isFP) {
9279 #ifndef NDEBUG
9280     MVT EltVT = Op0.getValueType().getVectorElementType().getSimpleVT();
9281     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
9282 #endif
9283
9284     unsigned SSECC;
9285     bool Swap = false;
9286
9287     // SSE Condition code mapping:
9288     //  0 - EQ
9289     //  1 - LT
9290     //  2 - LE
9291     //  3 - UNORD
9292     //  4 - NEQ
9293     //  5 - NLT
9294     //  6 - NLE
9295     //  7 - ORD
9296     switch (SetCCOpcode) {
9297     default: llvm_unreachable("Unexpected SETCC condition");
9298     case ISD::SETOEQ:
9299     case ISD::SETEQ:  SSECC = 0; break;
9300     case ISD::SETOGT:
9301     case ISD::SETGT: Swap = true; // Fallthrough
9302     case ISD::SETLT:
9303     case ISD::SETOLT: SSECC = 1; break;
9304     case ISD::SETOGE:
9305     case ISD::SETGE: Swap = true; // Fallthrough
9306     case ISD::SETLE:
9307     case ISD::SETOLE: SSECC = 2; break;
9308     case ISD::SETUO:  SSECC = 3; break;
9309     case ISD::SETUNE:
9310     case ISD::SETNE:  SSECC = 4; break;
9311     case ISD::SETULE: Swap = true; // Fallthrough
9312     case ISD::SETUGE: SSECC = 5; break;
9313     case ISD::SETULT: Swap = true; // Fallthrough
9314     case ISD::SETUGT: SSECC = 6; break;
9315     case ISD::SETO:   SSECC = 7; break;
9316     case ISD::SETUEQ:
9317     case ISD::SETONE: SSECC = 8; break;
9318     }
9319     if (Swap)
9320       std::swap(Op0, Op1);
9321
9322     // In the two special cases we can't handle, emit two comparisons.
9323     if (SSECC == 8) {
9324       unsigned CC0, CC1;
9325       unsigned CombineOpc;
9326       if (SetCCOpcode == ISD::SETUEQ) {
9327         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
9328       } else {
9329         assert(SetCCOpcode == ISD::SETONE);
9330         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
9331       }
9332
9333       SDValue Cmp0 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9334                                  DAG.getConstant(CC0, MVT::i8));
9335       SDValue Cmp1 = DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9336                                  DAG.getConstant(CC1, MVT::i8));
9337       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
9338     }
9339     // Handle all other FP comparisons here.
9340     return DAG.getNode(X86ISD::CMPP, dl, VT, Op0, Op1,
9341                        DAG.getConstant(SSECC, MVT::i8));
9342   }
9343
9344   // Break 256-bit integer vector compare into smaller ones.
9345   if (VT.is256BitVector() && !Subtarget->hasInt256())
9346     return Lower256IntVSETCC(Op, DAG);
9347
9348   // We are handling one of the integer comparisons here.  Since SSE only has
9349   // GT and EQ comparisons for integer, swapping operands and multiple
9350   // operations may be required for some comparisons.
9351   unsigned Opc;
9352   bool Swap = false, Invert = false, FlipSigns = false;
9353
9354   switch (SetCCOpcode) {
9355   default: llvm_unreachable("Unexpected SETCC condition");
9356   case ISD::SETNE:  Invert = true;
9357   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
9358   case ISD::SETLT:  Swap = true;
9359   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
9360   case ISD::SETGE:  Swap = true;
9361   case ISD::SETLE:  Opc = X86ISD::PCMPGT; Invert = true; break;
9362   case ISD::SETULT: Swap = true;
9363   case ISD::SETUGT: Opc = X86ISD::PCMPGT; FlipSigns = true; break;
9364   case ISD::SETUGE: Swap = true;
9365   case ISD::SETULE: Opc = X86ISD::PCMPGT; FlipSigns = true; Invert = true; break;
9366   }
9367   if (Swap)
9368     std::swap(Op0, Op1);
9369
9370   // Check that the operation in question is available (most are plain SSE2,
9371   // but PCMPGTQ and PCMPEQQ have different requirements).
9372   if (VT == MVT::v2i64) {
9373     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
9374       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
9375
9376       // First cast everything to the right type.
9377       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9378       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9379
9380       // Since SSE has no unsigned integer comparisons, we need to flip the sign
9381       // bits of the inputs before performing those operations. The lower
9382       // compare is always unsigned.
9383       SDValue SB;
9384       if (FlipSigns) {
9385         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
9386       } else {
9387         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
9388         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
9389         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
9390                          Sign, Zero, Sign, Zero);
9391       }
9392       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
9393       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
9394
9395       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
9396       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
9397       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
9398
9399       // Create masks for only the low parts/high parts of the 64 bit integers.
9400       const int MaskHi[] = { 1, 1, 3, 3 };
9401       const int MaskLo[] = { 0, 0, 2, 2 };
9402       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
9403       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
9404       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
9405
9406       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
9407       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
9408
9409       if (Invert)
9410         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9411
9412       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9413     }
9414
9415     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
9416       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
9417       // pcmpeqd + pshufd + pand.
9418       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
9419
9420       // First cast everything to the right type.
9421       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
9422       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
9423
9424       // Do the compare.
9425       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
9426
9427       // Make sure the lower and upper halves are both all-ones.
9428       const int Mask[] = { 1, 0, 3, 2 };
9429       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
9430       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
9431
9432       if (Invert)
9433         Result = DAG.getNOT(dl, Result, MVT::v4i32);
9434
9435       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9436     }
9437   }
9438
9439   // Since SSE has no unsigned integer comparisons, we need to flip the sign
9440   // bits of the inputs before performing those operations.
9441   if (FlipSigns) {
9442     EVT EltVT = VT.getVectorElementType();
9443     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
9444     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
9445     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
9446   }
9447
9448   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
9449
9450   // If the logical-not of the result is required, perform that now.
9451   if (Invert)
9452     Result = DAG.getNOT(dl, Result, VT);
9453
9454   return Result;
9455 }
9456
9457 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
9458
9459   MVT VT = Op.getValueType().getSimpleVT();
9460
9461   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
9462
9463   assert(VT == MVT::i8 && "SetCC type must be 8-bit integer");
9464   SDValue Op0 = Op.getOperand(0);
9465   SDValue Op1 = Op.getOperand(1);
9466   SDLoc dl(Op);
9467   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9468
9469   // Optimize to BT if possible.
9470   // Lower (X & (1 << N)) == 0 to BT(X, N).
9471   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
9472   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
9473   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
9474       Op1.getOpcode() == ISD::Constant &&
9475       cast<ConstantSDNode>(Op1)->isNullValue() &&
9476       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9477     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
9478     if (NewSetCC.getNode())
9479       return NewSetCC;
9480   }
9481
9482   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
9483   // these.
9484   if (Op1.getOpcode() == ISD::Constant &&
9485       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
9486        cast<ConstantSDNode>(Op1)->isNullValue()) &&
9487       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
9488
9489     // If the input is a setcc, then reuse the input setcc or use a new one with
9490     // the inverted condition.
9491     if (Op0.getOpcode() == X86ISD::SETCC) {
9492       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
9493       bool Invert = (CC == ISD::SETNE) ^
9494         cast<ConstantSDNode>(Op1)->isNullValue();
9495       if (!Invert) return Op0;
9496
9497       CCode = X86::GetOppositeBranchCondition(CCode);
9498       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9499                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
9500     }
9501   }
9502
9503   bool isFP = Op1.getValueType().getSimpleVT().isFloatingPoint();
9504   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
9505   if (X86CC == X86::COND_INVALID)
9506     return SDValue();
9507
9508   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
9509   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
9510   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9511                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
9512 }
9513
9514 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
9515 static bool isX86LogicalCmp(SDValue Op) {
9516   unsigned Opc = Op.getNode()->getOpcode();
9517   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
9518       Opc == X86ISD::SAHF)
9519     return true;
9520   if (Op.getResNo() == 1 &&
9521       (Opc == X86ISD::ADD ||
9522        Opc == X86ISD::SUB ||
9523        Opc == X86ISD::ADC ||
9524        Opc == X86ISD::SBB ||
9525        Opc == X86ISD::SMUL ||
9526        Opc == X86ISD::UMUL ||
9527        Opc == X86ISD::INC ||
9528        Opc == X86ISD::DEC ||
9529        Opc == X86ISD::OR ||
9530        Opc == X86ISD::XOR ||
9531        Opc == X86ISD::AND))
9532     return true;
9533
9534   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
9535     return true;
9536
9537   return false;
9538 }
9539
9540 static bool isZero(SDValue V) {
9541   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
9542   return C && C->isNullValue();
9543 }
9544
9545 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
9546   if (V.getOpcode() != ISD::TRUNCATE)
9547     return false;
9548
9549   SDValue VOp0 = V.getOperand(0);
9550   unsigned InBits = VOp0.getValueSizeInBits();
9551   unsigned Bits = V.getValueSizeInBits();
9552   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
9553 }
9554
9555 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
9556   bool addTest = true;
9557   SDValue Cond  = Op.getOperand(0);
9558   SDValue Op1 = Op.getOperand(1);
9559   SDValue Op2 = Op.getOperand(2);
9560   SDLoc DL(Op);
9561   SDValue CC;
9562
9563   if (Cond.getOpcode() == ISD::SETCC) {
9564     SDValue NewCond = LowerSETCC(Cond, DAG);
9565     if (NewCond.getNode())
9566       Cond = NewCond;
9567   }
9568
9569   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
9570   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
9571   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
9572   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
9573   if (Cond.getOpcode() == X86ISD::SETCC &&
9574       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
9575       isZero(Cond.getOperand(1).getOperand(1))) {
9576     SDValue Cmp = Cond.getOperand(1);
9577
9578     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
9579
9580     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
9581         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
9582       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
9583
9584       SDValue CmpOp0 = Cmp.getOperand(0);
9585       // Apply further optimizations for special cases
9586       // (select (x != 0), -1, 0) -> neg & sbb
9587       // (select (x == 0), 0, -1) -> neg & sbb
9588       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
9589         if (YC->isNullValue() &&
9590             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
9591           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
9592           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
9593                                     DAG.getConstant(0, CmpOp0.getValueType()),
9594                                     CmpOp0);
9595           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9596                                     DAG.getConstant(X86::COND_B, MVT::i8),
9597                                     SDValue(Neg.getNode(), 1));
9598           return Res;
9599         }
9600
9601       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
9602                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
9603       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
9604
9605       SDValue Res =   // Res = 0 or -1.
9606         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9607                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
9608
9609       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
9610         Res = DAG.getNOT(DL, Res, Res.getValueType());
9611
9612       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
9613       if (N2C == 0 || !N2C->isNullValue())
9614         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
9615       return Res;
9616     }
9617   }
9618
9619   // Look past (and (setcc_carry (cmp ...)), 1).
9620   if (Cond.getOpcode() == ISD::AND &&
9621       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9622     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9623     if (C && C->getAPIntValue() == 1)
9624       Cond = Cond.getOperand(0);
9625   }
9626
9627   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9628   // setting operand in place of the X86ISD::SETCC.
9629   unsigned CondOpcode = Cond.getOpcode();
9630   if (CondOpcode == X86ISD::SETCC ||
9631       CondOpcode == X86ISD::SETCC_CARRY) {
9632     CC = Cond.getOperand(0);
9633
9634     SDValue Cmp = Cond.getOperand(1);
9635     unsigned Opc = Cmp.getOpcode();
9636     MVT VT = Op.getValueType().getSimpleVT();
9637
9638     bool IllegalFPCMov = false;
9639     if (VT.isFloatingPoint() && !VT.isVector() &&
9640         !isScalarFPTypeInSSEReg(VT))  // FPStack?
9641       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
9642
9643     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
9644         Opc == X86ISD::BT) { // FIXME
9645       Cond = Cmp;
9646       addTest = false;
9647     }
9648   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9649              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9650              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9651               Cond.getOperand(0).getValueType() != MVT::i8)) {
9652     SDValue LHS = Cond.getOperand(0);
9653     SDValue RHS = Cond.getOperand(1);
9654     unsigned X86Opcode;
9655     unsigned X86Cond;
9656     SDVTList VTs;
9657     switch (CondOpcode) {
9658     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9659     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9660     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9661     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9662     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9663     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9664     default: llvm_unreachable("unexpected overflowing operator");
9665     }
9666     if (CondOpcode == ISD::UMULO)
9667       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9668                           MVT::i32);
9669     else
9670       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9671
9672     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
9673
9674     if (CondOpcode == ISD::UMULO)
9675       Cond = X86Op.getValue(2);
9676     else
9677       Cond = X86Op.getValue(1);
9678
9679     CC = DAG.getConstant(X86Cond, MVT::i8);
9680     addTest = false;
9681   }
9682
9683   if (addTest) {
9684     // Look pass the truncate if the high bits are known zero.
9685     if (isTruncWithZeroHighBitsInput(Cond, DAG))
9686         Cond = Cond.getOperand(0);
9687
9688     // We know the result of AND is compared against zero. Try to match
9689     // it to BT.
9690     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9691       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
9692       if (NewSetCC.getNode()) {
9693         CC = NewSetCC.getOperand(0);
9694         Cond = NewSetCC.getOperand(1);
9695         addTest = false;
9696       }
9697     }
9698   }
9699
9700   if (addTest) {
9701     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9702     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9703   }
9704
9705   // a <  b ? -1 :  0 -> RES = ~setcc_carry
9706   // a <  b ?  0 : -1 -> RES = setcc_carry
9707   // a >= b ? -1 :  0 -> RES = setcc_carry
9708   // a >= b ?  0 : -1 -> RES = ~setcc_carry
9709   if (Cond.getOpcode() == X86ISD::SUB) {
9710     Cond = ConvertCmpIfNecessary(Cond, DAG);
9711     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
9712
9713     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
9714         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
9715       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
9716                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
9717       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
9718         return DAG.getNOT(DL, Res, Res.getValueType());
9719       return Res;
9720     }
9721   }
9722
9723   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
9724   // widen the cmov and push the truncate through. This avoids introducing a new
9725   // branch during isel and doesn't add any extensions.
9726   if (Op.getValueType() == MVT::i8 &&
9727       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
9728     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
9729     if (T1.getValueType() == T2.getValueType() &&
9730         // Blacklist CopyFromReg to avoid partial register stalls.
9731         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
9732       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
9733       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
9734       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
9735     }
9736   }
9737
9738   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
9739   // condition is true.
9740   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
9741   SDValue Ops[] = { Op2, Op1, CC, Cond };
9742   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
9743 }
9744
9745 SDValue X86TargetLowering::LowerSIGN_EXTEND(SDValue Op,
9746                                             SelectionDAG &DAG) const {
9747   MVT VT = Op->getValueType(0).getSimpleVT();
9748   SDValue In = Op->getOperand(0);
9749   MVT InVT = In.getValueType().getSimpleVT();
9750   SDLoc dl(Op);
9751
9752   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
9753       (VT != MVT::v8i32 || InVT != MVT::v8i16))
9754     return SDValue();
9755
9756   if (Subtarget->hasInt256())
9757     return DAG.getNode(X86ISD::VSEXT_MOVL, dl, VT, In);
9758
9759   // Optimize vectors in AVX mode
9760   // Sign extend  v8i16 to v8i32 and
9761   //              v4i32 to v4i64
9762   //
9763   // Divide input vector into two parts
9764   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
9765   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
9766   // concat the vectors to original VT
9767
9768   unsigned NumElems = InVT.getVectorNumElements();
9769   SDValue Undef = DAG.getUNDEF(InVT);
9770
9771   SmallVector<int,8> ShufMask1(NumElems, -1);
9772   for (unsigned i = 0; i != NumElems/2; ++i)
9773     ShufMask1[i] = i;
9774
9775   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
9776
9777   SmallVector<int,8> ShufMask2(NumElems, -1);
9778   for (unsigned i = 0; i != NumElems/2; ++i)
9779     ShufMask2[i] = i + NumElems/2;
9780
9781   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
9782
9783   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
9784                                 VT.getVectorNumElements()/2);
9785
9786   OpLo = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpLo);
9787   OpHi = DAG.getNode(X86ISD::VSEXT_MOVL, dl, HalfVT, OpHi);
9788
9789   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9790 }
9791
9792 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
9793 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
9794 // from the AND / OR.
9795 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
9796   Opc = Op.getOpcode();
9797   if (Opc != ISD::OR && Opc != ISD::AND)
9798     return false;
9799   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9800           Op.getOperand(0).hasOneUse() &&
9801           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
9802           Op.getOperand(1).hasOneUse());
9803 }
9804
9805 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
9806 // 1 and that the SETCC node has a single use.
9807 static bool isXor1OfSetCC(SDValue Op) {
9808   if (Op.getOpcode() != ISD::XOR)
9809     return false;
9810   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9811   if (N1C && N1C->getAPIntValue() == 1) {
9812     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
9813       Op.getOperand(0).hasOneUse();
9814   }
9815   return false;
9816 }
9817
9818 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
9819   bool addTest = true;
9820   SDValue Chain = Op.getOperand(0);
9821   SDValue Cond  = Op.getOperand(1);
9822   SDValue Dest  = Op.getOperand(2);
9823   SDLoc dl(Op);
9824   SDValue CC;
9825   bool Inverted = false;
9826
9827   if (Cond.getOpcode() == ISD::SETCC) {
9828     // Check for setcc([su]{add,sub,mul}o == 0).
9829     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9830         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9831         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9832         Cond.getOperand(0).getResNo() == 1 &&
9833         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9834          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9835          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9836          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9837          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9838          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9839       Inverted = true;
9840       Cond = Cond.getOperand(0);
9841     } else {
9842       SDValue NewCond = LowerSETCC(Cond, DAG);
9843       if (NewCond.getNode())
9844         Cond = NewCond;
9845     }
9846   }
9847 #if 0
9848   // FIXME: LowerXALUO doesn't handle these!!
9849   else if (Cond.getOpcode() == X86ISD::ADD  ||
9850            Cond.getOpcode() == X86ISD::SUB  ||
9851            Cond.getOpcode() == X86ISD::SMUL ||
9852            Cond.getOpcode() == X86ISD::UMUL)
9853     Cond = LowerXALUO(Cond, DAG);
9854 #endif
9855
9856   // Look pass (and (setcc_carry (cmp ...)), 1).
9857   if (Cond.getOpcode() == ISD::AND &&
9858       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9859     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9860     if (C && C->getAPIntValue() == 1)
9861       Cond = Cond.getOperand(0);
9862   }
9863
9864   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9865   // setting operand in place of the X86ISD::SETCC.
9866   unsigned CondOpcode = Cond.getOpcode();
9867   if (CondOpcode == X86ISD::SETCC ||
9868       CondOpcode == X86ISD::SETCC_CARRY) {
9869     CC = Cond.getOperand(0);
9870
9871     SDValue Cmp = Cond.getOperand(1);
9872     unsigned Opc = Cmp.getOpcode();
9873     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9874     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9875       Cond = Cmp;
9876       addTest = false;
9877     } else {
9878       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9879       default: break;
9880       case X86::COND_O:
9881       case X86::COND_B:
9882         // These can only come from an arithmetic instruction with overflow,
9883         // e.g. SADDO, UADDO.
9884         Cond = Cond.getNode()->getOperand(1);
9885         addTest = false;
9886         break;
9887       }
9888     }
9889   }
9890   CondOpcode = Cond.getOpcode();
9891   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9892       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9893       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9894        Cond.getOperand(0).getValueType() != MVT::i8)) {
9895     SDValue LHS = Cond.getOperand(0);
9896     SDValue RHS = Cond.getOperand(1);
9897     unsigned X86Opcode;
9898     unsigned X86Cond;
9899     SDVTList VTs;
9900     switch (CondOpcode) {
9901     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9902     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9903     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9904     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9905     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9906     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9907     default: llvm_unreachable("unexpected overflowing operator");
9908     }
9909     if (Inverted)
9910       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9911     if (CondOpcode == ISD::UMULO)
9912       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9913                           MVT::i32);
9914     else
9915       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9916
9917     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9918
9919     if (CondOpcode == ISD::UMULO)
9920       Cond = X86Op.getValue(2);
9921     else
9922       Cond = X86Op.getValue(1);
9923
9924     CC = DAG.getConstant(X86Cond, MVT::i8);
9925     addTest = false;
9926   } else {
9927     unsigned CondOpc;
9928     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9929       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9930       if (CondOpc == ISD::OR) {
9931         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9932         // two branches instead of an explicit OR instruction with a
9933         // separate test.
9934         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9935             isX86LogicalCmp(Cmp)) {
9936           CC = Cond.getOperand(0).getOperand(0);
9937           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9938                               Chain, Dest, CC, Cmp);
9939           CC = Cond.getOperand(1).getOperand(0);
9940           Cond = Cmp;
9941           addTest = false;
9942         }
9943       } else { // ISD::AND
9944         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9945         // two branches instead of an explicit AND instruction with a
9946         // separate test. However, we only do this if this block doesn't
9947         // have a fall-through edge, because this requires an explicit
9948         // jmp when the condition is false.
9949         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9950             isX86LogicalCmp(Cmp) &&
9951             Op.getNode()->hasOneUse()) {
9952           X86::CondCode CCode =
9953             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9954           CCode = X86::GetOppositeBranchCondition(CCode);
9955           CC = DAG.getConstant(CCode, MVT::i8);
9956           SDNode *User = *Op.getNode()->use_begin();
9957           // Look for an unconditional branch following this conditional branch.
9958           // We need this because we need to reverse the successors in order
9959           // to implement FCMP_OEQ.
9960           if (User->getOpcode() == ISD::BR) {
9961             SDValue FalseBB = User->getOperand(1);
9962             SDNode *NewBR =
9963               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9964             assert(NewBR == User);
9965             (void)NewBR;
9966             Dest = FalseBB;
9967
9968             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9969                                 Chain, Dest, CC, Cmp);
9970             X86::CondCode CCode =
9971               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9972             CCode = X86::GetOppositeBranchCondition(CCode);
9973             CC = DAG.getConstant(CCode, MVT::i8);
9974             Cond = Cmp;
9975             addTest = false;
9976           }
9977         }
9978       }
9979     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9980       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9981       // It should be transformed during dag combiner except when the condition
9982       // is set by a arithmetics with overflow node.
9983       X86::CondCode CCode =
9984         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9985       CCode = X86::GetOppositeBranchCondition(CCode);
9986       CC = DAG.getConstant(CCode, MVT::i8);
9987       Cond = Cond.getOperand(0).getOperand(1);
9988       addTest = false;
9989     } else if (Cond.getOpcode() == ISD::SETCC &&
9990                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9991       // For FCMP_OEQ, we can emit
9992       // two branches instead of an explicit AND instruction with a
9993       // separate test. However, we only do this if this block doesn't
9994       // have a fall-through edge, because this requires an explicit
9995       // jmp when the condition is false.
9996       if (Op.getNode()->hasOneUse()) {
9997         SDNode *User = *Op.getNode()->use_begin();
9998         // Look for an unconditional branch following this conditional branch.
9999         // We need this because we need to reverse the successors in order
10000         // to implement FCMP_OEQ.
10001         if (User->getOpcode() == ISD::BR) {
10002           SDValue FalseBB = User->getOperand(1);
10003           SDNode *NewBR =
10004             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10005           assert(NewBR == User);
10006           (void)NewBR;
10007           Dest = FalseBB;
10008
10009           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10010                                     Cond.getOperand(0), Cond.getOperand(1));
10011           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10012           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10013           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10014                               Chain, Dest, CC, Cmp);
10015           CC = DAG.getConstant(X86::COND_P, MVT::i8);
10016           Cond = Cmp;
10017           addTest = false;
10018         }
10019       }
10020     } else if (Cond.getOpcode() == ISD::SETCC &&
10021                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
10022       // For FCMP_UNE, we can emit
10023       // two branches instead of an explicit AND instruction with a
10024       // separate test. However, we only do this if this block doesn't
10025       // have a fall-through edge, because this requires an explicit
10026       // jmp when the condition is false.
10027       if (Op.getNode()->hasOneUse()) {
10028         SDNode *User = *Op.getNode()->use_begin();
10029         // Look for an unconditional branch following this conditional branch.
10030         // We need this because we need to reverse the successors in order
10031         // to implement FCMP_UNE.
10032         if (User->getOpcode() == ISD::BR) {
10033           SDValue FalseBB = User->getOperand(1);
10034           SDNode *NewBR =
10035             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
10036           assert(NewBR == User);
10037           (void)NewBR;
10038
10039           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10040                                     Cond.getOperand(0), Cond.getOperand(1));
10041           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10042           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10043           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10044                               Chain, Dest, CC, Cmp);
10045           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
10046           Cond = Cmp;
10047           addTest = false;
10048           Dest = FalseBB;
10049         }
10050       }
10051     }
10052   }
10053
10054   if (addTest) {
10055     // Look pass the truncate if the high bits are known zero.
10056     if (isTruncWithZeroHighBitsInput(Cond, DAG))
10057         Cond = Cond.getOperand(0);
10058
10059     // We know the result of AND is compared against zero. Try to match
10060     // it to BT.
10061     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
10062       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
10063       if (NewSetCC.getNode()) {
10064         CC = NewSetCC.getOperand(0);
10065         Cond = NewSetCC.getOperand(1);
10066         addTest = false;
10067       }
10068     }
10069   }
10070
10071   if (addTest) {
10072     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10073     Cond = EmitTest(Cond, X86::COND_NE, DAG);
10074   }
10075   Cond = ConvertCmpIfNecessary(Cond, DAG);
10076   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
10077                      Chain, Dest, CC, Cond);
10078 }
10079
10080 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
10081 // Calls to _alloca is needed to probe the stack when allocating more than 4k
10082 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
10083 // that the guard pages used by the OS virtual memory manager are allocated in
10084 // correct sequence.
10085 SDValue
10086 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
10087                                            SelectionDAG &DAG) const {
10088   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
10089           getTargetMachine().Options.EnableSegmentedStacks) &&
10090          "This should be used only on Windows targets or when segmented stacks "
10091          "are being used");
10092   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
10093   SDLoc dl(Op);
10094
10095   // Get the inputs.
10096   SDValue Chain = Op.getOperand(0);
10097   SDValue Size  = Op.getOperand(1);
10098   // FIXME: Ensure alignment here
10099
10100   bool Is64Bit = Subtarget->is64Bit();
10101   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
10102
10103   if (getTargetMachine().Options.EnableSegmentedStacks) {
10104     MachineFunction &MF = DAG.getMachineFunction();
10105     MachineRegisterInfo &MRI = MF.getRegInfo();
10106
10107     if (Is64Bit) {
10108       // The 64 bit implementation of segmented stacks needs to clobber both r10
10109       // r11. This makes it impossible to use it along with nested parameters.
10110       const Function *F = MF.getFunction();
10111
10112       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
10113            I != E; ++I)
10114         if (I->hasNestAttr())
10115           report_fatal_error("Cannot use segmented stacks with functions that "
10116                              "have nested arguments.");
10117     }
10118
10119     const TargetRegisterClass *AddrRegClass =
10120       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
10121     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
10122     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
10123     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
10124                                 DAG.getRegister(Vreg, SPTy));
10125     SDValue Ops1[2] = { Value, Chain };
10126     return DAG.getMergeValues(Ops1, 2, dl);
10127   } else {
10128     SDValue Flag;
10129     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
10130
10131     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
10132     Flag = Chain.getValue(1);
10133     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10134
10135     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
10136     Flag = Chain.getValue(1);
10137
10138     const X86RegisterInfo *RegInfo =
10139       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
10140     Chain = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
10141                                SPTy).getValue(1);
10142
10143     SDValue Ops1[2] = { Chain.getValue(0), Chain };
10144     return DAG.getMergeValues(Ops1, 2, dl);
10145   }
10146 }
10147
10148 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
10149   MachineFunction &MF = DAG.getMachineFunction();
10150   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
10151
10152   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10153   SDLoc DL(Op);
10154
10155   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
10156     // vastart just stores the address of the VarArgsFrameIndex slot into the
10157     // memory location argument.
10158     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10159                                    getPointerTy());
10160     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
10161                         MachinePointerInfo(SV), false, false, 0);
10162   }
10163
10164   // __va_list_tag:
10165   //   gp_offset         (0 - 6 * 8)
10166   //   fp_offset         (48 - 48 + 8 * 16)
10167   //   overflow_arg_area (point to parameters coming in memory).
10168   //   reg_save_area
10169   SmallVector<SDValue, 8> MemOps;
10170   SDValue FIN = Op.getOperand(1);
10171   // Store gp_offset
10172   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
10173                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
10174                                                MVT::i32),
10175                                FIN, MachinePointerInfo(SV), false, false, 0);
10176   MemOps.push_back(Store);
10177
10178   // Store fp_offset
10179   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10180                     FIN, DAG.getIntPtrConstant(4));
10181   Store = DAG.getStore(Op.getOperand(0), DL,
10182                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
10183                                        MVT::i32),
10184                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
10185   MemOps.push_back(Store);
10186
10187   // Store ptr to overflow_arg_area
10188   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10189                     FIN, DAG.getIntPtrConstant(4));
10190   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
10191                                     getPointerTy());
10192   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
10193                        MachinePointerInfo(SV, 8),
10194                        false, false, 0);
10195   MemOps.push_back(Store);
10196
10197   // Store ptr to reg_save_area.
10198   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10199                     FIN, DAG.getIntPtrConstant(8));
10200   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
10201                                     getPointerTy());
10202   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
10203                        MachinePointerInfo(SV, 16), false, false, 0);
10204   MemOps.push_back(Store);
10205   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
10206                      &MemOps[0], MemOps.size());
10207 }
10208
10209 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
10210   assert(Subtarget->is64Bit() &&
10211          "LowerVAARG only handles 64-bit va_arg!");
10212   assert((Subtarget->isTargetLinux() ||
10213           Subtarget->isTargetDarwin()) &&
10214           "Unhandled target in LowerVAARG");
10215   assert(Op.getNode()->getNumOperands() == 4);
10216   SDValue Chain = Op.getOperand(0);
10217   SDValue SrcPtr = Op.getOperand(1);
10218   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
10219   unsigned Align = Op.getConstantOperandVal(3);
10220   SDLoc dl(Op);
10221
10222   EVT ArgVT = Op.getNode()->getValueType(0);
10223   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10224   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
10225   uint8_t ArgMode;
10226
10227   // Decide which area this value should be read from.
10228   // TODO: Implement the AMD64 ABI in its entirety. This simple
10229   // selection mechanism works only for the basic types.
10230   if (ArgVT == MVT::f80) {
10231     llvm_unreachable("va_arg for f80 not yet implemented");
10232   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
10233     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
10234   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
10235     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
10236   } else {
10237     llvm_unreachable("Unhandled argument type in LowerVAARG");
10238   }
10239
10240   if (ArgMode == 2) {
10241     // Sanity Check: Make sure using fp_offset makes sense.
10242     assert(!getTargetMachine().Options.UseSoftFloat &&
10243            !(DAG.getMachineFunction()
10244                 .getFunction()->getAttributes()
10245                 .hasAttribute(AttributeSet::FunctionIndex,
10246                               Attribute::NoImplicitFloat)) &&
10247            Subtarget->hasSSE1());
10248   }
10249
10250   // Insert VAARG_64 node into the DAG
10251   // VAARG_64 returns two values: Variable Argument Address, Chain
10252   SmallVector<SDValue, 11> InstOps;
10253   InstOps.push_back(Chain);
10254   InstOps.push_back(SrcPtr);
10255   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
10256   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
10257   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
10258   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
10259   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
10260                                           VTs, &InstOps[0], InstOps.size(),
10261                                           MVT::i64,
10262                                           MachinePointerInfo(SV),
10263                                           /*Align=*/0,
10264                                           /*Volatile=*/false,
10265                                           /*ReadMem=*/true,
10266                                           /*WriteMem=*/true);
10267   Chain = VAARG.getValue(1);
10268
10269   // Load the next argument and return it
10270   return DAG.getLoad(ArgVT, dl,
10271                      Chain,
10272                      VAARG,
10273                      MachinePointerInfo(),
10274                      false, false, false, 0);
10275 }
10276
10277 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
10278                            SelectionDAG &DAG) {
10279   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
10280   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
10281   SDValue Chain = Op.getOperand(0);
10282   SDValue DstPtr = Op.getOperand(1);
10283   SDValue SrcPtr = Op.getOperand(2);
10284   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
10285   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
10286   SDLoc DL(Op);
10287
10288   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
10289                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
10290                        false,
10291                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
10292 }
10293
10294 // getTargetVShiftNode - Handle vector element shifts where the shift amount
10295 // may or may not be a constant. Takes immediate version of shift as input.
10296 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, EVT VT,
10297                                    SDValue SrcOp, SDValue ShAmt,
10298                                    SelectionDAG &DAG) {
10299   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
10300
10301   if (isa<ConstantSDNode>(ShAmt)) {
10302     // Constant may be a TargetConstant. Use a regular constant.
10303     uint32_t ShiftAmt = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10304     switch (Opc) {
10305       default: llvm_unreachable("Unknown target vector shift node");
10306       case X86ISD::VSHLI:
10307       case X86ISD::VSRLI:
10308       case X86ISD::VSRAI:
10309         return DAG.getNode(Opc, dl, VT, SrcOp,
10310                            DAG.getConstant(ShiftAmt, MVT::i32));
10311     }
10312   }
10313
10314   // Change opcode to non-immediate version
10315   switch (Opc) {
10316     default: llvm_unreachable("Unknown target vector shift node");
10317     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
10318     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
10319     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
10320   }
10321
10322   // Need to build a vector containing shift amount
10323   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
10324   SDValue ShOps[4];
10325   ShOps[0] = ShAmt;
10326   ShOps[1] = DAG.getConstant(0, MVT::i32);
10327   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
10328   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, &ShOps[0], 4);
10329
10330   // The return type has to be a 128-bit type with the same element
10331   // type as the input type.
10332   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10333   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
10334
10335   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
10336   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
10337 }
10338
10339 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
10340   SDLoc dl(Op);
10341   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10342   switch (IntNo) {
10343   default: return SDValue();    // Don't custom lower most intrinsics.
10344   // Comparison intrinsics.
10345   case Intrinsic::x86_sse_comieq_ss:
10346   case Intrinsic::x86_sse_comilt_ss:
10347   case Intrinsic::x86_sse_comile_ss:
10348   case Intrinsic::x86_sse_comigt_ss:
10349   case Intrinsic::x86_sse_comige_ss:
10350   case Intrinsic::x86_sse_comineq_ss:
10351   case Intrinsic::x86_sse_ucomieq_ss:
10352   case Intrinsic::x86_sse_ucomilt_ss:
10353   case Intrinsic::x86_sse_ucomile_ss:
10354   case Intrinsic::x86_sse_ucomigt_ss:
10355   case Intrinsic::x86_sse_ucomige_ss:
10356   case Intrinsic::x86_sse_ucomineq_ss:
10357   case Intrinsic::x86_sse2_comieq_sd:
10358   case Intrinsic::x86_sse2_comilt_sd:
10359   case Intrinsic::x86_sse2_comile_sd:
10360   case Intrinsic::x86_sse2_comigt_sd:
10361   case Intrinsic::x86_sse2_comige_sd:
10362   case Intrinsic::x86_sse2_comineq_sd:
10363   case Intrinsic::x86_sse2_ucomieq_sd:
10364   case Intrinsic::x86_sse2_ucomilt_sd:
10365   case Intrinsic::x86_sse2_ucomile_sd:
10366   case Intrinsic::x86_sse2_ucomigt_sd:
10367   case Intrinsic::x86_sse2_ucomige_sd:
10368   case Intrinsic::x86_sse2_ucomineq_sd: {
10369     unsigned Opc;
10370     ISD::CondCode CC;
10371     switch (IntNo) {
10372     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10373     case Intrinsic::x86_sse_comieq_ss:
10374     case Intrinsic::x86_sse2_comieq_sd:
10375       Opc = X86ISD::COMI;
10376       CC = ISD::SETEQ;
10377       break;
10378     case Intrinsic::x86_sse_comilt_ss:
10379     case Intrinsic::x86_sse2_comilt_sd:
10380       Opc = X86ISD::COMI;
10381       CC = ISD::SETLT;
10382       break;
10383     case Intrinsic::x86_sse_comile_ss:
10384     case Intrinsic::x86_sse2_comile_sd:
10385       Opc = X86ISD::COMI;
10386       CC = ISD::SETLE;
10387       break;
10388     case Intrinsic::x86_sse_comigt_ss:
10389     case Intrinsic::x86_sse2_comigt_sd:
10390       Opc = X86ISD::COMI;
10391       CC = ISD::SETGT;
10392       break;
10393     case Intrinsic::x86_sse_comige_ss:
10394     case Intrinsic::x86_sse2_comige_sd:
10395       Opc = X86ISD::COMI;
10396       CC = ISD::SETGE;
10397       break;
10398     case Intrinsic::x86_sse_comineq_ss:
10399     case Intrinsic::x86_sse2_comineq_sd:
10400       Opc = X86ISD::COMI;
10401       CC = ISD::SETNE;
10402       break;
10403     case Intrinsic::x86_sse_ucomieq_ss:
10404     case Intrinsic::x86_sse2_ucomieq_sd:
10405       Opc = X86ISD::UCOMI;
10406       CC = ISD::SETEQ;
10407       break;
10408     case Intrinsic::x86_sse_ucomilt_ss:
10409     case Intrinsic::x86_sse2_ucomilt_sd:
10410       Opc = X86ISD::UCOMI;
10411       CC = ISD::SETLT;
10412       break;
10413     case Intrinsic::x86_sse_ucomile_ss:
10414     case Intrinsic::x86_sse2_ucomile_sd:
10415       Opc = X86ISD::UCOMI;
10416       CC = ISD::SETLE;
10417       break;
10418     case Intrinsic::x86_sse_ucomigt_ss:
10419     case Intrinsic::x86_sse2_ucomigt_sd:
10420       Opc = X86ISD::UCOMI;
10421       CC = ISD::SETGT;
10422       break;
10423     case Intrinsic::x86_sse_ucomige_ss:
10424     case Intrinsic::x86_sse2_ucomige_sd:
10425       Opc = X86ISD::UCOMI;
10426       CC = ISD::SETGE;
10427       break;
10428     case Intrinsic::x86_sse_ucomineq_ss:
10429     case Intrinsic::x86_sse2_ucomineq_sd:
10430       Opc = X86ISD::UCOMI;
10431       CC = ISD::SETNE;
10432       break;
10433     }
10434
10435     SDValue LHS = Op.getOperand(1);
10436     SDValue RHS = Op.getOperand(2);
10437     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
10438     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
10439     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
10440     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10441                                 DAG.getConstant(X86CC, MVT::i8), Cond);
10442     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10443   }
10444
10445   // Arithmetic intrinsics.
10446   case Intrinsic::x86_sse2_pmulu_dq:
10447   case Intrinsic::x86_avx2_pmulu_dq:
10448     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
10449                        Op.getOperand(1), Op.getOperand(2));
10450
10451   // SSE2/AVX2 sub with unsigned saturation intrinsics
10452   case Intrinsic::x86_sse2_psubus_b:
10453   case Intrinsic::x86_sse2_psubus_w:
10454   case Intrinsic::x86_avx2_psubus_b:
10455   case Intrinsic::x86_avx2_psubus_w:
10456     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
10457                        Op.getOperand(1), Op.getOperand(2));
10458
10459   // SSE3/AVX horizontal add/sub intrinsics
10460   case Intrinsic::x86_sse3_hadd_ps:
10461   case Intrinsic::x86_sse3_hadd_pd:
10462   case Intrinsic::x86_avx_hadd_ps_256:
10463   case Intrinsic::x86_avx_hadd_pd_256:
10464   case Intrinsic::x86_sse3_hsub_ps:
10465   case Intrinsic::x86_sse3_hsub_pd:
10466   case Intrinsic::x86_avx_hsub_ps_256:
10467   case Intrinsic::x86_avx_hsub_pd_256:
10468   case Intrinsic::x86_ssse3_phadd_w_128:
10469   case Intrinsic::x86_ssse3_phadd_d_128:
10470   case Intrinsic::x86_avx2_phadd_w:
10471   case Intrinsic::x86_avx2_phadd_d:
10472   case Intrinsic::x86_ssse3_phsub_w_128:
10473   case Intrinsic::x86_ssse3_phsub_d_128:
10474   case Intrinsic::x86_avx2_phsub_w:
10475   case Intrinsic::x86_avx2_phsub_d: {
10476     unsigned Opcode;
10477     switch (IntNo) {
10478     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10479     case Intrinsic::x86_sse3_hadd_ps:
10480     case Intrinsic::x86_sse3_hadd_pd:
10481     case Intrinsic::x86_avx_hadd_ps_256:
10482     case Intrinsic::x86_avx_hadd_pd_256:
10483       Opcode = X86ISD::FHADD;
10484       break;
10485     case Intrinsic::x86_sse3_hsub_ps:
10486     case Intrinsic::x86_sse3_hsub_pd:
10487     case Intrinsic::x86_avx_hsub_ps_256:
10488     case Intrinsic::x86_avx_hsub_pd_256:
10489       Opcode = X86ISD::FHSUB;
10490       break;
10491     case Intrinsic::x86_ssse3_phadd_w_128:
10492     case Intrinsic::x86_ssse3_phadd_d_128:
10493     case Intrinsic::x86_avx2_phadd_w:
10494     case Intrinsic::x86_avx2_phadd_d:
10495       Opcode = X86ISD::HADD;
10496       break;
10497     case Intrinsic::x86_ssse3_phsub_w_128:
10498     case Intrinsic::x86_ssse3_phsub_d_128:
10499     case Intrinsic::x86_avx2_phsub_w:
10500     case Intrinsic::x86_avx2_phsub_d:
10501       Opcode = X86ISD::HSUB;
10502       break;
10503     }
10504     return DAG.getNode(Opcode, dl, Op.getValueType(),
10505                        Op.getOperand(1), Op.getOperand(2));
10506   }
10507
10508   // SSE2/SSE41/AVX2 integer max/min intrinsics.
10509   case Intrinsic::x86_sse2_pmaxu_b:
10510   case Intrinsic::x86_sse41_pmaxuw:
10511   case Intrinsic::x86_sse41_pmaxud:
10512   case Intrinsic::x86_avx2_pmaxu_b:
10513   case Intrinsic::x86_avx2_pmaxu_w:
10514   case Intrinsic::x86_avx2_pmaxu_d:
10515   case Intrinsic::x86_sse2_pminu_b:
10516   case Intrinsic::x86_sse41_pminuw:
10517   case Intrinsic::x86_sse41_pminud:
10518   case Intrinsic::x86_avx2_pminu_b:
10519   case Intrinsic::x86_avx2_pminu_w:
10520   case Intrinsic::x86_avx2_pminu_d:
10521   case Intrinsic::x86_sse41_pmaxsb:
10522   case Intrinsic::x86_sse2_pmaxs_w:
10523   case Intrinsic::x86_sse41_pmaxsd:
10524   case Intrinsic::x86_avx2_pmaxs_b:
10525   case Intrinsic::x86_avx2_pmaxs_w:
10526   case Intrinsic::x86_avx2_pmaxs_d:
10527   case Intrinsic::x86_sse41_pminsb:
10528   case Intrinsic::x86_sse2_pmins_w:
10529   case Intrinsic::x86_sse41_pminsd:
10530   case Intrinsic::x86_avx2_pmins_b:
10531   case Intrinsic::x86_avx2_pmins_w:
10532   case Intrinsic::x86_avx2_pmins_d: {
10533     unsigned Opcode;
10534     switch (IntNo) {
10535     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10536     case Intrinsic::x86_sse2_pmaxu_b:
10537     case Intrinsic::x86_sse41_pmaxuw:
10538     case Intrinsic::x86_sse41_pmaxud:
10539     case Intrinsic::x86_avx2_pmaxu_b:
10540     case Intrinsic::x86_avx2_pmaxu_w:
10541     case Intrinsic::x86_avx2_pmaxu_d:
10542       Opcode = X86ISD::UMAX;
10543       break;
10544     case Intrinsic::x86_sse2_pminu_b:
10545     case Intrinsic::x86_sse41_pminuw:
10546     case Intrinsic::x86_sse41_pminud:
10547     case Intrinsic::x86_avx2_pminu_b:
10548     case Intrinsic::x86_avx2_pminu_w:
10549     case Intrinsic::x86_avx2_pminu_d:
10550       Opcode = X86ISD::UMIN;
10551       break;
10552     case Intrinsic::x86_sse41_pmaxsb:
10553     case Intrinsic::x86_sse2_pmaxs_w:
10554     case Intrinsic::x86_sse41_pmaxsd:
10555     case Intrinsic::x86_avx2_pmaxs_b:
10556     case Intrinsic::x86_avx2_pmaxs_w:
10557     case Intrinsic::x86_avx2_pmaxs_d:
10558       Opcode = X86ISD::SMAX;
10559       break;
10560     case Intrinsic::x86_sse41_pminsb:
10561     case Intrinsic::x86_sse2_pmins_w:
10562     case Intrinsic::x86_sse41_pminsd:
10563     case Intrinsic::x86_avx2_pmins_b:
10564     case Intrinsic::x86_avx2_pmins_w:
10565     case Intrinsic::x86_avx2_pmins_d:
10566       Opcode = X86ISD::SMIN;
10567       break;
10568     }
10569     return DAG.getNode(Opcode, dl, Op.getValueType(),
10570                        Op.getOperand(1), Op.getOperand(2));
10571   }
10572
10573   // SSE/SSE2/AVX floating point max/min intrinsics.
10574   case Intrinsic::x86_sse_max_ps:
10575   case Intrinsic::x86_sse2_max_pd:
10576   case Intrinsic::x86_avx_max_ps_256:
10577   case Intrinsic::x86_avx_max_pd_256:
10578   case Intrinsic::x86_sse_min_ps:
10579   case Intrinsic::x86_sse2_min_pd:
10580   case Intrinsic::x86_avx_min_ps_256:
10581   case Intrinsic::x86_avx_min_pd_256: {
10582     unsigned Opcode;
10583     switch (IntNo) {
10584     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10585     case Intrinsic::x86_sse_max_ps:
10586     case Intrinsic::x86_sse2_max_pd:
10587     case Intrinsic::x86_avx_max_ps_256:
10588     case Intrinsic::x86_avx_max_pd_256:
10589       Opcode = X86ISD::FMAX;
10590       break;
10591     case Intrinsic::x86_sse_min_ps:
10592     case Intrinsic::x86_sse2_min_pd:
10593     case Intrinsic::x86_avx_min_ps_256:
10594     case Intrinsic::x86_avx_min_pd_256:
10595       Opcode = X86ISD::FMIN;
10596       break;
10597     }
10598     return DAG.getNode(Opcode, dl, Op.getValueType(),
10599                        Op.getOperand(1), Op.getOperand(2));
10600   }
10601
10602   // AVX2 variable shift intrinsics
10603   case Intrinsic::x86_avx2_psllv_d:
10604   case Intrinsic::x86_avx2_psllv_q:
10605   case Intrinsic::x86_avx2_psllv_d_256:
10606   case Intrinsic::x86_avx2_psllv_q_256:
10607   case Intrinsic::x86_avx2_psrlv_d:
10608   case Intrinsic::x86_avx2_psrlv_q:
10609   case Intrinsic::x86_avx2_psrlv_d_256:
10610   case Intrinsic::x86_avx2_psrlv_q_256:
10611   case Intrinsic::x86_avx2_psrav_d:
10612   case Intrinsic::x86_avx2_psrav_d_256: {
10613     unsigned Opcode;
10614     switch (IntNo) {
10615     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10616     case Intrinsic::x86_avx2_psllv_d:
10617     case Intrinsic::x86_avx2_psllv_q:
10618     case Intrinsic::x86_avx2_psllv_d_256:
10619     case Intrinsic::x86_avx2_psllv_q_256:
10620       Opcode = ISD::SHL;
10621       break;
10622     case Intrinsic::x86_avx2_psrlv_d:
10623     case Intrinsic::x86_avx2_psrlv_q:
10624     case Intrinsic::x86_avx2_psrlv_d_256:
10625     case Intrinsic::x86_avx2_psrlv_q_256:
10626       Opcode = ISD::SRL;
10627       break;
10628     case Intrinsic::x86_avx2_psrav_d:
10629     case Intrinsic::x86_avx2_psrav_d_256:
10630       Opcode = ISD::SRA;
10631       break;
10632     }
10633     return DAG.getNode(Opcode, dl, Op.getValueType(),
10634                        Op.getOperand(1), Op.getOperand(2));
10635   }
10636
10637   case Intrinsic::x86_ssse3_pshuf_b_128:
10638   case Intrinsic::x86_avx2_pshuf_b:
10639     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
10640                        Op.getOperand(1), Op.getOperand(2));
10641
10642   case Intrinsic::x86_ssse3_psign_b_128:
10643   case Intrinsic::x86_ssse3_psign_w_128:
10644   case Intrinsic::x86_ssse3_psign_d_128:
10645   case Intrinsic::x86_avx2_psign_b:
10646   case Intrinsic::x86_avx2_psign_w:
10647   case Intrinsic::x86_avx2_psign_d:
10648     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
10649                        Op.getOperand(1), Op.getOperand(2));
10650
10651   case Intrinsic::x86_sse41_insertps:
10652     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
10653                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10654
10655   case Intrinsic::x86_avx_vperm2f128_ps_256:
10656   case Intrinsic::x86_avx_vperm2f128_pd_256:
10657   case Intrinsic::x86_avx_vperm2f128_si_256:
10658   case Intrinsic::x86_avx2_vperm2i128:
10659     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
10660                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
10661
10662   case Intrinsic::x86_avx2_permd:
10663   case Intrinsic::x86_avx2_permps:
10664     // Operands intentionally swapped. Mask is last operand to intrinsic,
10665     // but second operand for node/intruction.
10666     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
10667                        Op.getOperand(2), Op.getOperand(1));
10668
10669   case Intrinsic::x86_sse_sqrt_ps:
10670   case Intrinsic::x86_sse2_sqrt_pd:
10671   case Intrinsic::x86_avx_sqrt_ps_256:
10672   case Intrinsic::x86_avx_sqrt_pd_256:
10673     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
10674
10675   // ptest and testp intrinsics. The intrinsic these come from are designed to
10676   // return an integer value, not just an instruction so lower it to the ptest
10677   // or testp pattern and a setcc for the result.
10678   case Intrinsic::x86_sse41_ptestz:
10679   case Intrinsic::x86_sse41_ptestc:
10680   case Intrinsic::x86_sse41_ptestnzc:
10681   case Intrinsic::x86_avx_ptestz_256:
10682   case Intrinsic::x86_avx_ptestc_256:
10683   case Intrinsic::x86_avx_ptestnzc_256:
10684   case Intrinsic::x86_avx_vtestz_ps:
10685   case Intrinsic::x86_avx_vtestc_ps:
10686   case Intrinsic::x86_avx_vtestnzc_ps:
10687   case Intrinsic::x86_avx_vtestz_pd:
10688   case Intrinsic::x86_avx_vtestc_pd:
10689   case Intrinsic::x86_avx_vtestnzc_pd:
10690   case Intrinsic::x86_avx_vtestz_ps_256:
10691   case Intrinsic::x86_avx_vtestc_ps_256:
10692   case Intrinsic::x86_avx_vtestnzc_ps_256:
10693   case Intrinsic::x86_avx_vtestz_pd_256:
10694   case Intrinsic::x86_avx_vtestc_pd_256:
10695   case Intrinsic::x86_avx_vtestnzc_pd_256: {
10696     bool IsTestPacked = false;
10697     unsigned X86CC;
10698     switch (IntNo) {
10699     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
10700     case Intrinsic::x86_avx_vtestz_ps:
10701     case Intrinsic::x86_avx_vtestz_pd:
10702     case Intrinsic::x86_avx_vtestz_ps_256:
10703     case Intrinsic::x86_avx_vtestz_pd_256:
10704       IsTestPacked = true; // Fallthrough
10705     case Intrinsic::x86_sse41_ptestz:
10706     case Intrinsic::x86_avx_ptestz_256:
10707       // ZF = 1
10708       X86CC = X86::COND_E;
10709       break;
10710     case Intrinsic::x86_avx_vtestc_ps:
10711     case Intrinsic::x86_avx_vtestc_pd:
10712     case Intrinsic::x86_avx_vtestc_ps_256:
10713     case Intrinsic::x86_avx_vtestc_pd_256:
10714       IsTestPacked = true; // Fallthrough
10715     case Intrinsic::x86_sse41_ptestc:
10716     case Intrinsic::x86_avx_ptestc_256:
10717       // CF = 1
10718       X86CC = X86::COND_B;
10719       break;
10720     case Intrinsic::x86_avx_vtestnzc_ps:
10721     case Intrinsic::x86_avx_vtestnzc_pd:
10722     case Intrinsic::x86_avx_vtestnzc_ps_256:
10723     case Intrinsic::x86_avx_vtestnzc_pd_256:
10724       IsTestPacked = true; // Fallthrough
10725     case Intrinsic::x86_sse41_ptestnzc:
10726     case Intrinsic::x86_avx_ptestnzc_256:
10727       // ZF and CF = 0
10728       X86CC = X86::COND_A;
10729       break;
10730     }
10731
10732     SDValue LHS = Op.getOperand(1);
10733     SDValue RHS = Op.getOperand(2);
10734     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
10735     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
10736     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
10737     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
10738     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10739   }
10740
10741   // SSE/AVX shift intrinsics
10742   case Intrinsic::x86_sse2_psll_w:
10743   case Intrinsic::x86_sse2_psll_d:
10744   case Intrinsic::x86_sse2_psll_q:
10745   case Intrinsic::x86_avx2_psll_w:
10746   case Intrinsic::x86_avx2_psll_d:
10747   case Intrinsic::x86_avx2_psll_q:
10748   case Intrinsic::x86_sse2_psrl_w:
10749   case Intrinsic::x86_sse2_psrl_d:
10750   case Intrinsic::x86_sse2_psrl_q:
10751   case Intrinsic::x86_avx2_psrl_w:
10752   case Intrinsic::x86_avx2_psrl_d:
10753   case Intrinsic::x86_avx2_psrl_q:
10754   case Intrinsic::x86_sse2_psra_w:
10755   case Intrinsic::x86_sse2_psra_d:
10756   case Intrinsic::x86_avx2_psra_w:
10757   case Intrinsic::x86_avx2_psra_d: {
10758     unsigned Opcode;
10759     switch (IntNo) {
10760     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10761     case Intrinsic::x86_sse2_psll_w:
10762     case Intrinsic::x86_sse2_psll_d:
10763     case Intrinsic::x86_sse2_psll_q:
10764     case Intrinsic::x86_avx2_psll_w:
10765     case Intrinsic::x86_avx2_psll_d:
10766     case Intrinsic::x86_avx2_psll_q:
10767       Opcode = X86ISD::VSHL;
10768       break;
10769     case Intrinsic::x86_sse2_psrl_w:
10770     case Intrinsic::x86_sse2_psrl_d:
10771     case Intrinsic::x86_sse2_psrl_q:
10772     case Intrinsic::x86_avx2_psrl_w:
10773     case Intrinsic::x86_avx2_psrl_d:
10774     case Intrinsic::x86_avx2_psrl_q:
10775       Opcode = X86ISD::VSRL;
10776       break;
10777     case Intrinsic::x86_sse2_psra_w:
10778     case Intrinsic::x86_sse2_psra_d:
10779     case Intrinsic::x86_avx2_psra_w:
10780     case Intrinsic::x86_avx2_psra_d:
10781       Opcode = X86ISD::VSRA;
10782       break;
10783     }
10784     return DAG.getNode(Opcode, dl, Op.getValueType(),
10785                        Op.getOperand(1), Op.getOperand(2));
10786   }
10787
10788   // SSE/AVX immediate shift intrinsics
10789   case Intrinsic::x86_sse2_pslli_w:
10790   case Intrinsic::x86_sse2_pslli_d:
10791   case Intrinsic::x86_sse2_pslli_q:
10792   case Intrinsic::x86_avx2_pslli_w:
10793   case Intrinsic::x86_avx2_pslli_d:
10794   case Intrinsic::x86_avx2_pslli_q:
10795   case Intrinsic::x86_sse2_psrli_w:
10796   case Intrinsic::x86_sse2_psrli_d:
10797   case Intrinsic::x86_sse2_psrli_q:
10798   case Intrinsic::x86_avx2_psrli_w:
10799   case Intrinsic::x86_avx2_psrli_d:
10800   case Intrinsic::x86_avx2_psrli_q:
10801   case Intrinsic::x86_sse2_psrai_w:
10802   case Intrinsic::x86_sse2_psrai_d:
10803   case Intrinsic::x86_avx2_psrai_w:
10804   case Intrinsic::x86_avx2_psrai_d: {
10805     unsigned Opcode;
10806     switch (IntNo) {
10807     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10808     case Intrinsic::x86_sse2_pslli_w:
10809     case Intrinsic::x86_sse2_pslli_d:
10810     case Intrinsic::x86_sse2_pslli_q:
10811     case Intrinsic::x86_avx2_pslli_w:
10812     case Intrinsic::x86_avx2_pslli_d:
10813     case Intrinsic::x86_avx2_pslli_q:
10814       Opcode = X86ISD::VSHLI;
10815       break;
10816     case Intrinsic::x86_sse2_psrli_w:
10817     case Intrinsic::x86_sse2_psrli_d:
10818     case Intrinsic::x86_sse2_psrli_q:
10819     case Intrinsic::x86_avx2_psrli_w:
10820     case Intrinsic::x86_avx2_psrli_d:
10821     case Intrinsic::x86_avx2_psrli_q:
10822       Opcode = X86ISD::VSRLI;
10823       break;
10824     case Intrinsic::x86_sse2_psrai_w:
10825     case Intrinsic::x86_sse2_psrai_d:
10826     case Intrinsic::x86_avx2_psrai_w:
10827     case Intrinsic::x86_avx2_psrai_d:
10828       Opcode = X86ISD::VSRAI;
10829       break;
10830     }
10831     return getTargetVShiftNode(Opcode, dl, Op.getValueType(),
10832                                Op.getOperand(1), Op.getOperand(2), DAG);
10833   }
10834
10835   case Intrinsic::x86_sse42_pcmpistria128:
10836   case Intrinsic::x86_sse42_pcmpestria128:
10837   case Intrinsic::x86_sse42_pcmpistric128:
10838   case Intrinsic::x86_sse42_pcmpestric128:
10839   case Intrinsic::x86_sse42_pcmpistrio128:
10840   case Intrinsic::x86_sse42_pcmpestrio128:
10841   case Intrinsic::x86_sse42_pcmpistris128:
10842   case Intrinsic::x86_sse42_pcmpestris128:
10843   case Intrinsic::x86_sse42_pcmpistriz128:
10844   case Intrinsic::x86_sse42_pcmpestriz128: {
10845     unsigned Opcode;
10846     unsigned X86CC;
10847     switch (IntNo) {
10848     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10849     case Intrinsic::x86_sse42_pcmpistria128:
10850       Opcode = X86ISD::PCMPISTRI;
10851       X86CC = X86::COND_A;
10852       break;
10853     case Intrinsic::x86_sse42_pcmpestria128:
10854       Opcode = X86ISD::PCMPESTRI;
10855       X86CC = X86::COND_A;
10856       break;
10857     case Intrinsic::x86_sse42_pcmpistric128:
10858       Opcode = X86ISD::PCMPISTRI;
10859       X86CC = X86::COND_B;
10860       break;
10861     case Intrinsic::x86_sse42_pcmpestric128:
10862       Opcode = X86ISD::PCMPESTRI;
10863       X86CC = X86::COND_B;
10864       break;
10865     case Intrinsic::x86_sse42_pcmpistrio128:
10866       Opcode = X86ISD::PCMPISTRI;
10867       X86CC = X86::COND_O;
10868       break;
10869     case Intrinsic::x86_sse42_pcmpestrio128:
10870       Opcode = X86ISD::PCMPESTRI;
10871       X86CC = X86::COND_O;
10872       break;
10873     case Intrinsic::x86_sse42_pcmpistris128:
10874       Opcode = X86ISD::PCMPISTRI;
10875       X86CC = X86::COND_S;
10876       break;
10877     case Intrinsic::x86_sse42_pcmpestris128:
10878       Opcode = X86ISD::PCMPESTRI;
10879       X86CC = X86::COND_S;
10880       break;
10881     case Intrinsic::x86_sse42_pcmpistriz128:
10882       Opcode = X86ISD::PCMPISTRI;
10883       X86CC = X86::COND_E;
10884       break;
10885     case Intrinsic::x86_sse42_pcmpestriz128:
10886       Opcode = X86ISD::PCMPESTRI;
10887       X86CC = X86::COND_E;
10888       break;
10889     }
10890     SmallVector<SDValue, 5> NewOps;
10891     NewOps.append(Op->op_begin()+1, Op->op_end());
10892     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10893     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10894     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10895                                 DAG.getConstant(X86CC, MVT::i8),
10896                                 SDValue(PCMP.getNode(), 1));
10897     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
10898   }
10899
10900   case Intrinsic::x86_sse42_pcmpistri128:
10901   case Intrinsic::x86_sse42_pcmpestri128: {
10902     unsigned Opcode;
10903     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
10904       Opcode = X86ISD::PCMPISTRI;
10905     else
10906       Opcode = X86ISD::PCMPESTRI;
10907
10908     SmallVector<SDValue, 5> NewOps;
10909     NewOps.append(Op->op_begin()+1, Op->op_end());
10910     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10911     return DAG.getNode(Opcode, dl, VTs, NewOps.data(), NewOps.size());
10912   }
10913   case Intrinsic::x86_fma_vfmadd_ps:
10914   case Intrinsic::x86_fma_vfmadd_pd:
10915   case Intrinsic::x86_fma_vfmsub_ps:
10916   case Intrinsic::x86_fma_vfmsub_pd:
10917   case Intrinsic::x86_fma_vfnmadd_ps:
10918   case Intrinsic::x86_fma_vfnmadd_pd:
10919   case Intrinsic::x86_fma_vfnmsub_ps:
10920   case Intrinsic::x86_fma_vfnmsub_pd:
10921   case Intrinsic::x86_fma_vfmaddsub_ps:
10922   case Intrinsic::x86_fma_vfmaddsub_pd:
10923   case Intrinsic::x86_fma_vfmsubadd_ps:
10924   case Intrinsic::x86_fma_vfmsubadd_pd:
10925   case Intrinsic::x86_fma_vfmadd_ps_256:
10926   case Intrinsic::x86_fma_vfmadd_pd_256:
10927   case Intrinsic::x86_fma_vfmsub_ps_256:
10928   case Intrinsic::x86_fma_vfmsub_pd_256:
10929   case Intrinsic::x86_fma_vfnmadd_ps_256:
10930   case Intrinsic::x86_fma_vfnmadd_pd_256:
10931   case Intrinsic::x86_fma_vfnmsub_ps_256:
10932   case Intrinsic::x86_fma_vfnmsub_pd_256:
10933   case Intrinsic::x86_fma_vfmaddsub_ps_256:
10934   case Intrinsic::x86_fma_vfmaddsub_pd_256:
10935   case Intrinsic::x86_fma_vfmsubadd_ps_256:
10936   case Intrinsic::x86_fma_vfmsubadd_pd_256: {
10937     unsigned Opc;
10938     switch (IntNo) {
10939     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
10940     case Intrinsic::x86_fma_vfmadd_ps:
10941     case Intrinsic::x86_fma_vfmadd_pd:
10942     case Intrinsic::x86_fma_vfmadd_ps_256:
10943     case Intrinsic::x86_fma_vfmadd_pd_256:
10944       Opc = X86ISD::FMADD;
10945       break;
10946     case Intrinsic::x86_fma_vfmsub_ps:
10947     case Intrinsic::x86_fma_vfmsub_pd:
10948     case Intrinsic::x86_fma_vfmsub_ps_256:
10949     case Intrinsic::x86_fma_vfmsub_pd_256:
10950       Opc = X86ISD::FMSUB;
10951       break;
10952     case Intrinsic::x86_fma_vfnmadd_ps:
10953     case Intrinsic::x86_fma_vfnmadd_pd:
10954     case Intrinsic::x86_fma_vfnmadd_ps_256:
10955     case Intrinsic::x86_fma_vfnmadd_pd_256:
10956       Opc = X86ISD::FNMADD;
10957       break;
10958     case Intrinsic::x86_fma_vfnmsub_ps:
10959     case Intrinsic::x86_fma_vfnmsub_pd:
10960     case Intrinsic::x86_fma_vfnmsub_ps_256:
10961     case Intrinsic::x86_fma_vfnmsub_pd_256:
10962       Opc = X86ISD::FNMSUB;
10963       break;
10964     case Intrinsic::x86_fma_vfmaddsub_ps:
10965     case Intrinsic::x86_fma_vfmaddsub_pd:
10966     case Intrinsic::x86_fma_vfmaddsub_ps_256:
10967     case Intrinsic::x86_fma_vfmaddsub_pd_256:
10968       Opc = X86ISD::FMADDSUB;
10969       break;
10970     case Intrinsic::x86_fma_vfmsubadd_ps:
10971     case Intrinsic::x86_fma_vfmsubadd_pd:
10972     case Intrinsic::x86_fma_vfmsubadd_ps_256:
10973     case Intrinsic::x86_fma_vfmsubadd_pd_256:
10974       Opc = X86ISD::FMSUBADD;
10975       break;
10976     }
10977
10978     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
10979                        Op.getOperand(2), Op.getOperand(3));
10980   }
10981   }
10982 }
10983
10984 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, SelectionDAG &DAG) {
10985   SDLoc dl(Op);
10986   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10987   switch (IntNo) {
10988   default: return SDValue();    // Don't custom lower most intrinsics.
10989
10990   // RDRAND/RDSEED intrinsics.
10991   case Intrinsic::x86_rdrand_16:
10992   case Intrinsic::x86_rdrand_32:
10993   case Intrinsic::x86_rdrand_64:
10994   case Intrinsic::x86_rdseed_16:
10995   case Intrinsic::x86_rdseed_32:
10996   case Intrinsic::x86_rdseed_64: {
10997     unsigned Opcode = (IntNo == Intrinsic::x86_rdseed_16 ||
10998                        IntNo == Intrinsic::x86_rdseed_32 ||
10999                        IntNo == Intrinsic::x86_rdseed_64) ? X86ISD::RDSEED :
11000                                                             X86ISD::RDRAND;
11001     // Emit the node with the right value type.
11002     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
11003     SDValue Result = DAG.getNode(Opcode, dl, VTs, Op.getOperand(0));
11004
11005     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
11006     // Otherwise return the value from Rand, which is always 0, casted to i32.
11007     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
11008                       DAG.getConstant(1, Op->getValueType(1)),
11009                       DAG.getConstant(X86::COND_B, MVT::i32),
11010                       SDValue(Result.getNode(), 1) };
11011     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
11012                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
11013                                   Ops, array_lengthof(Ops));
11014
11015     // Return { result, isValid, chain }.
11016     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
11017                        SDValue(Result.getNode(), 2));
11018   }
11019
11020   // XTEST intrinsics.
11021   case Intrinsic::x86_xtest: {
11022     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
11023     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
11024     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11025                                 DAG.getConstant(X86::COND_NE, MVT::i8),
11026                                 InTrans);
11027     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
11028     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
11029                        Ret, SDValue(InTrans.getNode(), 1));
11030   }
11031   }
11032 }
11033
11034 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
11035                                            SelectionDAG &DAG) const {
11036   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11037   MFI->setReturnAddressIsTaken(true);
11038
11039   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11040   SDLoc dl(Op);
11041   EVT PtrVT = getPointerTy();
11042
11043   if (Depth > 0) {
11044     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
11045     const X86RegisterInfo *RegInfo =
11046       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11047     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
11048     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11049                        DAG.getNode(ISD::ADD, dl, PtrVT,
11050                                    FrameAddr, Offset),
11051                        MachinePointerInfo(), false, false, false, 0);
11052   }
11053
11054   // Just load the return address.
11055   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
11056   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
11057                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
11058 }
11059
11060 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
11061   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11062   MFI->setFrameAddressIsTaken(true);
11063
11064   EVT VT = Op.getValueType();
11065   SDLoc dl(Op);  // FIXME probably not meaningful
11066   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11067   const X86RegisterInfo *RegInfo =
11068     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11069   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11070   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
11071           (FrameReg == X86::EBP && VT == MVT::i32)) &&
11072          "Invalid Frame Register!");
11073   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
11074   while (Depth--)
11075     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
11076                             MachinePointerInfo(),
11077                             false, false, false, 0);
11078   return FrameAddr;
11079 }
11080
11081 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
11082                                                      SelectionDAG &DAG) const {
11083   const X86RegisterInfo *RegInfo =
11084     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11085   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
11086 }
11087
11088 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
11089   SDValue Chain     = Op.getOperand(0);
11090   SDValue Offset    = Op.getOperand(1);
11091   SDValue Handler   = Op.getOperand(2);
11092   SDLoc dl      (Op);
11093
11094   EVT PtrVT = getPointerTy();
11095   const X86RegisterInfo *RegInfo =
11096     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11097   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
11098   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
11099           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
11100          "Invalid Frame Register!");
11101   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
11102   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
11103
11104   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
11105                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
11106   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
11107   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
11108                        false, false, 0);
11109   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
11110
11111   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
11112                      DAG.getRegister(StoreAddrReg, PtrVT));
11113 }
11114
11115 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
11116                                                SelectionDAG &DAG) const {
11117   SDLoc DL(Op);
11118   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
11119                      DAG.getVTList(MVT::i32, MVT::Other),
11120                      Op.getOperand(0), Op.getOperand(1));
11121 }
11122
11123 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
11124                                                 SelectionDAG &DAG) const {
11125   SDLoc DL(Op);
11126   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
11127                      Op.getOperand(0), Op.getOperand(1));
11128 }
11129
11130 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
11131   return Op.getOperand(0);
11132 }
11133
11134 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
11135                                                 SelectionDAG &DAG) const {
11136   SDValue Root = Op.getOperand(0);
11137   SDValue Trmp = Op.getOperand(1); // trampoline
11138   SDValue FPtr = Op.getOperand(2); // nested function
11139   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
11140   SDLoc dl (Op);
11141
11142   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11143   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
11144
11145   if (Subtarget->is64Bit()) {
11146     SDValue OutChains[6];
11147
11148     // Large code-model.
11149     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
11150     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
11151
11152     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
11153     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
11154
11155     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
11156
11157     // Load the pointer to the nested function into R11.
11158     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
11159     SDValue Addr = Trmp;
11160     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11161                                 Addr, MachinePointerInfo(TrmpAddr),
11162                                 false, false, 0);
11163
11164     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11165                        DAG.getConstant(2, MVT::i64));
11166     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
11167                                 MachinePointerInfo(TrmpAddr, 2),
11168                                 false, false, 2);
11169
11170     // Load the 'nest' parameter value into R10.
11171     // R10 is specified in X86CallingConv.td
11172     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
11173     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11174                        DAG.getConstant(10, MVT::i64));
11175     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11176                                 Addr, MachinePointerInfo(TrmpAddr, 10),
11177                                 false, false, 0);
11178
11179     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11180                        DAG.getConstant(12, MVT::i64));
11181     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
11182                                 MachinePointerInfo(TrmpAddr, 12),
11183                                 false, false, 2);
11184
11185     // Jump to the nested function.
11186     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
11187     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11188                        DAG.getConstant(20, MVT::i64));
11189     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
11190                                 Addr, MachinePointerInfo(TrmpAddr, 20),
11191                                 false, false, 0);
11192
11193     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
11194     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
11195                        DAG.getConstant(22, MVT::i64));
11196     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
11197                                 MachinePointerInfo(TrmpAddr, 22),
11198                                 false, false, 0);
11199
11200     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
11201   } else {
11202     const Function *Func =
11203       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
11204     CallingConv::ID CC = Func->getCallingConv();
11205     unsigned NestReg;
11206
11207     switch (CC) {
11208     default:
11209       llvm_unreachable("Unsupported calling convention");
11210     case CallingConv::C:
11211     case CallingConv::X86_StdCall: {
11212       // Pass 'nest' parameter in ECX.
11213       // Must be kept in sync with X86CallingConv.td
11214       NestReg = X86::ECX;
11215
11216       // Check that ECX wasn't needed by an 'inreg' parameter.
11217       FunctionType *FTy = Func->getFunctionType();
11218       const AttributeSet &Attrs = Func->getAttributes();
11219
11220       if (!Attrs.isEmpty() && !Func->isVarArg()) {
11221         unsigned InRegCount = 0;
11222         unsigned Idx = 1;
11223
11224         for (FunctionType::param_iterator I = FTy->param_begin(),
11225              E = FTy->param_end(); I != E; ++I, ++Idx)
11226           if (Attrs.hasAttribute(Idx, Attribute::InReg))
11227             // FIXME: should only count parameters that are lowered to integers.
11228             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
11229
11230         if (InRegCount > 2) {
11231           report_fatal_error("Nest register in use - reduce number of inreg"
11232                              " parameters!");
11233         }
11234       }
11235       break;
11236     }
11237     case CallingConv::X86_FastCall:
11238     case CallingConv::X86_ThisCall:
11239     case CallingConv::Fast:
11240       // Pass 'nest' parameter in EAX.
11241       // Must be kept in sync with X86CallingConv.td
11242       NestReg = X86::EAX;
11243       break;
11244     }
11245
11246     SDValue OutChains[4];
11247     SDValue Addr, Disp;
11248
11249     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11250                        DAG.getConstant(10, MVT::i32));
11251     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
11252
11253     // This is storing the opcode for MOV32ri.
11254     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
11255     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
11256     OutChains[0] = DAG.getStore(Root, dl,
11257                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
11258                                 Trmp, MachinePointerInfo(TrmpAddr),
11259                                 false, false, 0);
11260
11261     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11262                        DAG.getConstant(1, MVT::i32));
11263     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
11264                                 MachinePointerInfo(TrmpAddr, 1),
11265                                 false, false, 1);
11266
11267     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
11268     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11269                        DAG.getConstant(5, MVT::i32));
11270     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
11271                                 MachinePointerInfo(TrmpAddr, 5),
11272                                 false, false, 1);
11273
11274     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
11275                        DAG.getConstant(6, MVT::i32));
11276     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
11277                                 MachinePointerInfo(TrmpAddr, 6),
11278                                 false, false, 1);
11279
11280     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
11281   }
11282 }
11283
11284 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
11285                                             SelectionDAG &DAG) const {
11286   /*
11287    The rounding mode is in bits 11:10 of FPSR, and has the following
11288    settings:
11289      00 Round to nearest
11290      01 Round to -inf
11291      10 Round to +inf
11292      11 Round to 0
11293
11294   FLT_ROUNDS, on the other hand, expects the following:
11295     -1 Undefined
11296      0 Round to 0
11297      1 Round to nearest
11298      2 Round to +inf
11299      3 Round to -inf
11300
11301   To perform the conversion, we do:
11302     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
11303   */
11304
11305   MachineFunction &MF = DAG.getMachineFunction();
11306   const TargetMachine &TM = MF.getTarget();
11307   const TargetFrameLowering &TFI = *TM.getFrameLowering();
11308   unsigned StackAlignment = TFI.getStackAlignment();
11309   EVT VT = Op.getValueType();
11310   SDLoc DL(Op);
11311
11312   // Save FP Control Word to stack slot
11313   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
11314   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11315
11316   MachineMemOperand *MMO =
11317    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11318                            MachineMemOperand::MOStore, 2, 2);
11319
11320   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
11321   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
11322                                           DAG.getVTList(MVT::Other),
11323                                           Ops, array_lengthof(Ops), MVT::i16,
11324                                           MMO);
11325
11326   // Load FP Control Word from stack slot
11327   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
11328                             MachinePointerInfo(), false, false, false, 0);
11329
11330   // Transform as necessary
11331   SDValue CWD1 =
11332     DAG.getNode(ISD::SRL, DL, MVT::i16,
11333                 DAG.getNode(ISD::AND, DL, MVT::i16,
11334                             CWD, DAG.getConstant(0x800, MVT::i16)),
11335                 DAG.getConstant(11, MVT::i8));
11336   SDValue CWD2 =
11337     DAG.getNode(ISD::SRL, DL, MVT::i16,
11338                 DAG.getNode(ISD::AND, DL, MVT::i16,
11339                             CWD, DAG.getConstant(0x400, MVT::i16)),
11340                 DAG.getConstant(9, MVT::i8));
11341
11342   SDValue RetVal =
11343     DAG.getNode(ISD::AND, DL, MVT::i16,
11344                 DAG.getNode(ISD::ADD, DL, MVT::i16,
11345                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
11346                             DAG.getConstant(1, MVT::i16)),
11347                 DAG.getConstant(3, MVT::i16));
11348
11349   return DAG.getNode((VT.getSizeInBits() < 16 ?
11350                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
11351 }
11352
11353 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
11354   EVT VT = Op.getValueType();
11355   EVT OpVT = VT;
11356   unsigned NumBits = VT.getSizeInBits();
11357   SDLoc dl(Op);
11358
11359   Op = Op.getOperand(0);
11360   if (VT == MVT::i8) {
11361     // Zero extend to i32 since there is not an i8 bsr.
11362     OpVT = MVT::i32;
11363     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11364   }
11365
11366   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
11367   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11368   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11369
11370   // If src is zero (i.e. bsr sets ZF), returns NumBits.
11371   SDValue Ops[] = {
11372     Op,
11373     DAG.getConstant(NumBits+NumBits-1, OpVT),
11374     DAG.getConstant(X86::COND_E, MVT::i8),
11375     Op.getValue(1)
11376   };
11377   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
11378
11379   // Finally xor with NumBits-1.
11380   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11381
11382   if (VT == MVT::i8)
11383     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11384   return Op;
11385 }
11386
11387 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
11388   EVT VT = Op.getValueType();
11389   EVT OpVT = VT;
11390   unsigned NumBits = VT.getSizeInBits();
11391   SDLoc dl(Op);
11392
11393   Op = Op.getOperand(0);
11394   if (VT == MVT::i8) {
11395     // Zero extend to i32 since there is not an i8 bsr.
11396     OpVT = MVT::i32;
11397     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
11398   }
11399
11400   // Issue a bsr (scan bits in reverse).
11401   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
11402   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
11403
11404   // And xor with NumBits-1.
11405   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
11406
11407   if (VT == MVT::i8)
11408     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
11409   return Op;
11410 }
11411
11412 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
11413   EVT VT = Op.getValueType();
11414   unsigned NumBits = VT.getSizeInBits();
11415   SDLoc dl(Op);
11416   Op = Op.getOperand(0);
11417
11418   // Issue a bsf (scan bits forward) which also sets EFLAGS.
11419   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
11420   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
11421
11422   // If src is zero (i.e. bsf sets ZF), returns NumBits.
11423   SDValue Ops[] = {
11424     Op,
11425     DAG.getConstant(NumBits, VT),
11426     DAG.getConstant(X86::COND_E, MVT::i8),
11427     Op.getValue(1)
11428   };
11429   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops, array_lengthof(Ops));
11430 }
11431
11432 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
11433 // ones, and then concatenate the result back.
11434 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
11435   EVT VT = Op.getValueType();
11436
11437   assert(VT.is256BitVector() && VT.isInteger() &&
11438          "Unsupported value type for operation");
11439
11440   unsigned NumElems = VT.getVectorNumElements();
11441   SDLoc dl(Op);
11442
11443   // Extract the LHS vectors
11444   SDValue LHS = Op.getOperand(0);
11445   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
11446   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
11447
11448   // Extract the RHS vectors
11449   SDValue RHS = Op.getOperand(1);
11450   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
11451   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
11452
11453   MVT EltVT = VT.getVectorElementType().getSimpleVT();
11454   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11455
11456   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
11457                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
11458                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
11459 }
11460
11461 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
11462   assert(Op.getValueType().is256BitVector() &&
11463          Op.getValueType().isInteger() &&
11464          "Only handle AVX 256-bit vector integer operation");
11465   return Lower256IntArith(Op, DAG);
11466 }
11467
11468 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
11469   assert(Op.getValueType().is256BitVector() &&
11470          Op.getValueType().isInteger() &&
11471          "Only handle AVX 256-bit vector integer operation");
11472   return Lower256IntArith(Op, DAG);
11473 }
11474
11475 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
11476                         SelectionDAG &DAG) {
11477   SDLoc dl(Op);
11478   EVT VT = Op.getValueType();
11479
11480   // Decompose 256-bit ops into smaller 128-bit ops.
11481   if (VT.is256BitVector() && !Subtarget->hasInt256())
11482     return Lower256IntArith(Op, DAG);
11483
11484   SDValue A = Op.getOperand(0);
11485   SDValue B = Op.getOperand(1);
11486
11487   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
11488   if (VT == MVT::v4i32) {
11489     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
11490            "Should not custom lower when pmuldq is available!");
11491
11492     // Extract the odd parts.
11493     const int UnpackMask[] = { 1, -1, 3, -1 };
11494     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
11495     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
11496
11497     // Multiply the even parts.
11498     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
11499     // Now multiply odd parts.
11500     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
11501
11502     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
11503     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
11504
11505     // Merge the two vectors back together with a shuffle. This expands into 2
11506     // shuffles.
11507     const int ShufMask[] = { 0, 4, 2, 6 };
11508     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
11509   }
11510
11511   assert((VT == MVT::v2i64 || VT == MVT::v4i64) &&
11512          "Only know how to lower V2I64/V4I64 multiply");
11513
11514   //  Ahi = psrlqi(a, 32);
11515   //  Bhi = psrlqi(b, 32);
11516   //
11517   //  AloBlo = pmuludq(a, b);
11518   //  AloBhi = pmuludq(a, Bhi);
11519   //  AhiBlo = pmuludq(Ahi, b);
11520
11521   //  AloBhi = psllqi(AloBhi, 32);
11522   //  AhiBlo = psllqi(AhiBlo, 32);
11523   //  return AloBlo + AloBhi + AhiBlo;
11524
11525   SDValue ShAmt = DAG.getConstant(32, MVT::i32);
11526
11527   SDValue Ahi = DAG.getNode(X86ISD::VSRLI, dl, VT, A, ShAmt);
11528   SDValue Bhi = DAG.getNode(X86ISD::VSRLI, dl, VT, B, ShAmt);
11529
11530   // Bit cast to 32-bit vectors for MULUDQ
11531   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 : MVT::v8i32;
11532   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
11533   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
11534   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
11535   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
11536
11537   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
11538   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
11539   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
11540
11541   AloBhi = DAG.getNode(X86ISD::VSHLI, dl, VT, AloBhi, ShAmt);
11542   AhiBlo = DAG.getNode(X86ISD::VSHLI, dl, VT, AhiBlo, ShAmt);
11543
11544   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
11545   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
11546 }
11547
11548 SDValue X86TargetLowering::LowerSDIV(SDValue Op, SelectionDAG &DAG) const {
11549   EVT VT = Op.getValueType();
11550   EVT EltTy = VT.getVectorElementType();
11551   unsigned NumElts = VT.getVectorNumElements();
11552   SDValue N0 = Op.getOperand(0);
11553   SDLoc dl(Op);
11554
11555   // Lower sdiv X, pow2-const.
11556   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(Op.getOperand(1));
11557   if (!C)
11558     return SDValue();
11559
11560   APInt SplatValue, SplatUndef;
11561   unsigned SplatBitSize;
11562   bool HasAnyUndefs;
11563   if (!C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
11564                           HasAnyUndefs) ||
11565       EltTy.getSizeInBits() < SplatBitSize)
11566     return SDValue();
11567
11568   if ((SplatValue != 0) &&
11569       (SplatValue.isPowerOf2() || (-SplatValue).isPowerOf2())) {
11570     unsigned lg2 = SplatValue.countTrailingZeros();
11571     // Splat the sign bit.
11572     SDValue Sz = DAG.getConstant(EltTy.getSizeInBits()-1, MVT::i32);
11573     SDValue SGN = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, N0, Sz, DAG);
11574     // Add (N0 < 0) ? abs2 - 1 : 0;
11575     SDValue Amt = DAG.getConstant(EltTy.getSizeInBits() - lg2, MVT::i32);
11576     SDValue SRL = getTargetVShiftNode(X86ISD::VSRLI, dl, VT, SGN, Amt, DAG);
11577     SDValue ADD = DAG.getNode(ISD::ADD, dl, VT, N0, SRL);
11578     SDValue Lg2Amt = DAG.getConstant(lg2, MVT::i32);
11579     SDValue SRA = getTargetVShiftNode(X86ISD::VSRAI, dl, VT, ADD, Lg2Amt, DAG);
11580
11581     // If we're dividing by a positive value, we're done.  Otherwise, we must
11582     // negate the result.
11583     if (SplatValue.isNonNegative())
11584       return SRA;
11585
11586     SmallVector<SDValue, 16> V(NumElts, DAG.getConstant(0, EltTy));
11587     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], NumElts);
11588     return DAG.getNode(ISD::SUB, dl, VT, Zero, SRA);
11589   }
11590   return SDValue();
11591 }
11592
11593 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
11594                                          const X86Subtarget *Subtarget) {
11595   EVT VT = Op.getValueType();
11596   SDLoc dl(Op);
11597   SDValue R = Op.getOperand(0);
11598   SDValue Amt = Op.getOperand(1);
11599
11600   // Optimize shl/srl/sra with constant shift amount.
11601   if (isSplatVector(Amt.getNode())) {
11602     SDValue SclrAmt = Amt->getOperand(0);
11603     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
11604       uint64_t ShiftAmt = C->getZExtValue();
11605
11606       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
11607           (Subtarget->hasInt256() &&
11608            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16))) {
11609         if (Op.getOpcode() == ISD::SHL)
11610           return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11611                              DAG.getConstant(ShiftAmt, MVT::i32));
11612         if (Op.getOpcode() == ISD::SRL)
11613           return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11614                              DAG.getConstant(ShiftAmt, MVT::i32));
11615         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
11616           return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11617                              DAG.getConstant(ShiftAmt, MVT::i32));
11618       }
11619
11620       if (VT == MVT::v16i8) {
11621         if (Op.getOpcode() == ISD::SHL) {
11622           // Make a large shift.
11623           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v8i16, R,
11624                                     DAG.getConstant(ShiftAmt, MVT::i32));
11625           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11626           // Zero out the rightmost bits.
11627           SmallVector<SDValue, 16> V(16,
11628                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11629                                                      MVT::i8));
11630           return DAG.getNode(ISD::AND, dl, VT, SHL,
11631                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11632         }
11633         if (Op.getOpcode() == ISD::SRL) {
11634           // Make a large shift.
11635           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v8i16, R,
11636                                     DAG.getConstant(ShiftAmt, MVT::i32));
11637           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11638           // Zero out the leftmost bits.
11639           SmallVector<SDValue, 16> V(16,
11640                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11641                                                      MVT::i8));
11642           return DAG.getNode(ISD::AND, dl, VT, SRL,
11643                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
11644         }
11645         if (Op.getOpcode() == ISD::SRA) {
11646           if (ShiftAmt == 7) {
11647             // R s>> 7  ===  R s< 0
11648             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11649             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11650           }
11651
11652           // R s>> a === ((R u>> a) ^ m) - m
11653           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11654           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
11655                                                          MVT::i8));
11656           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
11657           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11658           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11659           return Res;
11660         }
11661         llvm_unreachable("Unknown shift opcode.");
11662       }
11663
11664       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
11665         if (Op.getOpcode() == ISD::SHL) {
11666           // Make a large shift.
11667           SDValue SHL = DAG.getNode(X86ISD::VSHLI, dl, MVT::v16i16, R,
11668                                     DAG.getConstant(ShiftAmt, MVT::i32));
11669           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
11670           // Zero out the rightmost bits.
11671           SmallVector<SDValue, 32> V(32,
11672                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
11673                                                      MVT::i8));
11674           return DAG.getNode(ISD::AND, dl, VT, SHL,
11675                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11676         }
11677         if (Op.getOpcode() == ISD::SRL) {
11678           // Make a large shift.
11679           SDValue SRL = DAG.getNode(X86ISD::VSRLI, dl, MVT::v16i16, R,
11680                                     DAG.getConstant(ShiftAmt, MVT::i32));
11681           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
11682           // Zero out the leftmost bits.
11683           SmallVector<SDValue, 32> V(32,
11684                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
11685                                                      MVT::i8));
11686           return DAG.getNode(ISD::AND, dl, VT, SRL,
11687                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
11688         }
11689         if (Op.getOpcode() == ISD::SRA) {
11690           if (ShiftAmt == 7) {
11691             // R s>> 7  ===  R s< 0
11692             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
11693             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
11694           }
11695
11696           // R s>> a === ((R u>> a) ^ m) - m
11697           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
11698           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
11699                                                          MVT::i8));
11700           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
11701           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
11702           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
11703           return Res;
11704         }
11705         llvm_unreachable("Unknown shift opcode.");
11706       }
11707     }
11708   }
11709
11710   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11711   if (!Subtarget->is64Bit() &&
11712       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11713       Amt.getOpcode() == ISD::BITCAST &&
11714       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11715     Amt = Amt.getOperand(0);
11716     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11717                      VT.getVectorNumElements();
11718     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
11719     uint64_t ShiftAmt = 0;
11720     for (unsigned i = 0; i != Ratio; ++i) {
11721       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
11722       if (C == 0)
11723         return SDValue();
11724       // 6 == Log2(64)
11725       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
11726     }
11727     // Check remaining shift amounts.
11728     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11729       uint64_t ShAmt = 0;
11730       for (unsigned j = 0; j != Ratio; ++j) {
11731         ConstantSDNode *C =
11732           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
11733         if (C == 0)
11734           return SDValue();
11735         // 6 == Log2(64)
11736         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
11737       }
11738       if (ShAmt != ShiftAmt)
11739         return SDValue();
11740     }
11741     switch (Op.getOpcode()) {
11742     default:
11743       llvm_unreachable("Unknown shift opcode!");
11744     case ISD::SHL:
11745       return DAG.getNode(X86ISD::VSHLI, dl, VT, R,
11746                          DAG.getConstant(ShiftAmt, MVT::i32));
11747     case ISD::SRL:
11748       return DAG.getNode(X86ISD::VSRLI, dl, VT, R,
11749                          DAG.getConstant(ShiftAmt, MVT::i32));
11750     case ISD::SRA:
11751       return DAG.getNode(X86ISD::VSRAI, dl, VT, R,
11752                          DAG.getConstant(ShiftAmt, MVT::i32));
11753     }
11754   }
11755
11756   return SDValue();
11757 }
11758
11759 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
11760                                         const X86Subtarget* Subtarget) {
11761   EVT VT = Op.getValueType();
11762   SDLoc dl(Op);
11763   SDValue R = Op.getOperand(0);
11764   SDValue Amt = Op.getOperand(1);
11765
11766   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
11767       VT == MVT::v4i32 || VT == MVT::v8i16 ||
11768       (Subtarget->hasInt256() &&
11769        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
11770         VT == MVT::v8i32 || VT == MVT::v16i16))) {
11771     SDValue BaseShAmt;
11772     EVT EltVT = VT.getVectorElementType();
11773
11774     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11775       unsigned NumElts = VT.getVectorNumElements();
11776       unsigned i, j;
11777       for (i = 0; i != NumElts; ++i) {
11778         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
11779           continue;
11780         break;
11781       }
11782       for (j = i; j != NumElts; ++j) {
11783         SDValue Arg = Amt.getOperand(j);
11784         if (Arg.getOpcode() == ISD::UNDEF) continue;
11785         if (Arg != Amt.getOperand(i))
11786           break;
11787       }
11788       if (i != NumElts && j == NumElts)
11789         BaseShAmt = Amt.getOperand(i);
11790     } else {
11791       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
11792         Amt = Amt.getOperand(0);
11793       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
11794                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
11795         SDValue InVec = Amt.getOperand(0);
11796         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11797           unsigned NumElts = InVec.getValueType().getVectorNumElements();
11798           unsigned i = 0;
11799           for (; i != NumElts; ++i) {
11800             SDValue Arg = InVec.getOperand(i);
11801             if (Arg.getOpcode() == ISD::UNDEF) continue;
11802             BaseShAmt = Arg;
11803             break;
11804           }
11805         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11806            if (ConstantSDNode *C =
11807                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11808              unsigned SplatIdx =
11809                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
11810              if (C->getZExtValue() == SplatIdx)
11811                BaseShAmt = InVec.getOperand(1);
11812            }
11813         }
11814         if (BaseShAmt.getNode() == 0)
11815           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
11816                                   DAG.getIntPtrConstant(0));
11817       }
11818     }
11819
11820     if (BaseShAmt.getNode()) {
11821       if (EltVT.bitsGT(MVT::i32))
11822         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
11823       else if (EltVT.bitsLT(MVT::i32))
11824         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
11825
11826       switch (Op.getOpcode()) {
11827       default:
11828         llvm_unreachable("Unknown shift opcode!");
11829       case ISD::SHL:
11830         switch (VT.getSimpleVT().SimpleTy) {
11831         default: return SDValue();
11832         case MVT::v2i64:
11833         case MVT::v4i32:
11834         case MVT::v8i16:
11835         case MVT::v4i64:
11836         case MVT::v8i32:
11837         case MVT::v16i16:
11838           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
11839         }
11840       case ISD::SRA:
11841         switch (VT.getSimpleVT().SimpleTy) {
11842         default: return SDValue();
11843         case MVT::v4i32:
11844         case MVT::v8i16:
11845         case MVT::v8i32:
11846         case MVT::v16i16:
11847           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
11848         }
11849       case ISD::SRL:
11850         switch (VT.getSimpleVT().SimpleTy) {
11851         default: return SDValue();
11852         case MVT::v2i64:
11853         case MVT::v4i32:
11854         case MVT::v8i16:
11855         case MVT::v4i64:
11856         case MVT::v8i32:
11857         case MVT::v16i16:
11858           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
11859         }
11860       }
11861     }
11862   }
11863
11864   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
11865   if (!Subtarget->is64Bit() &&
11866       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
11867       Amt.getOpcode() == ISD::BITCAST &&
11868       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
11869     Amt = Amt.getOperand(0);
11870     unsigned Ratio = Amt.getValueType().getVectorNumElements() /
11871                      VT.getVectorNumElements();
11872     std::vector<SDValue> Vals(Ratio);
11873     for (unsigned i = 0; i != Ratio; ++i)
11874       Vals[i] = Amt.getOperand(i);
11875     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
11876       for (unsigned j = 0; j != Ratio; ++j)
11877         if (Vals[j] != Amt.getOperand(i + j))
11878           return SDValue();
11879     }
11880     switch (Op.getOpcode()) {
11881     default:
11882       llvm_unreachable("Unknown shift opcode!");
11883     case ISD::SHL:
11884       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
11885     case ISD::SRL:
11886       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
11887     case ISD::SRA:
11888       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
11889     }
11890   }
11891
11892   return SDValue();
11893 }
11894
11895 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
11896
11897   EVT VT = Op.getValueType();
11898   SDLoc dl(Op);
11899   SDValue R = Op.getOperand(0);
11900   SDValue Amt = Op.getOperand(1);
11901   SDValue V;
11902
11903   if (!Subtarget->hasSSE2())
11904     return SDValue();
11905
11906   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
11907   if (V.getNode())
11908     return V;
11909
11910   V = LowerScalarVariableShift(Op, DAG, Subtarget);
11911   if (V.getNode())
11912       return V;
11913
11914   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
11915   if (Subtarget->hasInt256()) {
11916     if (Op.getOpcode() == ISD::SRL &&
11917         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11918          VT == MVT::v4i64 || VT == MVT::v8i32))
11919       return Op;
11920     if (Op.getOpcode() == ISD::SHL &&
11921         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
11922          VT == MVT::v4i64 || VT == MVT::v8i32))
11923       return Op;
11924     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
11925       return Op;
11926   }
11927
11928   // Lower SHL with variable shift amount.
11929   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
11930     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
11931
11932     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
11933     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
11934     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
11935     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
11936   }
11937   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
11938     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
11939
11940     // a = a << 5;
11941     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
11942     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
11943
11944     // Turn 'a' into a mask suitable for VSELECT
11945     SDValue VSelM = DAG.getConstant(0x80, VT);
11946     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11947     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11948
11949     SDValue CM1 = DAG.getConstant(0x0f, VT);
11950     SDValue CM2 = DAG.getConstant(0x3f, VT);
11951
11952     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
11953     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
11954     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11955                             DAG.getConstant(4, MVT::i32), DAG);
11956     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11957     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11958
11959     // a += a
11960     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11961     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11962     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11963
11964     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
11965     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
11966     M = getTargetVShiftNode(X86ISD::VSHLI, dl, MVT::v8i16, M,
11967                             DAG.getConstant(2, MVT::i32), DAG);
11968     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
11969     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
11970
11971     // a += a
11972     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
11973     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
11974     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
11975
11976     // return VSELECT(r, r+r, a);
11977     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
11978                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
11979     return R;
11980   }
11981
11982   // Decompose 256-bit shifts into smaller 128-bit shifts.
11983   if (VT.is256BitVector()) {
11984     unsigned NumElems = VT.getVectorNumElements();
11985     MVT EltVT = VT.getVectorElementType().getSimpleVT();
11986     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
11987
11988     // Extract the two vectors
11989     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
11990     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
11991
11992     // Recreate the shift amount vectors
11993     SDValue Amt1, Amt2;
11994     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
11995       // Constant shift amount
11996       SmallVector<SDValue, 4> Amt1Csts;
11997       SmallVector<SDValue, 4> Amt2Csts;
11998       for (unsigned i = 0; i != NumElems/2; ++i)
11999         Amt1Csts.push_back(Amt->getOperand(i));
12000       for (unsigned i = NumElems/2; i != NumElems; ++i)
12001         Amt2Csts.push_back(Amt->getOperand(i));
12002
12003       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12004                                  &Amt1Csts[0], NumElems/2);
12005       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
12006                                  &Amt2Csts[0], NumElems/2);
12007     } else {
12008       // Variable shift amount
12009       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
12010       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
12011     }
12012
12013     // Issue new vector shifts for the smaller types
12014     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
12015     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
12016
12017     // Concatenate the result back
12018     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
12019   }
12020
12021   return SDValue();
12022 }
12023
12024 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
12025   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
12026   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
12027   // looks for this combo and may remove the "setcc" instruction if the "setcc"
12028   // has only one use.
12029   SDNode *N = Op.getNode();
12030   SDValue LHS = N->getOperand(0);
12031   SDValue RHS = N->getOperand(1);
12032   unsigned BaseOp = 0;
12033   unsigned Cond = 0;
12034   SDLoc DL(Op);
12035   switch (Op.getOpcode()) {
12036   default: llvm_unreachable("Unknown ovf instruction!");
12037   case ISD::SADDO:
12038     // A subtract of one will be selected as a INC. Note that INC doesn't
12039     // set CF, so we can't do this for UADDO.
12040     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12041       if (C->isOne()) {
12042         BaseOp = X86ISD::INC;
12043         Cond = X86::COND_O;
12044         break;
12045       }
12046     BaseOp = X86ISD::ADD;
12047     Cond = X86::COND_O;
12048     break;
12049   case ISD::UADDO:
12050     BaseOp = X86ISD::ADD;
12051     Cond = X86::COND_B;
12052     break;
12053   case ISD::SSUBO:
12054     // A subtract of one will be selected as a DEC. Note that DEC doesn't
12055     // set CF, so we can't do this for USUBO.
12056     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12057       if (C->isOne()) {
12058         BaseOp = X86ISD::DEC;
12059         Cond = X86::COND_O;
12060         break;
12061       }
12062     BaseOp = X86ISD::SUB;
12063     Cond = X86::COND_O;
12064     break;
12065   case ISD::USUBO:
12066     BaseOp = X86ISD::SUB;
12067     Cond = X86::COND_B;
12068     break;
12069   case ISD::SMULO:
12070     BaseOp = X86ISD::SMUL;
12071     Cond = X86::COND_O;
12072     break;
12073   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
12074     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
12075                                  MVT::i32);
12076     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
12077
12078     SDValue SetCC =
12079       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
12080                   DAG.getConstant(X86::COND_O, MVT::i32),
12081                   SDValue(Sum.getNode(), 2));
12082
12083     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12084   }
12085   }
12086
12087   // Also sets EFLAGS.
12088   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
12089   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
12090
12091   SDValue SetCC =
12092     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
12093                 DAG.getConstant(Cond, MVT::i32),
12094                 SDValue(Sum.getNode(), 1));
12095
12096   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
12097 }
12098
12099 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
12100                                                   SelectionDAG &DAG) const {
12101   SDLoc dl(Op);
12102   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
12103   EVT VT = Op.getValueType();
12104
12105   if (!Subtarget->hasSSE2() || !VT.isVector())
12106     return SDValue();
12107
12108   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
12109                       ExtraVT.getScalarType().getSizeInBits();
12110   SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
12111
12112   switch (VT.getSimpleVT().SimpleTy) {
12113     default: return SDValue();
12114     case MVT::v8i32:
12115     case MVT::v16i16:
12116       if (!Subtarget->hasFp256())
12117         return SDValue();
12118       if (!Subtarget->hasInt256()) {
12119         // needs to be split
12120         unsigned NumElems = VT.getVectorNumElements();
12121
12122         // Extract the LHS vectors
12123         SDValue LHS = Op.getOperand(0);
12124         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12125         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12126
12127         MVT EltVT = VT.getVectorElementType().getSimpleVT();
12128         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12129
12130         EVT ExtraEltVT = ExtraVT.getVectorElementType();
12131         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
12132         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
12133                                    ExtraNumElems/2);
12134         SDValue Extra = DAG.getValueType(ExtraVT);
12135
12136         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
12137         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
12138
12139         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
12140       }
12141       // fall through
12142     case MVT::v4i32:
12143     case MVT::v8i16: {
12144       // (sext (vzext x)) -> (vsext x)
12145       SDValue Op0 = Op.getOperand(0);
12146       SDValue Op00 = Op0.getOperand(0);
12147       SDValue Tmp1;
12148       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
12149       if (Op0.getOpcode() == ISD::BITCAST &&
12150           Op00.getOpcode() == ISD::VECTOR_SHUFFLE)
12151         Tmp1 = LowerVectorIntExtend(Op00, DAG);
12152       if (Tmp1.getNode()) {
12153         SDValue Tmp1Op0 = Tmp1.getOperand(0);
12154         assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
12155                "This optimization is invalid without a VZEXT.");
12156         return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
12157       }
12158
12159       // If the above didn't work, then just use Shift-Left + Shift-Right.
12160       Tmp1 = getTargetVShiftNode(X86ISD::VSHLI, dl, VT, Op0, ShAmt, DAG);
12161       return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, Tmp1, ShAmt, DAG);
12162     }
12163   }
12164 }
12165
12166 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
12167                                  SelectionDAG &DAG) {
12168   SDLoc dl(Op);
12169   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
12170     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
12171   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
12172     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
12173
12174   // The only fence that needs an instruction is a sequentially-consistent
12175   // cross-thread fence.
12176   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
12177     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
12178     // no-sse2). There isn't any reason to disable it if the target processor
12179     // supports it.
12180     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
12181       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
12182
12183     SDValue Chain = Op.getOperand(0);
12184     SDValue Zero = DAG.getConstant(0, MVT::i32);
12185     SDValue Ops[] = {
12186       DAG.getRegister(X86::ESP, MVT::i32), // Base
12187       DAG.getTargetConstant(1, MVT::i8),   // Scale
12188       DAG.getRegister(0, MVT::i32),        // Index
12189       DAG.getTargetConstant(0, MVT::i32),  // Disp
12190       DAG.getRegister(0, MVT::i32),        // Segment.
12191       Zero,
12192       Chain
12193     };
12194     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
12195     return SDValue(Res, 0);
12196   }
12197
12198   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
12199   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
12200 }
12201
12202 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
12203                              SelectionDAG &DAG) {
12204   EVT T = Op.getValueType();
12205   SDLoc DL(Op);
12206   unsigned Reg = 0;
12207   unsigned size = 0;
12208   switch(T.getSimpleVT().SimpleTy) {
12209   default: llvm_unreachable("Invalid value type!");
12210   case MVT::i8:  Reg = X86::AL;  size = 1; break;
12211   case MVT::i16: Reg = X86::AX;  size = 2; break;
12212   case MVT::i32: Reg = X86::EAX; size = 4; break;
12213   case MVT::i64:
12214     assert(Subtarget->is64Bit() && "Node not type legal!");
12215     Reg = X86::RAX; size = 8;
12216     break;
12217   }
12218   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
12219                                     Op.getOperand(2), SDValue());
12220   SDValue Ops[] = { cpIn.getValue(0),
12221                     Op.getOperand(1),
12222                     Op.getOperand(3),
12223                     DAG.getTargetConstant(size, MVT::i8),
12224                     cpIn.getValue(1) };
12225   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12226   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
12227   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
12228                                            Ops, array_lengthof(Ops), T, MMO);
12229   SDValue cpOut =
12230     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
12231   return cpOut;
12232 }
12233
12234 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12235                                      SelectionDAG &DAG) {
12236   assert(Subtarget->is64Bit() && "Result not type legalized?");
12237   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12238   SDValue TheChain = Op.getOperand(0);
12239   SDLoc dl(Op);
12240   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12241   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
12242   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
12243                                    rax.getValue(2));
12244   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
12245                             DAG.getConstant(32, MVT::i8));
12246   SDValue Ops[] = {
12247     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
12248     rdx.getValue(1)
12249   };
12250   return DAG.getMergeValues(Ops, array_lengthof(Ops), dl);
12251 }
12252
12253 SDValue X86TargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
12254   EVT SrcVT = Op.getOperand(0).getValueType();
12255   EVT DstVT = Op.getValueType();
12256   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
12257          Subtarget->hasMMX() && "Unexpected custom BITCAST");
12258   assert((DstVT == MVT::i64 ||
12259           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
12260          "Unexpected custom BITCAST");
12261   // i64 <=> MMX conversions are Legal.
12262   if (SrcVT==MVT::i64 && DstVT.isVector())
12263     return Op;
12264   if (DstVT==MVT::i64 && SrcVT.isVector())
12265     return Op;
12266   // MMX <=> MMX conversions are Legal.
12267   if (SrcVT.isVector() && DstVT.isVector())
12268     return Op;
12269   // All other conversions need to be expanded.
12270   return SDValue();
12271 }
12272
12273 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
12274   SDNode *Node = Op.getNode();
12275   SDLoc dl(Node);
12276   EVT T = Node->getValueType(0);
12277   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
12278                               DAG.getConstant(0, T), Node->getOperand(2));
12279   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
12280                        cast<AtomicSDNode>(Node)->getMemoryVT(),
12281                        Node->getOperand(0),
12282                        Node->getOperand(1), negOp,
12283                        cast<AtomicSDNode>(Node)->getSrcValue(),
12284                        cast<AtomicSDNode>(Node)->getAlignment(),
12285                        cast<AtomicSDNode>(Node)->getOrdering(),
12286                        cast<AtomicSDNode>(Node)->getSynchScope());
12287 }
12288
12289 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
12290   SDNode *Node = Op.getNode();
12291   SDLoc dl(Node);
12292   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12293
12294   // Convert seq_cst store -> xchg
12295   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
12296   // FIXME: On 32-bit, store -> fist or movq would be more efficient
12297   //        (The only way to get a 16-byte store is cmpxchg16b)
12298   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
12299   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
12300       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12301     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
12302                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
12303                                  Node->getOperand(0),
12304                                  Node->getOperand(1), Node->getOperand(2),
12305                                  cast<AtomicSDNode>(Node)->getMemOperand(),
12306                                  cast<AtomicSDNode>(Node)->getOrdering(),
12307                                  cast<AtomicSDNode>(Node)->getSynchScope());
12308     return Swap.getValue(1);
12309   }
12310   // Other atomic stores have a simple pattern.
12311   return Op;
12312 }
12313
12314 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
12315   EVT VT = Op.getNode()->getValueType(0);
12316
12317   // Let legalize expand this if it isn't a legal type yet.
12318   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12319     return SDValue();
12320
12321   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12322
12323   unsigned Opc;
12324   bool ExtraOp = false;
12325   switch (Op.getOpcode()) {
12326   default: llvm_unreachable("Invalid code");
12327   case ISD::ADDC: Opc = X86ISD::ADD; break;
12328   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
12329   case ISD::SUBC: Opc = X86ISD::SUB; break;
12330   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
12331   }
12332
12333   if (!ExtraOp)
12334     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12335                        Op.getOperand(1));
12336   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
12337                      Op.getOperand(1), Op.getOperand(2));
12338 }
12339
12340 SDValue X86TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
12341   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
12342
12343   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
12344   // which returns the values as { float, float } (in XMM0) or
12345   // { double, double } (which is returned in XMM0, XMM1).
12346   SDLoc dl(Op);
12347   SDValue Arg = Op.getOperand(0);
12348   EVT ArgVT = Arg.getValueType();
12349   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12350
12351   ArgListTy Args;
12352   ArgListEntry Entry;
12353
12354   Entry.Node = Arg;
12355   Entry.Ty = ArgTy;
12356   Entry.isSExt = false;
12357   Entry.isZExt = false;
12358   Args.push_back(Entry);
12359
12360   bool isF64 = ArgVT == MVT::f64;
12361   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
12362   // the small struct {f32, f32} is returned in (eax, edx). For f64,
12363   // the results are returned via SRet in memory.
12364   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
12365   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
12366
12367   Type *RetTy = isF64
12368     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
12369     : (Type*)VectorType::get(ArgTy, 4);
12370   TargetLowering::
12371     CallLoweringInfo CLI(DAG.getEntryNode(), RetTy,
12372                          false, false, false, false, 0,
12373                          CallingConv::C, /*isTaillCall=*/false,
12374                          /*doesNotRet=*/false, /*isReturnValueUsed*/true,
12375                          Callee, Args, DAG, dl);
12376   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12377
12378   if (isF64)
12379     // Returned in xmm0 and xmm1.
12380     return CallResult.first;
12381
12382   // Returned in bits 0:31 and 32:64 xmm0.
12383   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12384                                CallResult.first, DAG.getIntPtrConstant(0));
12385   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
12386                                CallResult.first, DAG.getIntPtrConstant(1));
12387   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
12388   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
12389 }
12390
12391 /// LowerOperation - Provide custom lowering hooks for some operations.
12392 ///
12393 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
12394   switch (Op.getOpcode()) {
12395   default: llvm_unreachable("Should not custom lower this!");
12396   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
12397   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
12398   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
12399   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
12400   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
12401   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
12402   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
12403   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
12404   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
12405   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
12406   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
12407   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
12408   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
12409   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
12410   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
12411   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
12412   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
12413   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
12414   case ISD::SHL_PARTS:
12415   case ISD::SRA_PARTS:
12416   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
12417   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
12418   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
12419   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
12420   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, DAG);
12421   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, DAG);
12422   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, DAG);
12423   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
12424   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
12425   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
12426   case ISD::FABS:               return LowerFABS(Op, DAG);
12427   case ISD::FNEG:               return LowerFNEG(Op, DAG);
12428   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
12429   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
12430   case ISD::SETCC:              return LowerSETCC(Op, DAG);
12431   case ISD::SELECT:             return LowerSELECT(Op, DAG);
12432   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
12433   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
12434   case ISD::VASTART:            return LowerVASTART(Op, DAG);
12435   case ISD::VAARG:              return LowerVAARG(Op, DAG);
12436   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
12437   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
12438   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
12439   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
12440   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
12441   case ISD::FRAME_TO_ARGS_OFFSET:
12442                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
12443   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
12444   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
12445   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
12446   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
12447   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
12448   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
12449   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
12450   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
12451   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
12452   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
12453   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
12454   case ISD::SRA:
12455   case ISD::SRL:
12456   case ISD::SHL:                return LowerShift(Op, DAG);
12457   case ISD::SADDO:
12458   case ISD::UADDO:
12459   case ISD::SSUBO:
12460   case ISD::USUBO:
12461   case ISD::SMULO:
12462   case ISD::UMULO:              return LowerXALUO(Op, DAG);
12463   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
12464   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
12465   case ISD::ADDC:
12466   case ISD::ADDE:
12467   case ISD::SUBC:
12468   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
12469   case ISD::ADD:                return LowerADD(Op, DAG);
12470   case ISD::SUB:                return LowerSUB(Op, DAG);
12471   case ISD::SDIV:               return LowerSDIV(Op, DAG);
12472   case ISD::FSINCOS:            return LowerFSINCOS(Op, DAG);
12473   }
12474 }
12475
12476 static void ReplaceATOMIC_LOAD(SDNode *Node,
12477                                   SmallVectorImpl<SDValue> &Results,
12478                                   SelectionDAG &DAG) {
12479   SDLoc dl(Node);
12480   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
12481
12482   // Convert wide load -> cmpxchg8b/cmpxchg16b
12483   // FIXME: On 32-bit, load -> fild or movq would be more efficient
12484   //        (The only way to get a 16-byte load is cmpxchg16b)
12485   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
12486   SDValue Zero = DAG.getConstant(0, VT);
12487   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
12488                                Node->getOperand(0),
12489                                Node->getOperand(1), Zero, Zero,
12490                                cast<AtomicSDNode>(Node)->getMemOperand(),
12491                                cast<AtomicSDNode>(Node)->getOrdering(),
12492                                cast<AtomicSDNode>(Node)->getSynchScope());
12493   Results.push_back(Swap.getValue(0));
12494   Results.push_back(Swap.getValue(1));
12495 }
12496
12497 static void
12498 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
12499                         SelectionDAG &DAG, unsigned NewOp) {
12500   SDLoc dl(Node);
12501   assert (Node->getValueType(0) == MVT::i64 &&
12502           "Only know how to expand i64 atomics");
12503
12504   SDValue Chain = Node->getOperand(0);
12505   SDValue In1 = Node->getOperand(1);
12506   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12507                              Node->getOperand(2), DAG.getIntPtrConstant(0));
12508   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
12509                              Node->getOperand(2), DAG.getIntPtrConstant(1));
12510   SDValue Ops[] = { Chain, In1, In2L, In2H };
12511   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
12512   SDValue Result =
12513     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, array_lengthof(Ops), MVT::i64,
12514                             cast<MemSDNode>(Node)->getMemOperand());
12515   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
12516   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
12517   Results.push_back(Result.getValue(2));
12518 }
12519
12520 /// ReplaceNodeResults - Replace a node with an illegal result type
12521 /// with a new node built out of custom code.
12522 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
12523                                            SmallVectorImpl<SDValue>&Results,
12524                                            SelectionDAG &DAG) const {
12525   SDLoc dl(N);
12526   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12527   switch (N->getOpcode()) {
12528   default:
12529     llvm_unreachable("Do not know how to custom type legalize this operation!");
12530   case ISD::SIGN_EXTEND_INREG:
12531   case ISD::ADDC:
12532   case ISD::ADDE:
12533   case ISD::SUBC:
12534   case ISD::SUBE:
12535     // We don't want to expand or promote these.
12536     return;
12537   case ISD::FP_TO_SINT:
12538   case ISD::FP_TO_UINT: {
12539     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
12540
12541     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
12542       return;
12543
12544     std::pair<SDValue,SDValue> Vals =
12545         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
12546     SDValue FIST = Vals.first, StackSlot = Vals.second;
12547     if (FIST.getNode() != 0) {
12548       EVT VT = N->getValueType(0);
12549       // Return a load from the stack slot.
12550       if (StackSlot.getNode() != 0)
12551         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
12552                                       MachinePointerInfo(),
12553                                       false, false, false, 0));
12554       else
12555         Results.push_back(FIST);
12556     }
12557     return;
12558   }
12559   case ISD::UINT_TO_FP: {
12560     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
12561     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
12562         N->getValueType(0) != MVT::v2f32)
12563       return;
12564     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
12565                                  N->getOperand(0));
12566     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12567                                      MVT::f64);
12568     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
12569     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
12570                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
12571     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
12572     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
12573     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
12574     return;
12575   }
12576   case ISD::FP_ROUND: {
12577     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
12578         return;
12579     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
12580     Results.push_back(V);
12581     return;
12582   }
12583   case ISD::READCYCLECOUNTER: {
12584     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12585     SDValue TheChain = N->getOperand(0);
12586     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
12587     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
12588                                      rd.getValue(1));
12589     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
12590                                      eax.getValue(2));
12591     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12592     SDValue Ops[] = { eax, edx };
12593     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops,
12594                                   array_lengthof(Ops)));
12595     Results.push_back(edx.getValue(1));
12596     return;
12597   }
12598   case ISD::ATOMIC_CMP_SWAP: {
12599     EVT T = N->getValueType(0);
12600     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
12601     bool Regs64bit = T == MVT::i128;
12602     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
12603     SDValue cpInL, cpInH;
12604     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12605                         DAG.getConstant(0, HalfT));
12606     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
12607                         DAG.getConstant(1, HalfT));
12608     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
12609                              Regs64bit ? X86::RAX : X86::EAX,
12610                              cpInL, SDValue());
12611     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
12612                              Regs64bit ? X86::RDX : X86::EDX,
12613                              cpInH, cpInL.getValue(1));
12614     SDValue swapInL, swapInH;
12615     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12616                           DAG.getConstant(0, HalfT));
12617     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
12618                           DAG.getConstant(1, HalfT));
12619     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
12620                                Regs64bit ? X86::RBX : X86::EBX,
12621                                swapInL, cpInH.getValue(1));
12622     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
12623                                Regs64bit ? X86::RCX : X86::ECX,
12624                                swapInH, swapInL.getValue(1));
12625     SDValue Ops[] = { swapInH.getValue(0),
12626                       N->getOperand(1),
12627                       swapInH.getValue(1) };
12628     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12629     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
12630     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
12631                                   X86ISD::LCMPXCHG8_DAG;
12632     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
12633                                              Ops, array_lengthof(Ops), T, MMO);
12634     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
12635                                         Regs64bit ? X86::RAX : X86::EAX,
12636                                         HalfT, Result.getValue(1));
12637     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
12638                                         Regs64bit ? X86::RDX : X86::EDX,
12639                                         HalfT, cpOutL.getValue(2));
12640     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
12641     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
12642     Results.push_back(cpOutH.getValue(1));
12643     return;
12644   }
12645   case ISD::ATOMIC_LOAD_ADD:
12646   case ISD::ATOMIC_LOAD_AND:
12647   case ISD::ATOMIC_LOAD_NAND:
12648   case ISD::ATOMIC_LOAD_OR:
12649   case ISD::ATOMIC_LOAD_SUB:
12650   case ISD::ATOMIC_LOAD_XOR:
12651   case ISD::ATOMIC_LOAD_MAX:
12652   case ISD::ATOMIC_LOAD_MIN:
12653   case ISD::ATOMIC_LOAD_UMAX:
12654   case ISD::ATOMIC_LOAD_UMIN:
12655   case ISD::ATOMIC_SWAP: {
12656     unsigned Opc;
12657     switch (N->getOpcode()) {
12658     default: llvm_unreachable("Unexpected opcode");
12659     case ISD::ATOMIC_LOAD_ADD:
12660       Opc = X86ISD::ATOMADD64_DAG;
12661       break;
12662     case ISD::ATOMIC_LOAD_AND:
12663       Opc = X86ISD::ATOMAND64_DAG;
12664       break;
12665     case ISD::ATOMIC_LOAD_NAND:
12666       Opc = X86ISD::ATOMNAND64_DAG;
12667       break;
12668     case ISD::ATOMIC_LOAD_OR:
12669       Opc = X86ISD::ATOMOR64_DAG;
12670       break;
12671     case ISD::ATOMIC_LOAD_SUB:
12672       Opc = X86ISD::ATOMSUB64_DAG;
12673       break;
12674     case ISD::ATOMIC_LOAD_XOR:
12675       Opc = X86ISD::ATOMXOR64_DAG;
12676       break;
12677     case ISD::ATOMIC_LOAD_MAX:
12678       Opc = X86ISD::ATOMMAX64_DAG;
12679       break;
12680     case ISD::ATOMIC_LOAD_MIN:
12681       Opc = X86ISD::ATOMMIN64_DAG;
12682       break;
12683     case ISD::ATOMIC_LOAD_UMAX:
12684       Opc = X86ISD::ATOMUMAX64_DAG;
12685       break;
12686     case ISD::ATOMIC_LOAD_UMIN:
12687       Opc = X86ISD::ATOMUMIN64_DAG;
12688       break;
12689     case ISD::ATOMIC_SWAP:
12690       Opc = X86ISD::ATOMSWAP64_DAG;
12691       break;
12692     }
12693     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
12694     return;
12695   }
12696   case ISD::ATOMIC_LOAD:
12697     ReplaceATOMIC_LOAD(N, Results, DAG);
12698   }
12699 }
12700
12701 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
12702   switch (Opcode) {
12703   default: return NULL;
12704   case X86ISD::BSF:                return "X86ISD::BSF";
12705   case X86ISD::BSR:                return "X86ISD::BSR";
12706   case X86ISD::SHLD:               return "X86ISD::SHLD";
12707   case X86ISD::SHRD:               return "X86ISD::SHRD";
12708   case X86ISD::FAND:               return "X86ISD::FAND";
12709   case X86ISD::FOR:                return "X86ISD::FOR";
12710   case X86ISD::FXOR:               return "X86ISD::FXOR";
12711   case X86ISD::FSRL:               return "X86ISD::FSRL";
12712   case X86ISD::FILD:               return "X86ISD::FILD";
12713   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
12714   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
12715   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
12716   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
12717   case X86ISD::FLD:                return "X86ISD::FLD";
12718   case X86ISD::FST:                return "X86ISD::FST";
12719   case X86ISD::CALL:               return "X86ISD::CALL";
12720   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
12721   case X86ISD::BT:                 return "X86ISD::BT";
12722   case X86ISD::CMP:                return "X86ISD::CMP";
12723   case X86ISD::COMI:               return "X86ISD::COMI";
12724   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
12725   case X86ISD::SETCC:              return "X86ISD::SETCC";
12726   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
12727   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
12728   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
12729   case X86ISD::CMOV:               return "X86ISD::CMOV";
12730   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
12731   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
12732   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
12733   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
12734   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
12735   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
12736   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
12737   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
12738   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
12739   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
12740   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
12741   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
12742   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
12743   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
12744   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
12745   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
12746   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
12747   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
12748   case X86ISD::HADD:               return "X86ISD::HADD";
12749   case X86ISD::HSUB:               return "X86ISD::HSUB";
12750   case X86ISD::FHADD:              return "X86ISD::FHADD";
12751   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
12752   case X86ISD::UMAX:               return "X86ISD::UMAX";
12753   case X86ISD::UMIN:               return "X86ISD::UMIN";
12754   case X86ISD::SMAX:               return "X86ISD::SMAX";
12755   case X86ISD::SMIN:               return "X86ISD::SMIN";
12756   case X86ISD::FMAX:               return "X86ISD::FMAX";
12757   case X86ISD::FMIN:               return "X86ISD::FMIN";
12758   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
12759   case X86ISD::FMINC:              return "X86ISD::FMINC";
12760   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
12761   case X86ISD::FRCP:               return "X86ISD::FRCP";
12762   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
12763   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
12764   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
12765   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
12766   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
12767   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
12768   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
12769   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
12770   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
12771   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
12772   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
12773   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
12774   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
12775   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
12776   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
12777   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
12778   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
12779   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
12780   case X86ISD::VSEXT_MOVL:         return "X86ISD::VSEXT_MOVL";
12781   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
12782   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
12783   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
12784   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
12785   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
12786   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
12787   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
12788   case X86ISD::VSHL:               return "X86ISD::VSHL";
12789   case X86ISD::VSRL:               return "X86ISD::VSRL";
12790   case X86ISD::VSRA:               return "X86ISD::VSRA";
12791   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
12792   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
12793   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
12794   case X86ISD::CMPP:               return "X86ISD::CMPP";
12795   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
12796   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
12797   case X86ISD::ADD:                return "X86ISD::ADD";
12798   case X86ISD::SUB:                return "X86ISD::SUB";
12799   case X86ISD::ADC:                return "X86ISD::ADC";
12800   case X86ISD::SBB:                return "X86ISD::SBB";
12801   case X86ISD::SMUL:               return "X86ISD::SMUL";
12802   case X86ISD::UMUL:               return "X86ISD::UMUL";
12803   case X86ISD::INC:                return "X86ISD::INC";
12804   case X86ISD::DEC:                return "X86ISD::DEC";
12805   case X86ISD::OR:                 return "X86ISD::OR";
12806   case X86ISD::XOR:                return "X86ISD::XOR";
12807   case X86ISD::AND:                return "X86ISD::AND";
12808   case X86ISD::BLSI:               return "X86ISD::BLSI";
12809   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
12810   case X86ISD::BLSR:               return "X86ISD::BLSR";
12811   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
12812   case X86ISD::PTEST:              return "X86ISD::PTEST";
12813   case X86ISD::TESTP:              return "X86ISD::TESTP";
12814   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
12815   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
12816   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
12817   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
12818   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
12819   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
12820   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
12821   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
12822   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
12823   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
12824   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
12825   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
12826   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
12827   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
12828   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
12829   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
12830   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
12831   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
12832   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
12833   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
12834   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
12835   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
12836   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
12837   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
12838   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
12839   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
12840   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
12841   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
12842   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
12843   case X86ISD::SAHF:               return "X86ISD::SAHF";
12844   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
12845   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
12846   case X86ISD::FMADD:              return "X86ISD::FMADD";
12847   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
12848   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
12849   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
12850   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
12851   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
12852   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
12853   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
12854   case X86ISD::XTEST:              return "X86ISD::XTEST";
12855   }
12856 }
12857
12858 // isLegalAddressingMode - Return true if the addressing mode represented
12859 // by AM is legal for this target, for a load/store of the specified type.
12860 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
12861                                               Type *Ty) const {
12862   // X86 supports extremely general addressing modes.
12863   CodeModel::Model M = getTargetMachine().getCodeModel();
12864   Reloc::Model R = getTargetMachine().getRelocationModel();
12865
12866   // X86 allows a sign-extended 32-bit immediate field as a displacement.
12867   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
12868     return false;
12869
12870   if (AM.BaseGV) {
12871     unsigned GVFlags =
12872       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
12873
12874     // If a reference to this global requires an extra load, we can't fold it.
12875     if (isGlobalStubReference(GVFlags))
12876       return false;
12877
12878     // If BaseGV requires a register for the PIC base, we cannot also have a
12879     // BaseReg specified.
12880     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
12881       return false;
12882
12883     // If lower 4G is not available, then we must use rip-relative addressing.
12884     if ((M != CodeModel::Small || R != Reloc::Static) &&
12885         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
12886       return false;
12887   }
12888
12889   switch (AM.Scale) {
12890   case 0:
12891   case 1:
12892   case 2:
12893   case 4:
12894   case 8:
12895     // These scales always work.
12896     break;
12897   case 3:
12898   case 5:
12899   case 9:
12900     // These scales are formed with basereg+scalereg.  Only accept if there is
12901     // no basereg yet.
12902     if (AM.HasBaseReg)
12903       return false;
12904     break;
12905   default:  // Other stuff never works.
12906     return false;
12907   }
12908
12909   return true;
12910 }
12911
12912 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12913   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12914     return false;
12915   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12916   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12917   return NumBits1 > NumBits2;
12918 }
12919
12920 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12921   return isInt<32>(Imm);
12922 }
12923
12924 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
12925   // Can also use sub to handle negated immediates.
12926   return isInt<32>(Imm);
12927 }
12928
12929 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12930   if (!VT1.isInteger() || !VT2.isInteger())
12931     return false;
12932   unsigned NumBits1 = VT1.getSizeInBits();
12933   unsigned NumBits2 = VT2.getSizeInBits();
12934   return NumBits1 > NumBits2;
12935 }
12936
12937 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
12938   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12939   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
12940 }
12941
12942 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
12943   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
12944   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
12945 }
12946
12947 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12948   EVT VT1 = Val.getValueType();
12949   if (isZExtFree(VT1, VT2))
12950     return true;
12951
12952   if (Val.getOpcode() != ISD::LOAD)
12953     return false;
12954
12955   if (!VT1.isSimple() || !VT1.isInteger() ||
12956       !VT2.isSimple() || !VT2.isInteger())
12957     return false;
12958
12959   switch (VT1.getSimpleVT().SimpleTy) {
12960   default: break;
12961   case MVT::i8:
12962   case MVT::i16:
12963   case MVT::i32:
12964     // X86 has 8, 16, and 32-bit zero-extending loads.
12965     return true;
12966   }
12967
12968   return false;
12969 }
12970
12971 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
12972   // i16 instructions are longer (0x66 prefix) and potentially slower.
12973   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
12974 }
12975
12976 /// isShuffleMaskLegal - Targets can use this to indicate that they only
12977 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
12978 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
12979 /// are assumed to be legal.
12980 bool
12981 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
12982                                       EVT VT) const {
12983   // Very little shuffling can be done for 64-bit vectors right now.
12984   if (VT.getSizeInBits() == 64)
12985     return false;
12986
12987   // FIXME: pshufb, blends, shifts.
12988   return (VT.getVectorNumElements() == 2 ||
12989           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
12990           isMOVLMask(M, VT) ||
12991           isSHUFPMask(M, VT, Subtarget->hasFp256()) ||
12992           isPSHUFDMask(M, VT) ||
12993           isPSHUFHWMask(M, VT, Subtarget->hasInt256()) ||
12994           isPSHUFLWMask(M, VT, Subtarget->hasInt256()) ||
12995           isPALIGNRMask(M, VT, Subtarget) ||
12996           isUNPCKLMask(M, VT, Subtarget->hasInt256()) ||
12997           isUNPCKHMask(M, VT, Subtarget->hasInt256()) ||
12998           isUNPCKL_v_undef_Mask(M, VT, Subtarget->hasInt256()) ||
12999           isUNPCKH_v_undef_Mask(M, VT, Subtarget->hasInt256()));
13000 }
13001
13002 bool
13003 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
13004                                           EVT VT) const {
13005   unsigned NumElts = VT.getVectorNumElements();
13006   // FIXME: This collection of masks seems suspect.
13007   if (NumElts == 2)
13008     return true;
13009   if (NumElts == 4 && VT.is128BitVector()) {
13010     return (isMOVLMask(Mask, VT)  ||
13011             isCommutedMOVLMask(Mask, VT, true) ||
13012             isSHUFPMask(Mask, VT, Subtarget->hasFp256()) ||
13013             isSHUFPMask(Mask, VT, Subtarget->hasFp256(), /* Commuted */ true));
13014   }
13015   return false;
13016 }
13017
13018 //===----------------------------------------------------------------------===//
13019 //                           X86 Scheduler Hooks
13020 //===----------------------------------------------------------------------===//
13021
13022 /// Utility function to emit xbegin specifying the start of an RTM region.
13023 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
13024                                      const TargetInstrInfo *TII) {
13025   DebugLoc DL = MI->getDebugLoc();
13026
13027   const BasicBlock *BB = MBB->getBasicBlock();
13028   MachineFunction::iterator I = MBB;
13029   ++I;
13030
13031   // For the v = xbegin(), we generate
13032   //
13033   // thisMBB:
13034   //  xbegin sinkMBB
13035   //
13036   // mainMBB:
13037   //  eax = -1
13038   //
13039   // sinkMBB:
13040   //  v = eax
13041
13042   MachineBasicBlock *thisMBB = MBB;
13043   MachineFunction *MF = MBB->getParent();
13044   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13045   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13046   MF->insert(I, mainMBB);
13047   MF->insert(I, sinkMBB);
13048
13049   // Transfer the remainder of BB and its successor edges to sinkMBB.
13050   sinkMBB->splice(sinkMBB->begin(), MBB,
13051                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13052   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13053
13054   // thisMBB:
13055   //  xbegin sinkMBB
13056   //  # fallthrough to mainMBB
13057   //  # abortion to sinkMBB
13058   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
13059   thisMBB->addSuccessor(mainMBB);
13060   thisMBB->addSuccessor(sinkMBB);
13061
13062   // mainMBB:
13063   //  EAX = -1
13064   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
13065   mainMBB->addSuccessor(sinkMBB);
13066
13067   // sinkMBB:
13068   // EAX is live into the sinkMBB
13069   sinkMBB->addLiveIn(X86::EAX);
13070   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13071           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13072     .addReg(X86::EAX);
13073
13074   MI->eraseFromParent();
13075   return sinkMBB;
13076 }
13077
13078 // Get CMPXCHG opcode for the specified data type.
13079 static unsigned getCmpXChgOpcode(EVT VT) {
13080   switch (VT.getSimpleVT().SimpleTy) {
13081   case MVT::i8:  return X86::LCMPXCHG8;
13082   case MVT::i16: return X86::LCMPXCHG16;
13083   case MVT::i32: return X86::LCMPXCHG32;
13084   case MVT::i64: return X86::LCMPXCHG64;
13085   default:
13086     break;
13087   }
13088   llvm_unreachable("Invalid operand size!");
13089 }
13090
13091 // Get LOAD opcode for the specified data type.
13092 static unsigned getLoadOpcode(EVT VT) {
13093   switch (VT.getSimpleVT().SimpleTy) {
13094   case MVT::i8:  return X86::MOV8rm;
13095   case MVT::i16: return X86::MOV16rm;
13096   case MVT::i32: return X86::MOV32rm;
13097   case MVT::i64: return X86::MOV64rm;
13098   default:
13099     break;
13100   }
13101   llvm_unreachable("Invalid operand size!");
13102 }
13103
13104 // Get opcode of the non-atomic one from the specified atomic instruction.
13105 static unsigned getNonAtomicOpcode(unsigned Opc) {
13106   switch (Opc) {
13107   case X86::ATOMAND8:  return X86::AND8rr;
13108   case X86::ATOMAND16: return X86::AND16rr;
13109   case X86::ATOMAND32: return X86::AND32rr;
13110   case X86::ATOMAND64: return X86::AND64rr;
13111   case X86::ATOMOR8:   return X86::OR8rr;
13112   case X86::ATOMOR16:  return X86::OR16rr;
13113   case X86::ATOMOR32:  return X86::OR32rr;
13114   case X86::ATOMOR64:  return X86::OR64rr;
13115   case X86::ATOMXOR8:  return X86::XOR8rr;
13116   case X86::ATOMXOR16: return X86::XOR16rr;
13117   case X86::ATOMXOR32: return X86::XOR32rr;
13118   case X86::ATOMXOR64: return X86::XOR64rr;
13119   }
13120   llvm_unreachable("Unhandled atomic-load-op opcode!");
13121 }
13122
13123 // Get opcode of the non-atomic one from the specified atomic instruction with
13124 // extra opcode.
13125 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
13126                                                unsigned &ExtraOpc) {
13127   switch (Opc) {
13128   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
13129   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
13130   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
13131   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
13132   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
13133   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
13134   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
13135   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
13136   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
13137   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
13138   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
13139   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
13140   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
13141   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
13142   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
13143   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
13144   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
13145   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
13146   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
13147   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
13148   }
13149   llvm_unreachable("Unhandled atomic-load-op opcode!");
13150 }
13151
13152 // Get opcode of the non-atomic one from the specified atomic instruction for
13153 // 64-bit data type on 32-bit target.
13154 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
13155   switch (Opc) {
13156   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
13157   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
13158   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
13159   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
13160   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
13161   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
13162   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
13163   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
13164   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
13165   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
13166   }
13167   llvm_unreachable("Unhandled atomic-load-op opcode!");
13168 }
13169
13170 // Get opcode of the non-atomic one from the specified atomic instruction for
13171 // 64-bit data type on 32-bit target with extra opcode.
13172 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
13173                                                    unsigned &HiOpc,
13174                                                    unsigned &ExtraOpc) {
13175   switch (Opc) {
13176   case X86::ATOMNAND6432:
13177     ExtraOpc = X86::NOT32r;
13178     HiOpc = X86::AND32rr;
13179     return X86::AND32rr;
13180   }
13181   llvm_unreachable("Unhandled atomic-load-op opcode!");
13182 }
13183
13184 // Get pseudo CMOV opcode from the specified data type.
13185 static unsigned getPseudoCMOVOpc(EVT VT) {
13186   switch (VT.getSimpleVT().SimpleTy) {
13187   case MVT::i8:  return X86::CMOV_GR8;
13188   case MVT::i16: return X86::CMOV_GR16;
13189   case MVT::i32: return X86::CMOV_GR32;
13190   default:
13191     break;
13192   }
13193   llvm_unreachable("Unknown CMOV opcode!");
13194 }
13195
13196 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
13197 // They will be translated into a spin-loop or compare-exchange loop from
13198 //
13199 //    ...
13200 //    dst = atomic-fetch-op MI.addr, MI.val
13201 //    ...
13202 //
13203 // to
13204 //
13205 //    ...
13206 //    t1 = LOAD MI.addr
13207 // loop:
13208 //    t4 = phi(t1, t3 / loop)
13209 //    t2 = OP MI.val, t4
13210 //    EAX = t4
13211 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
13212 //    t3 = EAX
13213 //    JNE loop
13214 // sink:
13215 //    dst = t3
13216 //    ...
13217 MachineBasicBlock *
13218 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
13219                                        MachineBasicBlock *MBB) const {
13220   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13221   DebugLoc DL = MI->getDebugLoc();
13222
13223   MachineFunction *MF = MBB->getParent();
13224   MachineRegisterInfo &MRI = MF->getRegInfo();
13225
13226   const BasicBlock *BB = MBB->getBasicBlock();
13227   MachineFunction::iterator I = MBB;
13228   ++I;
13229
13230   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
13231          "Unexpected number of operands");
13232
13233   assert(MI->hasOneMemOperand() &&
13234          "Expected atomic-load-op to have one memoperand");
13235
13236   // Memory Reference
13237   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13238   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13239
13240   unsigned DstReg, SrcReg;
13241   unsigned MemOpndSlot;
13242
13243   unsigned CurOp = 0;
13244
13245   DstReg = MI->getOperand(CurOp++).getReg();
13246   MemOpndSlot = CurOp;
13247   CurOp += X86::AddrNumOperands;
13248   SrcReg = MI->getOperand(CurOp++).getReg();
13249
13250   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
13251   MVT::SimpleValueType VT = *RC->vt_begin();
13252   unsigned t1 = MRI.createVirtualRegister(RC);
13253   unsigned t2 = MRI.createVirtualRegister(RC);
13254   unsigned t3 = MRI.createVirtualRegister(RC);
13255   unsigned t4 = MRI.createVirtualRegister(RC);
13256   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
13257
13258   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
13259   unsigned LOADOpc = getLoadOpcode(VT);
13260
13261   // For the atomic load-arith operator, we generate
13262   //
13263   //  thisMBB:
13264   //    t1 = LOAD [MI.addr]
13265   //  mainMBB:
13266   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
13267   //    t1 = OP MI.val, EAX
13268   //    EAX = t4
13269   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
13270   //    t3 = EAX
13271   //    JNE mainMBB
13272   //  sinkMBB:
13273   //    dst = t3
13274
13275   MachineBasicBlock *thisMBB = MBB;
13276   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13277   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13278   MF->insert(I, mainMBB);
13279   MF->insert(I, sinkMBB);
13280
13281   MachineInstrBuilder MIB;
13282
13283   // Transfer the remainder of BB and its successor edges to sinkMBB.
13284   sinkMBB->splice(sinkMBB->begin(), MBB,
13285                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13286   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13287
13288   // thisMBB:
13289   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
13290   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13291     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13292     if (NewMO.isReg())
13293       NewMO.setIsKill(false);
13294     MIB.addOperand(NewMO);
13295   }
13296   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13297     unsigned flags = (*MMOI)->getFlags();
13298     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13299     MachineMemOperand *MMO =
13300       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13301                                (*MMOI)->getSize(),
13302                                (*MMOI)->getBaseAlignment(),
13303                                (*MMOI)->getTBAAInfo(),
13304                                (*MMOI)->getRanges());
13305     MIB.addMemOperand(MMO);
13306   }
13307
13308   thisMBB->addSuccessor(mainMBB);
13309
13310   // mainMBB:
13311   MachineBasicBlock *origMainMBB = mainMBB;
13312
13313   // Add a PHI.
13314   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
13315                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13316
13317   unsigned Opc = MI->getOpcode();
13318   switch (Opc) {
13319   default:
13320     llvm_unreachable("Unhandled atomic-load-op opcode!");
13321   case X86::ATOMAND8:
13322   case X86::ATOMAND16:
13323   case X86::ATOMAND32:
13324   case X86::ATOMAND64:
13325   case X86::ATOMOR8:
13326   case X86::ATOMOR16:
13327   case X86::ATOMOR32:
13328   case X86::ATOMOR64:
13329   case X86::ATOMXOR8:
13330   case X86::ATOMXOR16:
13331   case X86::ATOMXOR32:
13332   case X86::ATOMXOR64: {
13333     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
13334     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
13335       .addReg(t4);
13336     break;
13337   }
13338   case X86::ATOMNAND8:
13339   case X86::ATOMNAND16:
13340   case X86::ATOMNAND32:
13341   case X86::ATOMNAND64: {
13342     unsigned Tmp = MRI.createVirtualRegister(RC);
13343     unsigned NOTOpc;
13344     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
13345     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
13346       .addReg(t4);
13347     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
13348     break;
13349   }
13350   case X86::ATOMMAX8:
13351   case X86::ATOMMAX16:
13352   case X86::ATOMMAX32:
13353   case X86::ATOMMAX64:
13354   case X86::ATOMMIN8:
13355   case X86::ATOMMIN16:
13356   case X86::ATOMMIN32:
13357   case X86::ATOMMIN64:
13358   case X86::ATOMUMAX8:
13359   case X86::ATOMUMAX16:
13360   case X86::ATOMUMAX32:
13361   case X86::ATOMUMAX64:
13362   case X86::ATOMUMIN8:
13363   case X86::ATOMUMIN16:
13364   case X86::ATOMUMIN32:
13365   case X86::ATOMUMIN64: {
13366     unsigned CMPOpc;
13367     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
13368
13369     BuildMI(mainMBB, DL, TII->get(CMPOpc))
13370       .addReg(SrcReg)
13371       .addReg(t4);
13372
13373     if (Subtarget->hasCMov()) {
13374       if (VT != MVT::i8) {
13375         // Native support
13376         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
13377           .addReg(SrcReg)
13378           .addReg(t4);
13379       } else {
13380         // Promote i8 to i32 to use CMOV32
13381         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13382         const TargetRegisterClass *RC32 =
13383           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
13384         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
13385         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
13386         unsigned Tmp = MRI.createVirtualRegister(RC32);
13387
13388         unsigned Undef = MRI.createVirtualRegister(RC32);
13389         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
13390
13391         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
13392           .addReg(Undef)
13393           .addReg(SrcReg)
13394           .addImm(X86::sub_8bit);
13395         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
13396           .addReg(Undef)
13397           .addReg(t4)
13398           .addImm(X86::sub_8bit);
13399
13400         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
13401           .addReg(SrcReg32)
13402           .addReg(AccReg32);
13403
13404         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
13405           .addReg(Tmp, 0, X86::sub_8bit);
13406       }
13407     } else {
13408       // Use pseudo select and lower them.
13409       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
13410              "Invalid atomic-load-op transformation!");
13411       unsigned SelOpc = getPseudoCMOVOpc(VT);
13412       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
13413       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
13414       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
13415               .addReg(SrcReg).addReg(t4)
13416               .addImm(CC);
13417       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13418       // Replace the original PHI node as mainMBB is changed after CMOV
13419       // lowering.
13420       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
13421         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
13422       Phi->eraseFromParent();
13423     }
13424     break;
13425   }
13426   }
13427
13428   // Copy PhyReg back from virtual register.
13429   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
13430     .addReg(t4);
13431
13432   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13433   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13434     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13435     if (NewMO.isReg())
13436       NewMO.setIsKill(false);
13437     MIB.addOperand(NewMO);
13438   }
13439   MIB.addReg(t2);
13440   MIB.setMemRefs(MMOBegin, MMOEnd);
13441
13442   // Copy PhyReg back to virtual register.
13443   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
13444     .addReg(PhyReg);
13445
13446   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13447
13448   mainMBB->addSuccessor(origMainMBB);
13449   mainMBB->addSuccessor(sinkMBB);
13450
13451   // sinkMBB:
13452   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13453           TII->get(TargetOpcode::COPY), DstReg)
13454     .addReg(t3);
13455
13456   MI->eraseFromParent();
13457   return sinkMBB;
13458 }
13459
13460 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
13461 // instructions. They will be translated into a spin-loop or compare-exchange
13462 // loop from
13463 //
13464 //    ...
13465 //    dst = atomic-fetch-op MI.addr, MI.val
13466 //    ...
13467 //
13468 // to
13469 //
13470 //    ...
13471 //    t1L = LOAD [MI.addr + 0]
13472 //    t1H = LOAD [MI.addr + 4]
13473 // loop:
13474 //    t4L = phi(t1L, t3L / loop)
13475 //    t4H = phi(t1H, t3H / loop)
13476 //    t2L = OP MI.val.lo, t4L
13477 //    t2H = OP MI.val.hi, t4H
13478 //    EAX = t4L
13479 //    EDX = t4H
13480 //    EBX = t2L
13481 //    ECX = t2H
13482 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13483 //    t3L = EAX
13484 //    t3H = EDX
13485 //    JNE loop
13486 // sink:
13487 //    dstL = t3L
13488 //    dstH = t3H
13489 //    ...
13490 MachineBasicBlock *
13491 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
13492                                            MachineBasicBlock *MBB) const {
13493   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13494   DebugLoc DL = MI->getDebugLoc();
13495
13496   MachineFunction *MF = MBB->getParent();
13497   MachineRegisterInfo &MRI = MF->getRegInfo();
13498
13499   const BasicBlock *BB = MBB->getBasicBlock();
13500   MachineFunction::iterator I = MBB;
13501   ++I;
13502
13503   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
13504          "Unexpected number of operands");
13505
13506   assert(MI->hasOneMemOperand() &&
13507          "Expected atomic-load-op32 to have one memoperand");
13508
13509   // Memory Reference
13510   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13511   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13512
13513   unsigned DstLoReg, DstHiReg;
13514   unsigned SrcLoReg, SrcHiReg;
13515   unsigned MemOpndSlot;
13516
13517   unsigned CurOp = 0;
13518
13519   DstLoReg = MI->getOperand(CurOp++).getReg();
13520   DstHiReg = MI->getOperand(CurOp++).getReg();
13521   MemOpndSlot = CurOp;
13522   CurOp += X86::AddrNumOperands;
13523   SrcLoReg = MI->getOperand(CurOp++).getReg();
13524   SrcHiReg = MI->getOperand(CurOp++).getReg();
13525
13526   const TargetRegisterClass *RC = &X86::GR32RegClass;
13527   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
13528
13529   unsigned t1L = MRI.createVirtualRegister(RC);
13530   unsigned t1H = MRI.createVirtualRegister(RC);
13531   unsigned t2L = MRI.createVirtualRegister(RC);
13532   unsigned t2H = MRI.createVirtualRegister(RC);
13533   unsigned t3L = MRI.createVirtualRegister(RC);
13534   unsigned t3H = MRI.createVirtualRegister(RC);
13535   unsigned t4L = MRI.createVirtualRegister(RC);
13536   unsigned t4H = MRI.createVirtualRegister(RC);
13537
13538   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
13539   unsigned LOADOpc = X86::MOV32rm;
13540
13541   // For the atomic load-arith operator, we generate
13542   //
13543   //  thisMBB:
13544   //    t1L = LOAD [MI.addr + 0]
13545   //    t1H = LOAD [MI.addr + 4]
13546   //  mainMBB:
13547   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
13548   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
13549   //    t2L = OP MI.val.lo, t4L
13550   //    t2H = OP MI.val.hi, t4H
13551   //    EBX = t2L
13552   //    ECX = t2H
13553   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
13554   //    t3L = EAX
13555   //    t3H = EDX
13556   //    JNE loop
13557   //  sinkMBB:
13558   //    dstL = t3L
13559   //    dstH = t3H
13560
13561   MachineBasicBlock *thisMBB = MBB;
13562   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
13563   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
13564   MF->insert(I, mainMBB);
13565   MF->insert(I, sinkMBB);
13566
13567   MachineInstrBuilder MIB;
13568
13569   // Transfer the remainder of BB and its successor edges to sinkMBB.
13570   sinkMBB->splice(sinkMBB->begin(), MBB,
13571                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
13572   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
13573
13574   // thisMBB:
13575   // Lo
13576   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
13577   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13578     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13579     if (NewMO.isReg())
13580       NewMO.setIsKill(false);
13581     MIB.addOperand(NewMO);
13582   }
13583   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
13584     unsigned flags = (*MMOI)->getFlags();
13585     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
13586     MachineMemOperand *MMO =
13587       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
13588                                (*MMOI)->getSize(),
13589                                (*MMOI)->getBaseAlignment(),
13590                                (*MMOI)->getTBAAInfo(),
13591                                (*MMOI)->getRanges());
13592     MIB.addMemOperand(MMO);
13593   };
13594   MachineInstr *LowMI = MIB;
13595
13596   // Hi
13597   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
13598   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13599     if (i == X86::AddrDisp) {
13600       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
13601     } else {
13602       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13603       if (NewMO.isReg())
13604         NewMO.setIsKill(false);
13605       MIB.addOperand(NewMO);
13606     }
13607   }
13608   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
13609
13610   thisMBB->addSuccessor(mainMBB);
13611
13612   // mainMBB:
13613   MachineBasicBlock *origMainMBB = mainMBB;
13614
13615   // Add PHIs.
13616   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
13617                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13618   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
13619                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13620
13621   unsigned Opc = MI->getOpcode();
13622   switch (Opc) {
13623   default:
13624     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
13625   case X86::ATOMAND6432:
13626   case X86::ATOMOR6432:
13627   case X86::ATOMXOR6432:
13628   case X86::ATOMADD6432:
13629   case X86::ATOMSUB6432: {
13630     unsigned HiOpc;
13631     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13632     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
13633       .addReg(SrcLoReg);
13634     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
13635       .addReg(SrcHiReg);
13636     break;
13637   }
13638   case X86::ATOMNAND6432: {
13639     unsigned HiOpc, NOTOpc;
13640     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
13641     unsigned TmpL = MRI.createVirtualRegister(RC);
13642     unsigned TmpH = MRI.createVirtualRegister(RC);
13643     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
13644       .addReg(t4L);
13645     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
13646       .addReg(t4H);
13647     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
13648     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
13649     break;
13650   }
13651   case X86::ATOMMAX6432:
13652   case X86::ATOMMIN6432:
13653   case X86::ATOMUMAX6432:
13654   case X86::ATOMUMIN6432: {
13655     unsigned HiOpc;
13656     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13657     unsigned cL = MRI.createVirtualRegister(RC8);
13658     unsigned cH = MRI.createVirtualRegister(RC8);
13659     unsigned cL32 = MRI.createVirtualRegister(RC);
13660     unsigned cH32 = MRI.createVirtualRegister(RC);
13661     unsigned cc = MRI.createVirtualRegister(RC);
13662     // cl := cmp src_lo, lo
13663     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13664       .addReg(SrcLoReg).addReg(t4L);
13665     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
13666     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
13667     // ch := cmp src_hi, hi
13668     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
13669       .addReg(SrcHiReg).addReg(t4H);
13670     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
13671     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
13672     // cc := if (src_hi == hi) ? cl : ch;
13673     if (Subtarget->hasCMov()) {
13674       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
13675         .addReg(cH32).addReg(cL32);
13676     } else {
13677       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
13678               .addReg(cH32).addReg(cL32)
13679               .addImm(X86::COND_E);
13680       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13681     }
13682     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
13683     if (Subtarget->hasCMov()) {
13684       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
13685         .addReg(SrcLoReg).addReg(t4L);
13686       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
13687         .addReg(SrcHiReg).addReg(t4H);
13688     } else {
13689       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
13690               .addReg(SrcLoReg).addReg(t4L)
13691               .addImm(X86::COND_NE);
13692       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13693       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
13694       // 2nd CMOV lowering.
13695       mainMBB->addLiveIn(X86::EFLAGS);
13696       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
13697               .addReg(SrcHiReg).addReg(t4H)
13698               .addImm(X86::COND_NE);
13699       mainMBB = EmitLoweredSelect(MIB, mainMBB);
13700       // Replace the original PHI node as mainMBB is changed after CMOV
13701       // lowering.
13702       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
13703         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
13704       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
13705         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
13706       PhiL->eraseFromParent();
13707       PhiH->eraseFromParent();
13708     }
13709     break;
13710   }
13711   case X86::ATOMSWAP6432: {
13712     unsigned HiOpc;
13713     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
13714     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
13715     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
13716     break;
13717   }
13718   }
13719
13720   // Copy EDX:EAX back from HiReg:LoReg
13721   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
13722   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
13723   // Copy ECX:EBX from t1H:t1L
13724   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
13725   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
13726
13727   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
13728   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
13729     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
13730     if (NewMO.isReg())
13731       NewMO.setIsKill(false);
13732     MIB.addOperand(NewMO);
13733   }
13734   MIB.setMemRefs(MMOBegin, MMOEnd);
13735
13736   // Copy EDX:EAX back to t3H:t3L
13737   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
13738   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
13739
13740   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
13741
13742   mainMBB->addSuccessor(origMainMBB);
13743   mainMBB->addSuccessor(sinkMBB);
13744
13745   // sinkMBB:
13746   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13747           TII->get(TargetOpcode::COPY), DstLoReg)
13748     .addReg(t3L);
13749   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
13750           TII->get(TargetOpcode::COPY), DstHiReg)
13751     .addReg(t3H);
13752
13753   MI->eraseFromParent();
13754   return sinkMBB;
13755 }
13756
13757 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
13758 // or XMM0_V32I8 in AVX all of this code can be replaced with that
13759 // in the .td file.
13760 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
13761                                        const TargetInstrInfo *TII) {
13762   unsigned Opc;
13763   switch (MI->getOpcode()) {
13764   default: llvm_unreachable("illegal opcode!");
13765   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
13766   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
13767   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
13768   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
13769   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
13770   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
13771   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
13772   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
13773   }
13774
13775   DebugLoc dl = MI->getDebugLoc();
13776   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13777
13778   unsigned NumArgs = MI->getNumOperands();
13779   for (unsigned i = 1; i < NumArgs; ++i) {
13780     MachineOperand &Op = MI->getOperand(i);
13781     if (!(Op.isReg() && Op.isImplicit()))
13782       MIB.addOperand(Op);
13783   }
13784   if (MI->hasOneMemOperand())
13785     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13786
13787   BuildMI(*BB, MI, dl,
13788     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13789     .addReg(X86::XMM0);
13790
13791   MI->eraseFromParent();
13792   return BB;
13793 }
13794
13795 // FIXME: Custom handling because TableGen doesn't support multiple implicit
13796 // defs in an instruction pattern
13797 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
13798                                        const TargetInstrInfo *TII) {
13799   unsigned Opc;
13800   switch (MI->getOpcode()) {
13801   default: llvm_unreachable("illegal opcode!");
13802   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
13803   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
13804   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
13805   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
13806   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
13807   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
13808   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
13809   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
13810   }
13811
13812   DebugLoc dl = MI->getDebugLoc();
13813   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
13814
13815   unsigned NumArgs = MI->getNumOperands(); // remove the results
13816   for (unsigned i = 1; i < NumArgs; ++i) {
13817     MachineOperand &Op = MI->getOperand(i);
13818     if (!(Op.isReg() && Op.isImplicit()))
13819       MIB.addOperand(Op);
13820   }
13821   if (MI->hasOneMemOperand())
13822     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
13823
13824   BuildMI(*BB, MI, dl,
13825     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
13826     .addReg(X86::ECX);
13827
13828   MI->eraseFromParent();
13829   return BB;
13830 }
13831
13832 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
13833                                        const TargetInstrInfo *TII,
13834                                        const X86Subtarget* Subtarget) {
13835   DebugLoc dl = MI->getDebugLoc();
13836
13837   // Address into RAX/EAX, other two args into ECX, EDX.
13838   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
13839   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
13840   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
13841   for (int i = 0; i < X86::AddrNumOperands; ++i)
13842     MIB.addOperand(MI->getOperand(i));
13843
13844   unsigned ValOps = X86::AddrNumOperands;
13845   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
13846     .addReg(MI->getOperand(ValOps).getReg());
13847   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
13848     .addReg(MI->getOperand(ValOps+1).getReg());
13849
13850   // The instruction doesn't actually take any operands though.
13851   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
13852
13853   MI->eraseFromParent(); // The pseudo is gone now.
13854   return BB;
13855 }
13856
13857 MachineBasicBlock *
13858 X86TargetLowering::EmitVAARG64WithCustomInserter(
13859                    MachineInstr *MI,
13860                    MachineBasicBlock *MBB) const {
13861   // Emit va_arg instruction on X86-64.
13862
13863   // Operands to this pseudo-instruction:
13864   // 0  ) Output        : destination address (reg)
13865   // 1-5) Input         : va_list address (addr, i64mem)
13866   // 6  ) ArgSize       : Size (in bytes) of vararg type
13867   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
13868   // 8  ) Align         : Alignment of type
13869   // 9  ) EFLAGS (implicit-def)
13870
13871   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
13872   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
13873
13874   unsigned DestReg = MI->getOperand(0).getReg();
13875   MachineOperand &Base = MI->getOperand(1);
13876   MachineOperand &Scale = MI->getOperand(2);
13877   MachineOperand &Index = MI->getOperand(3);
13878   MachineOperand &Disp = MI->getOperand(4);
13879   MachineOperand &Segment = MI->getOperand(5);
13880   unsigned ArgSize = MI->getOperand(6).getImm();
13881   unsigned ArgMode = MI->getOperand(7).getImm();
13882   unsigned Align = MI->getOperand(8).getImm();
13883
13884   // Memory Reference
13885   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
13886   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
13887   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
13888
13889   // Machine Information
13890   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
13891   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
13892   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
13893   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
13894   DebugLoc DL = MI->getDebugLoc();
13895
13896   // struct va_list {
13897   //   i32   gp_offset
13898   //   i32   fp_offset
13899   //   i64   overflow_area (address)
13900   //   i64   reg_save_area (address)
13901   // }
13902   // sizeof(va_list) = 24
13903   // alignment(va_list) = 8
13904
13905   unsigned TotalNumIntRegs = 6;
13906   unsigned TotalNumXMMRegs = 8;
13907   bool UseGPOffset = (ArgMode == 1);
13908   bool UseFPOffset = (ArgMode == 2);
13909   unsigned MaxOffset = TotalNumIntRegs * 8 +
13910                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
13911
13912   /* Align ArgSize to a multiple of 8 */
13913   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
13914   bool NeedsAlign = (Align > 8);
13915
13916   MachineBasicBlock *thisMBB = MBB;
13917   MachineBasicBlock *overflowMBB;
13918   MachineBasicBlock *offsetMBB;
13919   MachineBasicBlock *endMBB;
13920
13921   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
13922   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
13923   unsigned OffsetReg = 0;
13924
13925   if (!UseGPOffset && !UseFPOffset) {
13926     // If we only pull from the overflow region, we don't create a branch.
13927     // We don't need to alter control flow.
13928     OffsetDestReg = 0; // unused
13929     OverflowDestReg = DestReg;
13930
13931     offsetMBB = NULL;
13932     overflowMBB = thisMBB;
13933     endMBB = thisMBB;
13934   } else {
13935     // First emit code to check if gp_offset (or fp_offset) is below the bound.
13936     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
13937     // If not, pull from overflow_area. (branch to overflowMBB)
13938     //
13939     //       thisMBB
13940     //         |     .
13941     //         |        .
13942     //     offsetMBB   overflowMBB
13943     //         |        .
13944     //         |     .
13945     //        endMBB
13946
13947     // Registers for the PHI in endMBB
13948     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
13949     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
13950
13951     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
13952     MachineFunction *MF = MBB->getParent();
13953     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13954     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13955     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
13956
13957     MachineFunction::iterator MBBIter = MBB;
13958     ++MBBIter;
13959
13960     // Insert the new basic blocks
13961     MF->insert(MBBIter, offsetMBB);
13962     MF->insert(MBBIter, overflowMBB);
13963     MF->insert(MBBIter, endMBB);
13964
13965     // Transfer the remainder of MBB and its successor edges to endMBB.
13966     endMBB->splice(endMBB->begin(), thisMBB,
13967                     llvm::next(MachineBasicBlock::iterator(MI)),
13968                     thisMBB->end());
13969     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
13970
13971     // Make offsetMBB and overflowMBB successors of thisMBB
13972     thisMBB->addSuccessor(offsetMBB);
13973     thisMBB->addSuccessor(overflowMBB);
13974
13975     // endMBB is a successor of both offsetMBB and overflowMBB
13976     offsetMBB->addSuccessor(endMBB);
13977     overflowMBB->addSuccessor(endMBB);
13978
13979     // Load the offset value into a register
13980     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
13981     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
13982       .addOperand(Base)
13983       .addOperand(Scale)
13984       .addOperand(Index)
13985       .addDisp(Disp, UseFPOffset ? 4 : 0)
13986       .addOperand(Segment)
13987       .setMemRefs(MMOBegin, MMOEnd);
13988
13989     // Check if there is enough room left to pull this argument.
13990     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
13991       .addReg(OffsetReg)
13992       .addImm(MaxOffset + 8 - ArgSizeA8);
13993
13994     // Branch to "overflowMBB" if offset >= max
13995     // Fall through to "offsetMBB" otherwise
13996     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
13997       .addMBB(overflowMBB);
13998   }
13999
14000   // In offsetMBB, emit code to use the reg_save_area.
14001   if (offsetMBB) {
14002     assert(OffsetReg != 0);
14003
14004     // Read the reg_save_area address.
14005     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
14006     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
14007       .addOperand(Base)
14008       .addOperand(Scale)
14009       .addOperand(Index)
14010       .addDisp(Disp, 16)
14011       .addOperand(Segment)
14012       .setMemRefs(MMOBegin, MMOEnd);
14013
14014     // Zero-extend the offset
14015     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
14016       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
14017         .addImm(0)
14018         .addReg(OffsetReg)
14019         .addImm(X86::sub_32bit);
14020
14021     // Add the offset to the reg_save_area to get the final address.
14022     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
14023       .addReg(OffsetReg64)
14024       .addReg(RegSaveReg);
14025
14026     // Compute the offset for the next argument
14027     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
14028     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
14029       .addReg(OffsetReg)
14030       .addImm(UseFPOffset ? 16 : 8);
14031
14032     // Store it back into the va_list.
14033     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
14034       .addOperand(Base)
14035       .addOperand(Scale)
14036       .addOperand(Index)
14037       .addDisp(Disp, UseFPOffset ? 4 : 0)
14038       .addOperand(Segment)
14039       .addReg(NextOffsetReg)
14040       .setMemRefs(MMOBegin, MMOEnd);
14041
14042     // Jump to endMBB
14043     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
14044       .addMBB(endMBB);
14045   }
14046
14047   //
14048   // Emit code to use overflow area
14049   //
14050
14051   // Load the overflow_area address into a register.
14052   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
14053   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
14054     .addOperand(Base)
14055     .addOperand(Scale)
14056     .addOperand(Index)
14057     .addDisp(Disp, 8)
14058     .addOperand(Segment)
14059     .setMemRefs(MMOBegin, MMOEnd);
14060
14061   // If we need to align it, do so. Otherwise, just copy the address
14062   // to OverflowDestReg.
14063   if (NeedsAlign) {
14064     // Align the overflow address
14065     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
14066     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
14067
14068     // aligned_addr = (addr + (align-1)) & ~(align-1)
14069     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
14070       .addReg(OverflowAddrReg)
14071       .addImm(Align-1);
14072
14073     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
14074       .addReg(TmpReg)
14075       .addImm(~(uint64_t)(Align-1));
14076   } else {
14077     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
14078       .addReg(OverflowAddrReg);
14079   }
14080
14081   // Compute the next overflow address after this argument.
14082   // (the overflow address should be kept 8-byte aligned)
14083   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
14084   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
14085     .addReg(OverflowDestReg)
14086     .addImm(ArgSizeA8);
14087
14088   // Store the new overflow address.
14089   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
14090     .addOperand(Base)
14091     .addOperand(Scale)
14092     .addOperand(Index)
14093     .addDisp(Disp, 8)
14094     .addOperand(Segment)
14095     .addReg(NextAddrReg)
14096     .setMemRefs(MMOBegin, MMOEnd);
14097
14098   // If we branched, emit the PHI to the front of endMBB.
14099   if (offsetMBB) {
14100     BuildMI(*endMBB, endMBB->begin(), DL,
14101             TII->get(X86::PHI), DestReg)
14102       .addReg(OffsetDestReg).addMBB(offsetMBB)
14103       .addReg(OverflowDestReg).addMBB(overflowMBB);
14104   }
14105
14106   // Erase the pseudo instruction
14107   MI->eraseFromParent();
14108
14109   return endMBB;
14110 }
14111
14112 MachineBasicBlock *
14113 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
14114                                                  MachineInstr *MI,
14115                                                  MachineBasicBlock *MBB) const {
14116   // Emit code to save XMM registers to the stack. The ABI says that the
14117   // number of registers to save is given in %al, so it's theoretically
14118   // possible to do an indirect jump trick to avoid saving all of them,
14119   // however this code takes a simpler approach and just executes all
14120   // of the stores if %al is non-zero. It's less code, and it's probably
14121   // easier on the hardware branch predictor, and stores aren't all that
14122   // expensive anyway.
14123
14124   // Create the new basic blocks. One block contains all the XMM stores,
14125   // and one block is the final destination regardless of whether any
14126   // stores were performed.
14127   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
14128   MachineFunction *F = MBB->getParent();
14129   MachineFunction::iterator MBBIter = MBB;
14130   ++MBBIter;
14131   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
14132   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
14133   F->insert(MBBIter, XMMSaveMBB);
14134   F->insert(MBBIter, EndMBB);
14135
14136   // Transfer the remainder of MBB and its successor edges to EndMBB.
14137   EndMBB->splice(EndMBB->begin(), MBB,
14138                  llvm::next(MachineBasicBlock::iterator(MI)),
14139                  MBB->end());
14140   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
14141
14142   // The original block will now fall through to the XMM save block.
14143   MBB->addSuccessor(XMMSaveMBB);
14144   // The XMMSaveMBB will fall through to the end block.
14145   XMMSaveMBB->addSuccessor(EndMBB);
14146
14147   // Now add the instructions.
14148   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14149   DebugLoc DL = MI->getDebugLoc();
14150
14151   unsigned CountReg = MI->getOperand(0).getReg();
14152   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
14153   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
14154
14155   if (!Subtarget->isTargetWin64()) {
14156     // If %al is 0, branch around the XMM save block.
14157     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
14158     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
14159     MBB->addSuccessor(EndMBB);
14160   }
14161
14162   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
14163   // In the XMM save block, save all the XMM argument registers.
14164   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
14165     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
14166     MachineMemOperand *MMO =
14167       F->getMachineMemOperand(
14168           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
14169         MachineMemOperand::MOStore,
14170         /*Size=*/16, /*Align=*/16);
14171     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
14172       .addFrameIndex(RegSaveFrameIndex)
14173       .addImm(/*Scale=*/1)
14174       .addReg(/*IndexReg=*/0)
14175       .addImm(/*Disp=*/Offset)
14176       .addReg(/*Segment=*/0)
14177       .addReg(MI->getOperand(i).getReg())
14178       .addMemOperand(MMO);
14179   }
14180
14181   MI->eraseFromParent();   // The pseudo instruction is gone now.
14182
14183   return EndMBB;
14184 }
14185
14186 // The EFLAGS operand of SelectItr might be missing a kill marker
14187 // because there were multiple uses of EFLAGS, and ISel didn't know
14188 // which to mark. Figure out whether SelectItr should have had a
14189 // kill marker, and set it if it should. Returns the correct kill
14190 // marker value.
14191 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
14192                                      MachineBasicBlock* BB,
14193                                      const TargetRegisterInfo* TRI) {
14194   // Scan forward through BB for a use/def of EFLAGS.
14195   MachineBasicBlock::iterator miI(llvm::next(SelectItr));
14196   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
14197     const MachineInstr& mi = *miI;
14198     if (mi.readsRegister(X86::EFLAGS))
14199       return false;
14200     if (mi.definesRegister(X86::EFLAGS))
14201       break; // Should have kill-flag - update below.
14202   }
14203
14204   // If we hit the end of the block, check whether EFLAGS is live into a
14205   // successor.
14206   if (miI == BB->end()) {
14207     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
14208                                           sEnd = BB->succ_end();
14209          sItr != sEnd; ++sItr) {
14210       MachineBasicBlock* succ = *sItr;
14211       if (succ->isLiveIn(X86::EFLAGS))
14212         return false;
14213     }
14214   }
14215
14216   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
14217   // out. SelectMI should have a kill flag on EFLAGS.
14218   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
14219   return true;
14220 }
14221
14222 MachineBasicBlock *
14223 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
14224                                      MachineBasicBlock *BB) const {
14225   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14226   DebugLoc DL = MI->getDebugLoc();
14227
14228   // To "insert" a SELECT_CC instruction, we actually have to insert the
14229   // diamond control-flow pattern.  The incoming instruction knows the
14230   // destination vreg to set, the condition code register to branch on, the
14231   // true/false values to select between, and a branch opcode to use.
14232   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14233   MachineFunction::iterator It = BB;
14234   ++It;
14235
14236   //  thisMBB:
14237   //  ...
14238   //   TrueVal = ...
14239   //   cmpTY ccX, r1, r2
14240   //   bCC copy1MBB
14241   //   fallthrough --> copy0MBB
14242   MachineBasicBlock *thisMBB = BB;
14243   MachineFunction *F = BB->getParent();
14244   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
14245   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
14246   F->insert(It, copy0MBB);
14247   F->insert(It, sinkMBB);
14248
14249   // If the EFLAGS register isn't dead in the terminator, then claim that it's
14250   // live into the sink and copy blocks.
14251   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
14252   if (!MI->killsRegister(X86::EFLAGS) &&
14253       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
14254     copy0MBB->addLiveIn(X86::EFLAGS);
14255     sinkMBB->addLiveIn(X86::EFLAGS);
14256   }
14257
14258   // Transfer the remainder of BB and its successor edges to sinkMBB.
14259   sinkMBB->splice(sinkMBB->begin(), BB,
14260                   llvm::next(MachineBasicBlock::iterator(MI)),
14261                   BB->end());
14262   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
14263
14264   // Add the true and fallthrough blocks as its successors.
14265   BB->addSuccessor(copy0MBB);
14266   BB->addSuccessor(sinkMBB);
14267
14268   // Create the conditional branch instruction.
14269   unsigned Opc =
14270     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
14271   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
14272
14273   //  copy0MBB:
14274   //   %FalseValue = ...
14275   //   # fallthrough to sinkMBB
14276   copy0MBB->addSuccessor(sinkMBB);
14277
14278   //  sinkMBB:
14279   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
14280   //  ...
14281   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
14282           TII->get(X86::PHI), MI->getOperand(0).getReg())
14283     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
14284     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
14285
14286   MI->eraseFromParent();   // The pseudo instruction is gone now.
14287   return sinkMBB;
14288 }
14289
14290 MachineBasicBlock *
14291 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
14292                                         bool Is64Bit) const {
14293   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14294   DebugLoc DL = MI->getDebugLoc();
14295   MachineFunction *MF = BB->getParent();
14296   const BasicBlock *LLVM_BB = BB->getBasicBlock();
14297
14298   assert(getTargetMachine().Options.EnableSegmentedStacks);
14299
14300   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
14301   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
14302
14303   // BB:
14304   //  ... [Till the alloca]
14305   // If stacklet is not large enough, jump to mallocMBB
14306   //
14307   // bumpMBB:
14308   //  Allocate by subtracting from RSP
14309   //  Jump to continueMBB
14310   //
14311   // mallocMBB:
14312   //  Allocate by call to runtime
14313   //
14314   // continueMBB:
14315   //  ...
14316   //  [rest of original BB]
14317   //
14318
14319   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14320   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14321   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
14322
14323   MachineRegisterInfo &MRI = MF->getRegInfo();
14324   const TargetRegisterClass *AddrRegClass =
14325     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
14326
14327   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14328     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
14329     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
14330     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
14331     sizeVReg = MI->getOperand(1).getReg(),
14332     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
14333
14334   MachineFunction::iterator MBBIter = BB;
14335   ++MBBIter;
14336
14337   MF->insert(MBBIter, bumpMBB);
14338   MF->insert(MBBIter, mallocMBB);
14339   MF->insert(MBBIter, continueMBB);
14340
14341   continueMBB->splice(continueMBB->begin(), BB, llvm::next
14342                       (MachineBasicBlock::iterator(MI)), BB->end());
14343   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
14344
14345   // Add code to the main basic block to check if the stack limit has been hit,
14346   // and if so, jump to mallocMBB otherwise to bumpMBB.
14347   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
14348   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
14349     .addReg(tmpSPVReg).addReg(sizeVReg);
14350   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
14351     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
14352     .addReg(SPLimitVReg);
14353   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
14354
14355   // bumpMBB simply decreases the stack pointer, since we know the current
14356   // stacklet has enough space.
14357   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
14358     .addReg(SPLimitVReg);
14359   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
14360     .addReg(SPLimitVReg);
14361   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14362
14363   // Calls into a routine in libgcc to allocate more space from the heap.
14364   const uint32_t *RegMask =
14365     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14366   if (Is64Bit) {
14367     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
14368       .addReg(sizeVReg);
14369     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
14370       .addExternalSymbol("__morestack_allocate_stack_space")
14371       .addRegMask(RegMask)
14372       .addReg(X86::RDI, RegState::Implicit)
14373       .addReg(X86::RAX, RegState::ImplicitDefine);
14374   } else {
14375     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
14376       .addImm(12);
14377     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
14378     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
14379       .addExternalSymbol("__morestack_allocate_stack_space")
14380       .addRegMask(RegMask)
14381       .addReg(X86::EAX, RegState::ImplicitDefine);
14382   }
14383
14384   if (!Is64Bit)
14385     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
14386       .addImm(16);
14387
14388   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
14389     .addReg(Is64Bit ? X86::RAX : X86::EAX);
14390   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
14391
14392   // Set up the CFG correctly.
14393   BB->addSuccessor(bumpMBB);
14394   BB->addSuccessor(mallocMBB);
14395   mallocMBB->addSuccessor(continueMBB);
14396   bumpMBB->addSuccessor(continueMBB);
14397
14398   // Take care of the PHI nodes.
14399   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
14400           MI->getOperand(0).getReg())
14401     .addReg(mallocPtrVReg).addMBB(mallocMBB)
14402     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
14403
14404   // Delete the original pseudo instruction.
14405   MI->eraseFromParent();
14406
14407   // And we're done.
14408   return continueMBB;
14409 }
14410
14411 MachineBasicBlock *
14412 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
14413                                           MachineBasicBlock *BB) const {
14414   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14415   DebugLoc DL = MI->getDebugLoc();
14416
14417   assert(!Subtarget->isTargetEnvMacho());
14418
14419   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
14420   // non-trivial part is impdef of ESP.
14421
14422   if (Subtarget->isTargetWin64()) {
14423     if (Subtarget->isTargetCygMing()) {
14424       // ___chkstk(Mingw64):
14425       // Clobbers R10, R11, RAX and EFLAGS.
14426       // Updates RSP.
14427       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14428         .addExternalSymbol("___chkstk")
14429         .addReg(X86::RAX, RegState::Implicit)
14430         .addReg(X86::RSP, RegState::Implicit)
14431         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
14432         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
14433         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14434     } else {
14435       // __chkstk(MSVCRT): does not update stack pointer.
14436       // Clobbers R10, R11 and EFLAGS.
14437       // FIXME: RAX(allocated size) might be reused and not killed.
14438       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
14439         .addExternalSymbol("__chkstk")
14440         .addReg(X86::RAX, RegState::Implicit)
14441         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14442       // RAX has the offset to subtracted from RSP.
14443       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
14444         .addReg(X86::RSP)
14445         .addReg(X86::RAX);
14446     }
14447   } else {
14448     const char *StackProbeSymbol =
14449       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
14450
14451     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
14452       .addExternalSymbol(StackProbeSymbol)
14453       .addReg(X86::EAX, RegState::Implicit)
14454       .addReg(X86::ESP, RegState::Implicit)
14455       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
14456       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
14457       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
14458   }
14459
14460   MI->eraseFromParent();   // The pseudo instruction is gone now.
14461   return BB;
14462 }
14463
14464 MachineBasicBlock *
14465 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
14466                                       MachineBasicBlock *BB) const {
14467   // This is pretty easy.  We're taking the value that we received from
14468   // our load from the relocation, sticking it in either RDI (x86-64)
14469   // or EAX and doing an indirect call.  The return value will then
14470   // be in the normal return register.
14471   const X86InstrInfo *TII
14472     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
14473   DebugLoc DL = MI->getDebugLoc();
14474   MachineFunction *F = BB->getParent();
14475
14476   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
14477   assert(MI->getOperand(3).isGlobal() && "This should be a global");
14478
14479   // Get a register mask for the lowered call.
14480   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
14481   // proper register mask.
14482   const uint32_t *RegMask =
14483     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
14484   if (Subtarget->is64Bit()) {
14485     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14486                                       TII->get(X86::MOV64rm), X86::RDI)
14487     .addReg(X86::RIP)
14488     .addImm(0).addReg(0)
14489     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14490                       MI->getOperand(3).getTargetFlags())
14491     .addReg(0);
14492     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
14493     addDirectMem(MIB, X86::RDI);
14494     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
14495   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
14496     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14497                                       TII->get(X86::MOV32rm), X86::EAX)
14498     .addReg(0)
14499     .addImm(0).addReg(0)
14500     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14501                       MI->getOperand(3).getTargetFlags())
14502     .addReg(0);
14503     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14504     addDirectMem(MIB, X86::EAX);
14505     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14506   } else {
14507     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
14508                                       TII->get(X86::MOV32rm), X86::EAX)
14509     .addReg(TII->getGlobalBaseReg(F))
14510     .addImm(0).addReg(0)
14511     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
14512                       MI->getOperand(3).getTargetFlags())
14513     .addReg(0);
14514     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
14515     addDirectMem(MIB, X86::EAX);
14516     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
14517   }
14518
14519   MI->eraseFromParent(); // The pseudo instruction is gone now.
14520   return BB;
14521 }
14522
14523 MachineBasicBlock *
14524 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
14525                                     MachineBasicBlock *MBB) const {
14526   DebugLoc DL = MI->getDebugLoc();
14527   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14528
14529   MachineFunction *MF = MBB->getParent();
14530   MachineRegisterInfo &MRI = MF->getRegInfo();
14531
14532   const BasicBlock *BB = MBB->getBasicBlock();
14533   MachineFunction::iterator I = MBB;
14534   ++I;
14535
14536   // Memory Reference
14537   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
14538   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
14539
14540   unsigned DstReg;
14541   unsigned MemOpndSlot = 0;
14542
14543   unsigned CurOp = 0;
14544
14545   DstReg = MI->getOperand(CurOp++).getReg();
14546   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
14547   assert(RC->hasType(MVT::i32) && "Invalid destination!");
14548   unsigned mainDstReg = MRI.createVirtualRegister(RC);
14549   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
14550
14551   MemOpndSlot = CurOp;
14552
14553   MVT PVT = getPointerTy();
14554   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
14555          "Invalid Pointer Size!");
14556
14557   // For v = setjmp(buf), we generate
14558   //
14559   // thisMBB:
14560   //  buf[LabelOffset] = restoreMBB
14561   //  SjLjSetup restoreMBB
14562   //
14563   // mainMBB:
14564   //  v_main = 0
14565   //
14566   // sinkMBB:
14567   //  v = phi(main, restore)
14568   //
14569   // restoreMBB:
14570   //  v_restore = 1
14571
14572   MachineBasicBlock *thisMBB = MBB;
14573   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
14574   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
14575   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
14576   MF->insert(I, mainMBB);
14577   MF->insert(I, sinkMBB);
14578   MF->push_back(restoreMBB);
14579
14580   MachineInstrBuilder MIB;
14581
14582   // Transfer the remainder of BB and its successor edges to sinkMBB.
14583   sinkMBB->splice(sinkMBB->begin(), MBB,
14584                   llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
14585   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
14586
14587   // thisMBB:
14588   unsigned PtrStoreOpc = 0;
14589   unsigned LabelReg = 0;
14590   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14591   Reloc::Model RM = getTargetMachine().getRelocationModel();
14592   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
14593                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
14594
14595   // Prepare IP either in reg or imm.
14596   if (!UseImmLabel) {
14597     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
14598     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
14599     LabelReg = MRI.createVirtualRegister(PtrRC);
14600     if (Subtarget->is64Bit()) {
14601       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
14602               .addReg(X86::RIP)
14603               .addImm(0)
14604               .addReg(0)
14605               .addMBB(restoreMBB)
14606               .addReg(0);
14607     } else {
14608       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
14609       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
14610               .addReg(XII->getGlobalBaseReg(MF))
14611               .addImm(0)
14612               .addReg(0)
14613               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
14614               .addReg(0);
14615     }
14616   } else
14617     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
14618   // Store IP
14619   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
14620   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14621     if (i == X86::AddrDisp)
14622       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
14623     else
14624       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
14625   }
14626   if (!UseImmLabel)
14627     MIB.addReg(LabelReg);
14628   else
14629     MIB.addMBB(restoreMBB);
14630   MIB.setMemRefs(MMOBegin, MMOEnd);
14631   // Setup
14632   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
14633           .addMBB(restoreMBB);
14634
14635   const X86RegisterInfo *RegInfo =
14636     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
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   const X86RegisterInfo *RegInfo =
14683     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
14684   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
14685   unsigned SP = RegInfo->getStackRegister();
14686
14687   MachineInstrBuilder MIB;
14688
14689   const int64_t LabelOffset = 1 * PVT.getStoreSize();
14690   const int64_t SPOffset = 2 * PVT.getStoreSize();
14691
14692   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
14693   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
14694
14695   // Reload FP
14696   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
14697   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
14698     MIB.addOperand(MI->getOperand(i));
14699   MIB.setMemRefs(MMOBegin, MMOEnd);
14700   // Reload IP
14701   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
14702   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14703     if (i == X86::AddrDisp)
14704       MIB.addDisp(MI->getOperand(i), LabelOffset);
14705     else
14706       MIB.addOperand(MI->getOperand(i));
14707   }
14708   MIB.setMemRefs(MMOBegin, MMOEnd);
14709   // Reload SP
14710   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
14711   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
14712     if (i == X86::AddrDisp)
14713       MIB.addDisp(MI->getOperand(i), SPOffset);
14714     else
14715       MIB.addOperand(MI->getOperand(i));
14716   }
14717   MIB.setMemRefs(MMOBegin, MMOEnd);
14718   // Jump
14719   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
14720
14721   MI->eraseFromParent();
14722   return MBB;
14723 }
14724
14725 MachineBasicBlock *
14726 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
14727                                                MachineBasicBlock *BB) const {
14728   switch (MI->getOpcode()) {
14729   default: llvm_unreachable("Unexpected instr type to insert");
14730   case X86::TAILJMPd64:
14731   case X86::TAILJMPr64:
14732   case X86::TAILJMPm64:
14733     llvm_unreachable("TAILJMP64 would not be touched here.");
14734   case X86::TCRETURNdi64:
14735   case X86::TCRETURNri64:
14736   case X86::TCRETURNmi64:
14737     return BB;
14738   case X86::WIN_ALLOCA:
14739     return EmitLoweredWinAlloca(MI, BB);
14740   case X86::SEG_ALLOCA_32:
14741     return EmitLoweredSegAlloca(MI, BB, false);
14742   case X86::SEG_ALLOCA_64:
14743     return EmitLoweredSegAlloca(MI, BB, true);
14744   case X86::TLSCall_32:
14745   case X86::TLSCall_64:
14746     return EmitLoweredTLSCall(MI, BB);
14747   case X86::CMOV_GR8:
14748   case X86::CMOV_FR32:
14749   case X86::CMOV_FR64:
14750   case X86::CMOV_V4F32:
14751   case X86::CMOV_V2F64:
14752   case X86::CMOV_V2I64:
14753   case X86::CMOV_V8F32:
14754   case X86::CMOV_V4F64:
14755   case X86::CMOV_V4I64:
14756   case X86::CMOV_GR16:
14757   case X86::CMOV_GR32:
14758   case X86::CMOV_RFP32:
14759   case X86::CMOV_RFP64:
14760   case X86::CMOV_RFP80:
14761     return EmitLoweredSelect(MI, BB);
14762
14763   case X86::FP32_TO_INT16_IN_MEM:
14764   case X86::FP32_TO_INT32_IN_MEM:
14765   case X86::FP32_TO_INT64_IN_MEM:
14766   case X86::FP64_TO_INT16_IN_MEM:
14767   case X86::FP64_TO_INT32_IN_MEM:
14768   case X86::FP64_TO_INT64_IN_MEM:
14769   case X86::FP80_TO_INT16_IN_MEM:
14770   case X86::FP80_TO_INT32_IN_MEM:
14771   case X86::FP80_TO_INT64_IN_MEM: {
14772     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
14773     DebugLoc DL = MI->getDebugLoc();
14774
14775     // Change the floating point control register to use "round towards zero"
14776     // mode when truncating to an integer value.
14777     MachineFunction *F = BB->getParent();
14778     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
14779     addFrameReference(BuildMI(*BB, MI, DL,
14780                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
14781
14782     // Load the old value of the high byte of the control word...
14783     unsigned OldCW =
14784       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
14785     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
14786                       CWFrameIdx);
14787
14788     // Set the high part to be round to zero...
14789     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
14790       .addImm(0xC7F);
14791
14792     // Reload the modified control word now...
14793     addFrameReference(BuildMI(*BB, MI, DL,
14794                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14795
14796     // Restore the memory image of control word to original value
14797     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
14798       .addReg(OldCW);
14799
14800     // Get the X86 opcode to use.
14801     unsigned Opc;
14802     switch (MI->getOpcode()) {
14803     default: llvm_unreachable("illegal opcode!");
14804     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
14805     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
14806     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
14807     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
14808     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
14809     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
14810     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
14811     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
14812     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
14813     }
14814
14815     X86AddressMode AM;
14816     MachineOperand &Op = MI->getOperand(0);
14817     if (Op.isReg()) {
14818       AM.BaseType = X86AddressMode::RegBase;
14819       AM.Base.Reg = Op.getReg();
14820     } else {
14821       AM.BaseType = X86AddressMode::FrameIndexBase;
14822       AM.Base.FrameIndex = Op.getIndex();
14823     }
14824     Op = MI->getOperand(1);
14825     if (Op.isImm())
14826       AM.Scale = Op.getImm();
14827     Op = MI->getOperand(2);
14828     if (Op.isImm())
14829       AM.IndexReg = Op.getImm();
14830     Op = MI->getOperand(3);
14831     if (Op.isGlobal()) {
14832       AM.GV = Op.getGlobal();
14833     } else {
14834       AM.Disp = Op.getImm();
14835     }
14836     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
14837                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
14838
14839     // Reload the original control word now.
14840     addFrameReference(BuildMI(*BB, MI, DL,
14841                               TII->get(X86::FLDCW16m)), CWFrameIdx);
14842
14843     MI->eraseFromParent();   // The pseudo instruction is gone now.
14844     return BB;
14845   }
14846     // String/text processing lowering.
14847   case X86::PCMPISTRM128REG:
14848   case X86::VPCMPISTRM128REG:
14849   case X86::PCMPISTRM128MEM:
14850   case X86::VPCMPISTRM128MEM:
14851   case X86::PCMPESTRM128REG:
14852   case X86::VPCMPESTRM128REG:
14853   case X86::PCMPESTRM128MEM:
14854   case X86::VPCMPESTRM128MEM:
14855     assert(Subtarget->hasSSE42() &&
14856            "Target must have SSE4.2 or AVX features enabled");
14857     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
14858
14859   // String/text processing lowering.
14860   case X86::PCMPISTRIREG:
14861   case X86::VPCMPISTRIREG:
14862   case X86::PCMPISTRIMEM:
14863   case X86::VPCMPISTRIMEM:
14864   case X86::PCMPESTRIREG:
14865   case X86::VPCMPESTRIREG:
14866   case X86::PCMPESTRIMEM:
14867   case X86::VPCMPESTRIMEM:
14868     assert(Subtarget->hasSSE42() &&
14869            "Target must have SSE4.2 or AVX features enabled");
14870     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
14871
14872   // Thread synchronization.
14873   case X86::MONITOR:
14874     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
14875
14876   // xbegin
14877   case X86::XBEGIN:
14878     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
14879
14880   // Atomic Lowering.
14881   case X86::ATOMAND8:
14882   case X86::ATOMAND16:
14883   case X86::ATOMAND32:
14884   case X86::ATOMAND64:
14885     // Fall through
14886   case X86::ATOMOR8:
14887   case X86::ATOMOR16:
14888   case X86::ATOMOR32:
14889   case X86::ATOMOR64:
14890     // Fall through
14891   case X86::ATOMXOR16:
14892   case X86::ATOMXOR8:
14893   case X86::ATOMXOR32:
14894   case X86::ATOMXOR64:
14895     // Fall through
14896   case X86::ATOMNAND8:
14897   case X86::ATOMNAND16:
14898   case X86::ATOMNAND32:
14899   case X86::ATOMNAND64:
14900     // Fall through
14901   case X86::ATOMMAX8:
14902   case X86::ATOMMAX16:
14903   case X86::ATOMMAX32:
14904   case X86::ATOMMAX64:
14905     // Fall through
14906   case X86::ATOMMIN8:
14907   case X86::ATOMMIN16:
14908   case X86::ATOMMIN32:
14909   case X86::ATOMMIN64:
14910     // Fall through
14911   case X86::ATOMUMAX8:
14912   case X86::ATOMUMAX16:
14913   case X86::ATOMUMAX32:
14914   case X86::ATOMUMAX64:
14915     // Fall through
14916   case X86::ATOMUMIN8:
14917   case X86::ATOMUMIN16:
14918   case X86::ATOMUMIN32:
14919   case X86::ATOMUMIN64:
14920     return EmitAtomicLoadArith(MI, BB);
14921
14922   // This group does 64-bit operations on a 32-bit host.
14923   case X86::ATOMAND6432:
14924   case X86::ATOMOR6432:
14925   case X86::ATOMXOR6432:
14926   case X86::ATOMNAND6432:
14927   case X86::ATOMADD6432:
14928   case X86::ATOMSUB6432:
14929   case X86::ATOMMAX6432:
14930   case X86::ATOMMIN6432:
14931   case X86::ATOMUMAX6432:
14932   case X86::ATOMUMIN6432:
14933   case X86::ATOMSWAP6432:
14934     return EmitAtomicLoadArith6432(MI, BB);
14935
14936   case X86::VASTART_SAVE_XMM_REGS:
14937     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
14938
14939   case X86::VAARG_64:
14940     return EmitVAARG64WithCustomInserter(MI, BB);
14941
14942   case X86::EH_SjLj_SetJmp32:
14943   case X86::EH_SjLj_SetJmp64:
14944     return emitEHSjLjSetJmp(MI, BB);
14945
14946   case X86::EH_SjLj_LongJmp32:
14947   case X86::EH_SjLj_LongJmp64:
14948     return emitEHSjLjLongJmp(MI, BB);
14949   }
14950 }
14951
14952 //===----------------------------------------------------------------------===//
14953 //                           X86 Optimization Hooks
14954 //===----------------------------------------------------------------------===//
14955
14956 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
14957                                                        APInt &KnownZero,
14958                                                        APInt &KnownOne,
14959                                                        const SelectionDAG &DAG,
14960                                                        unsigned Depth) const {
14961   unsigned BitWidth = KnownZero.getBitWidth();
14962   unsigned Opc = Op.getOpcode();
14963   assert((Opc >= ISD::BUILTIN_OP_END ||
14964           Opc == ISD::INTRINSIC_WO_CHAIN ||
14965           Opc == ISD::INTRINSIC_W_CHAIN ||
14966           Opc == ISD::INTRINSIC_VOID) &&
14967          "Should use MaskedValueIsZero if you don't know whether Op"
14968          " is a target node!");
14969
14970   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
14971   switch (Opc) {
14972   default: break;
14973   case X86ISD::ADD:
14974   case X86ISD::SUB:
14975   case X86ISD::ADC:
14976   case X86ISD::SBB:
14977   case X86ISD::SMUL:
14978   case X86ISD::UMUL:
14979   case X86ISD::INC:
14980   case X86ISD::DEC:
14981   case X86ISD::OR:
14982   case X86ISD::XOR:
14983   case X86ISD::AND:
14984     // These nodes' second result is a boolean.
14985     if (Op.getResNo() == 0)
14986       break;
14987     // Fallthrough
14988   case X86ISD::SETCC:
14989     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
14990     break;
14991   case ISD::INTRINSIC_WO_CHAIN: {
14992     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14993     unsigned NumLoBits = 0;
14994     switch (IntId) {
14995     default: break;
14996     case Intrinsic::x86_sse_movmsk_ps:
14997     case Intrinsic::x86_avx_movmsk_ps_256:
14998     case Intrinsic::x86_sse2_movmsk_pd:
14999     case Intrinsic::x86_avx_movmsk_pd_256:
15000     case Intrinsic::x86_mmx_pmovmskb:
15001     case Intrinsic::x86_sse2_pmovmskb_128:
15002     case Intrinsic::x86_avx2_pmovmskb: {
15003       // High bits of movmskp{s|d}, pmovmskb are known zero.
15004       switch (IntId) {
15005         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15006         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
15007         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
15008         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
15009         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
15010         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
15011         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
15012         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
15013       }
15014       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
15015       break;
15016     }
15017     }
15018     break;
15019   }
15020   }
15021 }
15022
15023 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
15024                                                          unsigned Depth) const {
15025   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
15026   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
15027     return Op.getValueType().getScalarType().getSizeInBits();
15028
15029   // Fallback case.
15030   return 1;
15031 }
15032
15033 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
15034 /// node is a GlobalAddress + offset.
15035 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
15036                                        const GlobalValue* &GA,
15037                                        int64_t &Offset) const {
15038   if (N->getOpcode() == X86ISD::Wrapper) {
15039     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
15040       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
15041       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
15042       return true;
15043     }
15044   }
15045   return TargetLowering::isGAPlusOffset(N, GA, Offset);
15046 }
15047
15048 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
15049 /// same as extracting the high 128-bit part of 256-bit vector and then
15050 /// inserting the result into the low part of a new 256-bit vector
15051 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
15052   EVT VT = SVOp->getValueType(0);
15053   unsigned NumElems = VT.getVectorNumElements();
15054
15055   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15056   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
15057     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15058         SVOp->getMaskElt(j) >= 0)
15059       return false;
15060
15061   return true;
15062 }
15063
15064 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
15065 /// same as extracting the low 128-bit part of 256-bit vector and then
15066 /// inserting the result into the high part of a new 256-bit vector
15067 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
15068   EVT VT = SVOp->getValueType(0);
15069   unsigned NumElems = VT.getVectorNumElements();
15070
15071   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15072   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
15073     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
15074         SVOp->getMaskElt(j) >= 0)
15075       return false;
15076
15077   return true;
15078 }
15079
15080 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
15081 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
15082                                         TargetLowering::DAGCombinerInfo &DCI,
15083                                         const X86Subtarget* Subtarget) {
15084   SDLoc dl(N);
15085   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
15086   SDValue V1 = SVOp->getOperand(0);
15087   SDValue V2 = SVOp->getOperand(1);
15088   EVT VT = SVOp->getValueType(0);
15089   unsigned NumElems = VT.getVectorNumElements();
15090
15091   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
15092       V2.getOpcode() == ISD::CONCAT_VECTORS) {
15093     //
15094     //                   0,0,0,...
15095     //                      |
15096     //    V      UNDEF    BUILD_VECTOR    UNDEF
15097     //     \      /           \           /
15098     //  CONCAT_VECTOR         CONCAT_VECTOR
15099     //         \                  /
15100     //          \                /
15101     //          RESULT: V + zero extended
15102     //
15103     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
15104         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
15105         V1.getOperand(1).getOpcode() != ISD::UNDEF)
15106       return SDValue();
15107
15108     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
15109       return SDValue();
15110
15111     // To match the shuffle mask, the first half of the mask should
15112     // be exactly the first vector, and all the rest a splat with the
15113     // first element of the second one.
15114     for (unsigned i = 0; i != NumElems/2; ++i)
15115       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
15116           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
15117         return SDValue();
15118
15119     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
15120     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
15121       if (Ld->hasNUsesOfValue(1, 0)) {
15122         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
15123         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
15124         SDValue ResNode =
15125           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
15126                                   array_lengthof(Ops),
15127                                   Ld->getMemoryVT(),
15128                                   Ld->getPointerInfo(),
15129                                   Ld->getAlignment(),
15130                                   false/*isVolatile*/, true/*ReadMem*/,
15131                                   false/*WriteMem*/);
15132
15133         // Make sure the newly-created LOAD is in the same position as Ld in
15134         // terms of dependency. We create a TokenFactor for Ld and ResNode,
15135         // and update uses of Ld's output chain to use the TokenFactor.
15136         if (Ld->hasAnyUseOfValue(1)) {
15137           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15138                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
15139           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
15140           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
15141                                  SDValue(ResNode.getNode(), 1));
15142         }
15143
15144         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
15145       }
15146     }
15147
15148     // Emit a zeroed vector and insert the desired subvector on its
15149     // first half.
15150     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15151     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
15152     return DCI.CombineTo(N, InsV);
15153   }
15154
15155   //===--------------------------------------------------------------------===//
15156   // Combine some shuffles into subvector extracts and inserts:
15157   //
15158
15159   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
15160   if (isShuffleHigh128VectorInsertLow(SVOp)) {
15161     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
15162     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
15163     return DCI.CombineTo(N, InsV);
15164   }
15165
15166   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
15167   if (isShuffleLow128VectorInsertHigh(SVOp)) {
15168     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
15169     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
15170     return DCI.CombineTo(N, InsV);
15171   }
15172
15173   return SDValue();
15174 }
15175
15176 /// PerformShuffleCombine - Performs several different shuffle combines.
15177 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
15178                                      TargetLowering::DAGCombinerInfo &DCI,
15179                                      const X86Subtarget *Subtarget) {
15180   SDLoc dl(N);
15181   EVT VT = N->getValueType(0);
15182
15183   // Don't create instructions with illegal types after legalize types has run.
15184   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15185   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
15186     return SDValue();
15187
15188   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
15189   if (Subtarget->hasFp256() && VT.is256BitVector() &&
15190       N->getOpcode() == ISD::VECTOR_SHUFFLE)
15191     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
15192
15193   // Only handle 128 wide vector from here on.
15194   if (!VT.is128BitVector())
15195     return SDValue();
15196
15197   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
15198   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
15199   // consecutive, non-overlapping, and in the right order.
15200   SmallVector<SDValue, 16> Elts;
15201   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
15202     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
15203
15204   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
15205 }
15206
15207 /// PerformTruncateCombine - Converts truncate operation to
15208 /// a sequence of vector shuffle operations.
15209 /// It is possible when we truncate 256-bit vector to 128-bit vector
15210 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
15211                                       TargetLowering::DAGCombinerInfo &DCI,
15212                                       const X86Subtarget *Subtarget)  {
15213   return SDValue();
15214 }
15215
15216 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
15217 /// specific shuffle of a load can be folded into a single element load.
15218 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
15219 /// shuffles have been customed lowered so we need to handle those here.
15220 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
15221                                          TargetLowering::DAGCombinerInfo &DCI) {
15222   if (DCI.isBeforeLegalizeOps())
15223     return SDValue();
15224
15225   SDValue InVec = N->getOperand(0);
15226   SDValue EltNo = N->getOperand(1);
15227
15228   if (!isa<ConstantSDNode>(EltNo))
15229     return SDValue();
15230
15231   EVT VT = InVec.getValueType();
15232
15233   bool HasShuffleIntoBitcast = false;
15234   if (InVec.getOpcode() == ISD::BITCAST) {
15235     // Don't duplicate a load with other uses.
15236     if (!InVec.hasOneUse())
15237       return SDValue();
15238     EVT BCVT = InVec.getOperand(0).getValueType();
15239     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
15240       return SDValue();
15241     InVec = InVec.getOperand(0);
15242     HasShuffleIntoBitcast = true;
15243   }
15244
15245   if (!isTargetShuffle(InVec.getOpcode()))
15246     return SDValue();
15247
15248   // Don't duplicate a load with other uses.
15249   if (!InVec.hasOneUse())
15250     return SDValue();
15251
15252   SmallVector<int, 16> ShuffleMask;
15253   bool UnaryShuffle;
15254   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
15255                             UnaryShuffle))
15256     return SDValue();
15257
15258   // Select the input vector, guarding against out of range extract vector.
15259   unsigned NumElems = VT.getVectorNumElements();
15260   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
15261   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
15262   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
15263                                          : InVec.getOperand(1);
15264
15265   // If inputs to shuffle are the same for both ops, then allow 2 uses
15266   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
15267
15268   if (LdNode.getOpcode() == ISD::BITCAST) {
15269     // Don't duplicate a load with other uses.
15270     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
15271       return SDValue();
15272
15273     AllowedUses = 1; // only allow 1 load use if we have a bitcast
15274     LdNode = LdNode.getOperand(0);
15275   }
15276
15277   if (!ISD::isNormalLoad(LdNode.getNode()))
15278     return SDValue();
15279
15280   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
15281
15282   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
15283     return SDValue();
15284
15285   if (HasShuffleIntoBitcast) {
15286     // If there's a bitcast before the shuffle, check if the load type and
15287     // alignment is valid.
15288     unsigned Align = LN0->getAlignment();
15289     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15290     unsigned NewAlign = TLI.getDataLayout()->
15291       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
15292
15293     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
15294       return SDValue();
15295   }
15296
15297   // All checks match so transform back to vector_shuffle so that DAG combiner
15298   // can finish the job
15299   SDLoc dl(N);
15300
15301   // Create shuffle node taking into account the case that its a unary shuffle
15302   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
15303   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
15304                                  InVec.getOperand(0), Shuffle,
15305                                  &ShuffleMask[0]);
15306   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
15307   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
15308                      EltNo);
15309 }
15310
15311 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
15312 /// generation and convert it from being a bunch of shuffles and extracts
15313 /// to a simple store and scalar loads to extract the elements.
15314 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
15315                                          TargetLowering::DAGCombinerInfo &DCI) {
15316   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
15317   if (NewOp.getNode())
15318     return NewOp;
15319
15320   SDValue InputVector = N->getOperand(0);
15321   // Detect whether we are trying to convert from mmx to i32 and the bitcast
15322   // from mmx to v2i32 has a single usage.
15323   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
15324       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
15325       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
15326     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
15327                        N->getValueType(0),
15328                        InputVector.getNode()->getOperand(0));
15329
15330   // Only operate on vectors of 4 elements, where the alternative shuffling
15331   // gets to be more expensive.
15332   if (InputVector.getValueType() != MVT::v4i32)
15333     return SDValue();
15334
15335   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
15336   // single use which is a sign-extend or zero-extend, and all elements are
15337   // used.
15338   SmallVector<SDNode *, 4> Uses;
15339   unsigned ExtractedElements = 0;
15340   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
15341        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
15342     if (UI.getUse().getResNo() != InputVector.getResNo())
15343       return SDValue();
15344
15345     SDNode *Extract = *UI;
15346     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
15347       return SDValue();
15348
15349     if (Extract->getValueType(0) != MVT::i32)
15350       return SDValue();
15351     if (!Extract->hasOneUse())
15352       return SDValue();
15353     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
15354         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
15355       return SDValue();
15356     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
15357       return SDValue();
15358
15359     // Record which element was extracted.
15360     ExtractedElements |=
15361       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
15362
15363     Uses.push_back(Extract);
15364   }
15365
15366   // If not all the elements were used, this may not be worthwhile.
15367   if (ExtractedElements != 15)
15368     return SDValue();
15369
15370   // Ok, we've now decided to do the transformation.
15371   SDLoc dl(InputVector);
15372
15373   // Store the value to a temporary stack slot.
15374   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
15375   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
15376                             MachinePointerInfo(), false, false, 0);
15377
15378   // Replace each use (extract) with a load of the appropriate element.
15379   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
15380        UE = Uses.end(); UI != UE; ++UI) {
15381     SDNode *Extract = *UI;
15382
15383     // cOMpute the element's address.
15384     SDValue Idx = Extract->getOperand(1);
15385     unsigned EltSize =
15386         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
15387     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
15388     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15389     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
15390
15391     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
15392                                      StackPtr, OffsetVal);
15393
15394     // Load the scalar.
15395     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
15396                                      ScalarAddr, MachinePointerInfo(),
15397                                      false, false, false, 0);
15398
15399     // Replace the exact with the load.
15400     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
15401   }
15402
15403   // The replacement was made in place; don't return anything.
15404   return SDValue();
15405 }
15406
15407 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
15408 static unsigned matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS,
15409                                    SDValue RHS, SelectionDAG &DAG,
15410                                    const X86Subtarget *Subtarget) {
15411   if (!VT.isVector())
15412     return 0;
15413
15414   switch (VT.getSimpleVT().SimpleTy) {
15415   default: return 0;
15416   case MVT::v32i8:
15417   case MVT::v16i16:
15418   case MVT::v8i32:
15419     if (!Subtarget->hasAVX2())
15420       return 0;
15421   case MVT::v16i8:
15422   case MVT::v8i16:
15423   case MVT::v4i32:
15424     if (!Subtarget->hasSSE2())
15425       return 0;
15426   }
15427
15428   // SSE2 has only a small subset of the operations.
15429   bool hasUnsigned = Subtarget->hasSSE41() ||
15430                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
15431   bool hasSigned = Subtarget->hasSSE41() ||
15432                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
15433
15434   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15435
15436   // Check for x CC y ? x : y.
15437   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15438       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15439     switch (CC) {
15440     default: break;
15441     case ISD::SETULT:
15442     case ISD::SETULE:
15443       return hasUnsigned ? X86ISD::UMIN : 0;
15444     case ISD::SETUGT:
15445     case ISD::SETUGE:
15446       return hasUnsigned ? X86ISD::UMAX : 0;
15447     case ISD::SETLT:
15448     case ISD::SETLE:
15449       return hasSigned ? X86ISD::SMIN : 0;
15450     case ISD::SETGT:
15451     case ISD::SETGE:
15452       return hasSigned ? X86ISD::SMAX : 0;
15453     }
15454   // Check for x CC y ? y : x -- a min/max with reversed arms.
15455   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15456              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15457     switch (CC) {
15458     default: break;
15459     case ISD::SETULT:
15460     case ISD::SETULE:
15461       return hasUnsigned ? X86ISD::UMAX : 0;
15462     case ISD::SETUGT:
15463     case ISD::SETUGE:
15464       return hasUnsigned ? X86ISD::UMIN : 0;
15465     case ISD::SETLT:
15466     case ISD::SETLE:
15467       return hasSigned ? X86ISD::SMAX : 0;
15468     case ISD::SETGT:
15469     case ISD::SETGE:
15470       return hasSigned ? X86ISD::SMIN : 0;
15471     }
15472   }
15473
15474   return 0;
15475 }
15476
15477 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
15478 /// nodes.
15479 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
15480                                     TargetLowering::DAGCombinerInfo &DCI,
15481                                     const X86Subtarget *Subtarget) {
15482   SDLoc DL(N);
15483   SDValue Cond = N->getOperand(0);
15484   // Get the LHS/RHS of the select.
15485   SDValue LHS = N->getOperand(1);
15486   SDValue RHS = N->getOperand(2);
15487   EVT VT = LHS.getValueType();
15488
15489   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
15490   // instructions match the semantics of the common C idiom x<y?x:y but not
15491   // x<=y?x:y, because of how they handle negative zero (which can be
15492   // ignored in unsafe-math mode).
15493   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
15494       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
15495       (Subtarget->hasSSE2() ||
15496        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
15497     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15498
15499     unsigned Opcode = 0;
15500     // Check for x CC y ? x : y.
15501     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15502         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15503       switch (CC) {
15504       default: break;
15505       case ISD::SETULT:
15506         // Converting this to a min would handle NaNs incorrectly, and swapping
15507         // the operands would cause it to handle comparisons between positive
15508         // and negative zero incorrectly.
15509         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15510           if (!DAG.getTarget().Options.UnsafeFPMath &&
15511               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15512             break;
15513           std::swap(LHS, RHS);
15514         }
15515         Opcode = X86ISD::FMIN;
15516         break;
15517       case ISD::SETOLE:
15518         // Converting this to a min would handle comparisons between positive
15519         // and negative zero incorrectly.
15520         if (!DAG.getTarget().Options.UnsafeFPMath &&
15521             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15522           break;
15523         Opcode = X86ISD::FMIN;
15524         break;
15525       case ISD::SETULE:
15526         // Converting this to a min would handle both negative zeros and NaNs
15527         // incorrectly, but we can swap the operands to fix both.
15528         std::swap(LHS, RHS);
15529       case ISD::SETOLT:
15530       case ISD::SETLT:
15531       case ISD::SETLE:
15532         Opcode = X86ISD::FMIN;
15533         break;
15534
15535       case ISD::SETOGE:
15536         // Converting this to a max would handle comparisons between positive
15537         // and negative zero incorrectly.
15538         if (!DAG.getTarget().Options.UnsafeFPMath &&
15539             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
15540           break;
15541         Opcode = X86ISD::FMAX;
15542         break;
15543       case ISD::SETUGT:
15544         // Converting this to a max would handle NaNs incorrectly, and swapping
15545         // the operands would cause it to handle comparisons between positive
15546         // and negative zero incorrectly.
15547         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
15548           if (!DAG.getTarget().Options.UnsafeFPMath &&
15549               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
15550             break;
15551           std::swap(LHS, RHS);
15552         }
15553         Opcode = X86ISD::FMAX;
15554         break;
15555       case ISD::SETUGE:
15556         // Converting this to a max would handle both negative zeros and NaNs
15557         // incorrectly, but we can swap the operands to fix both.
15558         std::swap(LHS, RHS);
15559       case ISD::SETOGT:
15560       case ISD::SETGT:
15561       case ISD::SETGE:
15562         Opcode = X86ISD::FMAX;
15563         break;
15564       }
15565     // Check for x CC y ? y : x -- a min/max with reversed arms.
15566     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
15567                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
15568       switch (CC) {
15569       default: break;
15570       case ISD::SETOGE:
15571         // Converting this to a min would handle comparisons between positive
15572         // and negative zero incorrectly, and swapping the operands would
15573         // cause it to handle NaNs incorrectly.
15574         if (!DAG.getTarget().Options.UnsafeFPMath &&
15575             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
15576           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15577             break;
15578           std::swap(LHS, RHS);
15579         }
15580         Opcode = X86ISD::FMIN;
15581         break;
15582       case ISD::SETUGT:
15583         // Converting this to a min would handle NaNs incorrectly.
15584         if (!DAG.getTarget().Options.UnsafeFPMath &&
15585             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
15586           break;
15587         Opcode = X86ISD::FMIN;
15588         break;
15589       case ISD::SETUGE:
15590         // Converting this to a min would handle both negative zeros and NaNs
15591         // incorrectly, but we can swap the operands to fix both.
15592         std::swap(LHS, RHS);
15593       case ISD::SETOGT:
15594       case ISD::SETGT:
15595       case ISD::SETGE:
15596         Opcode = X86ISD::FMIN;
15597         break;
15598
15599       case ISD::SETULT:
15600         // Converting this to a max would handle NaNs incorrectly.
15601         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15602           break;
15603         Opcode = X86ISD::FMAX;
15604         break;
15605       case ISD::SETOLE:
15606         // Converting this to a max would handle comparisons between positive
15607         // and negative zero incorrectly, and swapping the operands would
15608         // cause it to handle NaNs incorrectly.
15609         if (!DAG.getTarget().Options.UnsafeFPMath &&
15610             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
15611           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
15612             break;
15613           std::swap(LHS, RHS);
15614         }
15615         Opcode = X86ISD::FMAX;
15616         break;
15617       case ISD::SETULE:
15618         // Converting this to a max would handle both negative zeros and NaNs
15619         // incorrectly, but we can swap the operands to fix both.
15620         std::swap(LHS, RHS);
15621       case ISD::SETOLT:
15622       case ISD::SETLT:
15623       case ISD::SETLE:
15624         Opcode = X86ISD::FMAX;
15625         break;
15626       }
15627     }
15628
15629     if (Opcode)
15630       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
15631   }
15632
15633   // If this is a select between two integer constants, try to do some
15634   // optimizations.
15635   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
15636     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
15637       // Don't do this for crazy integer types.
15638       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
15639         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
15640         // so that TrueC (the true value) is larger than FalseC.
15641         bool NeedsCondInvert = false;
15642
15643         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
15644             // Efficiently invertible.
15645             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
15646              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
15647               isa<ConstantSDNode>(Cond.getOperand(1))))) {
15648           NeedsCondInvert = true;
15649           std::swap(TrueC, FalseC);
15650         }
15651
15652         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
15653         if (FalseC->getAPIntValue() == 0 &&
15654             TrueC->getAPIntValue().isPowerOf2()) {
15655           if (NeedsCondInvert) // Invert the condition if needed.
15656             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15657                                DAG.getConstant(1, Cond.getValueType()));
15658
15659           // Zero extend the condition if needed.
15660           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
15661
15662           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
15663           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
15664                              DAG.getConstant(ShAmt, MVT::i8));
15665         }
15666
15667         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
15668         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
15669           if (NeedsCondInvert) // Invert the condition if needed.
15670             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15671                                DAG.getConstant(1, Cond.getValueType()));
15672
15673           // Zero extend the condition if needed.
15674           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
15675                              FalseC->getValueType(0), Cond);
15676           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15677                              SDValue(FalseC, 0));
15678         }
15679
15680         // Optimize cases that will turn into an LEA instruction.  This requires
15681         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
15682         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
15683           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
15684           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
15685
15686           bool isFastMultiplier = false;
15687           if (Diff < 10) {
15688             switch ((unsigned char)Diff) {
15689               default: break;
15690               case 1:  // result = add base, cond
15691               case 2:  // result = lea base(    , cond*2)
15692               case 3:  // result = lea base(cond, cond*2)
15693               case 4:  // result = lea base(    , cond*4)
15694               case 5:  // result = lea base(cond, cond*4)
15695               case 8:  // result = lea base(    , cond*8)
15696               case 9:  // result = lea base(cond, cond*8)
15697                 isFastMultiplier = true;
15698                 break;
15699             }
15700           }
15701
15702           if (isFastMultiplier) {
15703             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
15704             if (NeedsCondInvert) // Invert the condition if needed.
15705               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
15706                                  DAG.getConstant(1, Cond.getValueType()));
15707
15708             // Zero extend the condition if needed.
15709             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
15710                                Cond);
15711             // Scale the condition by the difference.
15712             if (Diff != 1)
15713               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
15714                                  DAG.getConstant(Diff, Cond.getValueType()));
15715
15716             // Add the base if non-zero.
15717             if (FalseC->getAPIntValue() != 0)
15718               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
15719                                  SDValue(FalseC, 0));
15720             return Cond;
15721           }
15722         }
15723       }
15724   }
15725
15726   // Canonicalize max and min:
15727   // (x > y) ? x : y -> (x >= y) ? x : y
15728   // (x < y) ? x : y -> (x <= y) ? x : y
15729   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
15730   // the need for an extra compare
15731   // against zero. e.g.
15732   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
15733   // subl   %esi, %edi
15734   // testl  %edi, %edi
15735   // movl   $0, %eax
15736   // cmovgl %edi, %eax
15737   // =>
15738   // xorl   %eax, %eax
15739   // subl   %esi, $edi
15740   // cmovsl %eax, %edi
15741   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
15742       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
15743       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
15744     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15745     switch (CC) {
15746     default: break;
15747     case ISD::SETLT:
15748     case ISD::SETGT: {
15749       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
15750       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
15751                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
15752       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
15753     }
15754     }
15755   }
15756
15757   // Match VSELECTs into subs with unsigned saturation.
15758   if (!DCI.isBeforeLegalize() &&
15759       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
15760       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
15761       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
15762        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
15763     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15764
15765     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
15766     // left side invert the predicate to simplify logic below.
15767     SDValue Other;
15768     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
15769       Other = RHS;
15770       CC = ISD::getSetCCInverse(CC, true);
15771     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
15772       Other = LHS;
15773     }
15774
15775     if (Other.getNode() && Other->getNumOperands() == 2 &&
15776         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
15777       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
15778       SDValue CondRHS = Cond->getOperand(1);
15779
15780       // Look for a general sub with unsigned saturation first.
15781       // x >= y ? x-y : 0 --> subus x, y
15782       // x >  y ? x-y : 0 --> subus x, y
15783       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
15784           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
15785         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15786
15787       // If the RHS is a constant we have to reverse the const canonicalization.
15788       // x > C-1 ? x+-C : 0 --> subus x, C
15789       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
15790           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
15791         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15792         if (CondRHS.getConstantOperandVal(0) == -A-1)
15793           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
15794                              DAG.getConstant(-A, VT));
15795       }
15796
15797       // Another special case: If C was a sign bit, the sub has been
15798       // canonicalized into a xor.
15799       // FIXME: Would it be better to use ComputeMaskedBits to determine whether
15800       //        it's safe to decanonicalize the xor?
15801       // x s< 0 ? x^C : 0 --> subus x, C
15802       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
15803           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
15804           isSplatVector(OpRHS.getNode())) {
15805         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
15806         if (A.isSignBit())
15807           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
15808       }
15809     }
15810   }
15811
15812   // Try to match a min/max vector operation.
15813   if (!DCI.isBeforeLegalize() &&
15814       N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC)
15815     if (unsigned Op = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget))
15816       return DAG.getNode(Op, DL, N->getValueType(0), LHS, RHS);
15817
15818   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
15819   if (!DCI.isBeforeLegalize() && N->getOpcode() == ISD::VSELECT &&
15820       Cond.getOpcode() == ISD::SETCC) {
15821
15822     assert(Cond.getValueType().isVector() &&
15823            "vector select expects a vector selector!");
15824
15825     EVT IntVT = Cond.getValueType();
15826     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
15827     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
15828
15829     if (!TValIsAllOnes && !FValIsAllZeros) {
15830       // Try invert the condition if true value is not all 1s and false value
15831       // is not all 0s.
15832       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
15833       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
15834
15835       if (TValIsAllZeros || FValIsAllOnes) {
15836         SDValue CC = Cond.getOperand(2);
15837         ISD::CondCode NewCC =
15838           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
15839                                Cond.getOperand(0).getValueType().isInteger());
15840         Cond = DAG.getSetCC(DL, IntVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
15841         std::swap(LHS, RHS);
15842         TValIsAllOnes = FValIsAllOnes;
15843         FValIsAllZeros = TValIsAllZeros;
15844       }
15845     }
15846
15847     if (TValIsAllOnes || FValIsAllZeros) {
15848       SDValue Ret;
15849
15850       if (TValIsAllOnes && FValIsAllZeros)
15851         Ret = Cond;
15852       else if (TValIsAllOnes)
15853         Ret = DAG.getNode(ISD::OR, DL, IntVT, Cond,
15854                           DAG.getNode(ISD::BITCAST, DL, IntVT, RHS));
15855       else if (FValIsAllZeros)
15856         Ret = DAG.getNode(ISD::AND, DL, IntVT, Cond,
15857                           DAG.getNode(ISD::BITCAST, DL, IntVT, LHS));
15858
15859       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
15860     }
15861   }
15862
15863   // If we know that this node is legal then we know that it is going to be
15864   // matched by one of the SSE/AVX BLEND instructions. These instructions only
15865   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
15866   // to simplify previous instructions.
15867   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15868   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
15869       !DCI.isBeforeLegalize() && TLI.isOperationLegal(ISD::VSELECT, VT)) {
15870     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
15871
15872     // Don't optimize vector selects that map to mask-registers.
15873     if (BitWidth == 1)
15874       return SDValue();
15875
15876     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
15877     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
15878
15879     APInt KnownZero, KnownOne;
15880     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
15881                                           DCI.isBeforeLegalizeOps());
15882     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
15883         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
15884       DCI.CommitTargetLoweringOpt(TLO);
15885   }
15886
15887   return SDValue();
15888 }
15889
15890 // Check whether a boolean test is testing a boolean value generated by
15891 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
15892 // code.
15893 //
15894 // Simplify the following patterns:
15895 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
15896 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
15897 // to (Op EFLAGS Cond)
15898 //
15899 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
15900 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
15901 // to (Op EFLAGS !Cond)
15902 //
15903 // where Op could be BRCOND or CMOV.
15904 //
15905 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
15906   // Quit if not CMP and SUB with its value result used.
15907   if (Cmp.getOpcode() != X86ISD::CMP &&
15908       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
15909       return SDValue();
15910
15911   // Quit if not used as a boolean value.
15912   if (CC != X86::COND_E && CC != X86::COND_NE)
15913     return SDValue();
15914
15915   // Check CMP operands. One of them should be 0 or 1 and the other should be
15916   // an SetCC or extended from it.
15917   SDValue Op1 = Cmp.getOperand(0);
15918   SDValue Op2 = Cmp.getOperand(1);
15919
15920   SDValue SetCC;
15921   const ConstantSDNode* C = 0;
15922   bool needOppositeCond = (CC == X86::COND_E);
15923   bool checkAgainstTrue = false; // Is it a comparison against 1?
15924
15925   if ((C = dyn_cast<ConstantSDNode>(Op1)))
15926     SetCC = Op2;
15927   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
15928     SetCC = Op1;
15929   else // Quit if all operands are not constants.
15930     return SDValue();
15931
15932   if (C->getZExtValue() == 1) {
15933     needOppositeCond = !needOppositeCond;
15934     checkAgainstTrue = true;
15935   } else if (C->getZExtValue() != 0)
15936     // Quit if the constant is neither 0 or 1.
15937     return SDValue();
15938
15939   bool truncatedToBoolWithAnd = false;
15940   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
15941   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
15942          SetCC.getOpcode() == ISD::TRUNCATE ||
15943          SetCC.getOpcode() == ISD::AND) {
15944     if (SetCC.getOpcode() == ISD::AND) {
15945       int OpIdx = -1;
15946       ConstantSDNode *CS;
15947       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
15948           CS->getZExtValue() == 1)
15949         OpIdx = 1;
15950       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
15951           CS->getZExtValue() == 1)
15952         OpIdx = 0;
15953       if (OpIdx == -1)
15954         break;
15955       SetCC = SetCC.getOperand(OpIdx);
15956       truncatedToBoolWithAnd = true;
15957     } else
15958       SetCC = SetCC.getOperand(0);
15959   }
15960
15961   switch (SetCC.getOpcode()) {
15962   case X86ISD::SETCC_CARRY:
15963     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
15964     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
15965     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
15966     // truncated to i1 using 'and'.
15967     if (checkAgainstTrue && !truncatedToBoolWithAnd)
15968       break;
15969     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
15970            "Invalid use of SETCC_CARRY!");
15971     // FALL THROUGH
15972   case X86ISD::SETCC:
15973     // Set the condition code or opposite one if necessary.
15974     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
15975     if (needOppositeCond)
15976       CC = X86::GetOppositeBranchCondition(CC);
15977     return SetCC.getOperand(1);
15978   case X86ISD::CMOV: {
15979     // Check whether false/true value has canonical one, i.e. 0 or 1.
15980     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
15981     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
15982     // Quit if true value is not a constant.
15983     if (!TVal)
15984       return SDValue();
15985     // Quit if false value is not a constant.
15986     if (!FVal) {
15987       SDValue Op = SetCC.getOperand(0);
15988       // Skip 'zext' or 'trunc' node.
15989       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
15990           Op.getOpcode() == ISD::TRUNCATE)
15991         Op = Op.getOperand(0);
15992       // A special case for rdrand/rdseed, where 0 is set if false cond is
15993       // found.
15994       if ((Op.getOpcode() != X86ISD::RDRAND &&
15995            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
15996         return SDValue();
15997     }
15998     // Quit if false value is not the constant 0 or 1.
15999     bool FValIsFalse = true;
16000     if (FVal && FVal->getZExtValue() != 0) {
16001       if (FVal->getZExtValue() != 1)
16002         return SDValue();
16003       // If FVal is 1, opposite cond is needed.
16004       needOppositeCond = !needOppositeCond;
16005       FValIsFalse = false;
16006     }
16007     // Quit if TVal is not the constant opposite of FVal.
16008     if (FValIsFalse && TVal->getZExtValue() != 1)
16009       return SDValue();
16010     if (!FValIsFalse && TVal->getZExtValue() != 0)
16011       return SDValue();
16012     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
16013     if (needOppositeCond)
16014       CC = X86::GetOppositeBranchCondition(CC);
16015     return SetCC.getOperand(3);
16016   }
16017   }
16018
16019   return SDValue();
16020 }
16021
16022 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
16023 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
16024                                   TargetLowering::DAGCombinerInfo &DCI,
16025                                   const X86Subtarget *Subtarget) {
16026   SDLoc DL(N);
16027
16028   // If the flag operand isn't dead, don't touch this CMOV.
16029   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
16030     return SDValue();
16031
16032   SDValue FalseOp = N->getOperand(0);
16033   SDValue TrueOp = N->getOperand(1);
16034   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
16035   SDValue Cond = N->getOperand(3);
16036
16037   if (CC == X86::COND_E || CC == X86::COND_NE) {
16038     switch (Cond.getOpcode()) {
16039     default: break;
16040     case X86ISD::BSR:
16041     case X86ISD::BSF:
16042       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
16043       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
16044         return (CC == X86::COND_E) ? FalseOp : TrueOp;
16045     }
16046   }
16047
16048   SDValue Flags;
16049
16050   Flags = checkBoolTestSetCCCombine(Cond, CC);
16051   if (Flags.getNode() &&
16052       // Extra check as FCMOV only supports a subset of X86 cond.
16053       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
16054     SDValue Ops[] = { FalseOp, TrueOp,
16055                       DAG.getConstant(CC, MVT::i8), Flags };
16056     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(),
16057                        Ops, array_lengthof(Ops));
16058   }
16059
16060   // If this is a select between two integer constants, try to do some
16061   // optimizations.  Note that the operands are ordered the opposite of SELECT
16062   // operands.
16063   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
16064     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
16065       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
16066       // larger than FalseC (the false value).
16067       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
16068         CC = X86::GetOppositeBranchCondition(CC);
16069         std::swap(TrueC, FalseC);
16070         std::swap(TrueOp, FalseOp);
16071       }
16072
16073       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
16074       // This is efficient for any integer data type (including i8/i16) and
16075       // shift amount.
16076       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
16077         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16078                            DAG.getConstant(CC, MVT::i8), Cond);
16079
16080         // Zero extend the condition if needed.
16081         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
16082
16083         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
16084         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
16085                            DAG.getConstant(ShAmt, MVT::i8));
16086         if (N->getNumValues() == 2)  // Dead flag value?
16087           return DCI.CombineTo(N, Cond, SDValue());
16088         return Cond;
16089       }
16090
16091       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
16092       // for any integer data type, including i8/i16.
16093       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
16094         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16095                            DAG.getConstant(CC, MVT::i8), Cond);
16096
16097         // Zero extend the condition if needed.
16098         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
16099                            FalseC->getValueType(0), Cond);
16100         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16101                            SDValue(FalseC, 0));
16102
16103         if (N->getNumValues() == 2)  // Dead flag value?
16104           return DCI.CombineTo(N, Cond, SDValue());
16105         return Cond;
16106       }
16107
16108       // Optimize cases that will turn into an LEA instruction.  This requires
16109       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
16110       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
16111         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
16112         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
16113
16114         bool isFastMultiplier = false;
16115         if (Diff < 10) {
16116           switch ((unsigned char)Diff) {
16117           default: break;
16118           case 1:  // result = add base, cond
16119           case 2:  // result = lea base(    , cond*2)
16120           case 3:  // result = lea base(cond, cond*2)
16121           case 4:  // result = lea base(    , cond*4)
16122           case 5:  // result = lea base(cond, cond*4)
16123           case 8:  // result = lea base(    , cond*8)
16124           case 9:  // result = lea base(cond, cond*8)
16125             isFastMultiplier = true;
16126             break;
16127           }
16128         }
16129
16130         if (isFastMultiplier) {
16131           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
16132           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16133                              DAG.getConstant(CC, MVT::i8), Cond);
16134           // Zero extend the condition if needed.
16135           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
16136                              Cond);
16137           // Scale the condition by the difference.
16138           if (Diff != 1)
16139             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
16140                                DAG.getConstant(Diff, Cond.getValueType()));
16141
16142           // Add the base if non-zero.
16143           if (FalseC->getAPIntValue() != 0)
16144             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
16145                                SDValue(FalseC, 0));
16146           if (N->getNumValues() == 2)  // Dead flag value?
16147             return DCI.CombineTo(N, Cond, SDValue());
16148           return Cond;
16149         }
16150       }
16151     }
16152   }
16153
16154   // Handle these cases:
16155   //   (select (x != c), e, c) -> select (x != c), e, x),
16156   //   (select (x == c), c, e) -> select (x == c), x, e)
16157   // where the c is an integer constant, and the "select" is the combination
16158   // of CMOV and CMP.
16159   //
16160   // The rationale for this change is that the conditional-move from a constant
16161   // needs two instructions, however, conditional-move from a register needs
16162   // only one instruction.
16163   //
16164   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
16165   //  some instruction-combining opportunities. This opt needs to be
16166   //  postponed as late as possible.
16167   //
16168   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
16169     // the DCI.xxxx conditions are provided to postpone the optimization as
16170     // late as possible.
16171
16172     ConstantSDNode *CmpAgainst = 0;
16173     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
16174         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
16175         !isa<ConstantSDNode>(Cond.getOperand(0))) {
16176
16177       if (CC == X86::COND_NE &&
16178           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
16179         CC = X86::GetOppositeBranchCondition(CC);
16180         std::swap(TrueOp, FalseOp);
16181       }
16182
16183       if (CC == X86::COND_E &&
16184           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
16185         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
16186                           DAG.getConstant(CC, MVT::i8), Cond };
16187         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops,
16188                            array_lengthof(Ops));
16189       }
16190     }
16191   }
16192
16193   return SDValue();
16194 }
16195
16196 /// PerformMulCombine - Optimize a single multiply with constant into two
16197 /// in order to implement it with two cheaper instructions, e.g.
16198 /// LEA + SHL, LEA + LEA.
16199 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
16200                                  TargetLowering::DAGCombinerInfo &DCI) {
16201   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
16202     return SDValue();
16203
16204   EVT VT = N->getValueType(0);
16205   if (VT != MVT::i64)
16206     return SDValue();
16207
16208   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
16209   if (!C)
16210     return SDValue();
16211   uint64_t MulAmt = C->getZExtValue();
16212   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
16213     return SDValue();
16214
16215   uint64_t MulAmt1 = 0;
16216   uint64_t MulAmt2 = 0;
16217   if ((MulAmt % 9) == 0) {
16218     MulAmt1 = 9;
16219     MulAmt2 = MulAmt / 9;
16220   } else if ((MulAmt % 5) == 0) {
16221     MulAmt1 = 5;
16222     MulAmt2 = MulAmt / 5;
16223   } else if ((MulAmt % 3) == 0) {
16224     MulAmt1 = 3;
16225     MulAmt2 = MulAmt / 3;
16226   }
16227   if (MulAmt2 &&
16228       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
16229     SDLoc DL(N);
16230
16231     if (isPowerOf2_64(MulAmt2) &&
16232         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
16233       // If second multiplifer is pow2, issue it first. We want the multiply by
16234       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
16235       // is an add.
16236       std::swap(MulAmt1, MulAmt2);
16237
16238     SDValue NewMul;
16239     if (isPowerOf2_64(MulAmt1))
16240       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16241                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
16242     else
16243       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
16244                            DAG.getConstant(MulAmt1, VT));
16245
16246     if (isPowerOf2_64(MulAmt2))
16247       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
16248                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
16249     else
16250       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
16251                            DAG.getConstant(MulAmt2, VT));
16252
16253     // Do not add new nodes to DAG combiner worklist.
16254     DCI.CombineTo(N, NewMul, false);
16255   }
16256   return SDValue();
16257 }
16258
16259 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
16260   SDValue N0 = N->getOperand(0);
16261   SDValue N1 = N->getOperand(1);
16262   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
16263   EVT VT = N0.getValueType();
16264
16265   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
16266   // since the result of setcc_c is all zero's or all ones.
16267   if (VT.isInteger() && !VT.isVector() &&
16268       N1C && N0.getOpcode() == ISD::AND &&
16269       N0.getOperand(1).getOpcode() == ISD::Constant) {
16270     SDValue N00 = N0.getOperand(0);
16271     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
16272         ((N00.getOpcode() == ISD::ANY_EXTEND ||
16273           N00.getOpcode() == ISD::ZERO_EXTEND) &&
16274          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
16275       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
16276       APInt ShAmt = N1C->getAPIntValue();
16277       Mask = Mask.shl(ShAmt);
16278       if (Mask != 0)
16279         return DAG.getNode(ISD::AND, SDLoc(N), VT,
16280                            N00, DAG.getConstant(Mask, VT));
16281     }
16282   }
16283
16284   // Hardware support for vector shifts is sparse which makes us scalarize the
16285   // vector operations in many cases. Also, on sandybridge ADD is faster than
16286   // shl.
16287   // (shl V, 1) -> add V,V
16288   if (isSplatVector(N1.getNode())) {
16289     assert(N0.getValueType().isVector() && "Invalid vector shift type");
16290     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
16291     // We shift all of the values by one. In many cases we do not have
16292     // hardware support for this operation. This is better expressed as an ADD
16293     // of two values.
16294     if (N1C && (1 == N1C->getZExtValue())) {
16295       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
16296     }
16297   }
16298
16299   return SDValue();
16300 }
16301
16302 /// PerformShiftCombine - Combine shifts.
16303 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
16304                                    TargetLowering::DAGCombinerInfo &DCI,
16305                                    const X86Subtarget *Subtarget) {
16306   if (N->getOpcode() == ISD::SHL) {
16307     SDValue V = PerformSHLCombine(N, DAG);
16308     if (V.getNode()) return V;
16309   }
16310
16311   return SDValue();
16312 }
16313
16314 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
16315 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
16316 // and friends.  Likewise for OR -> CMPNEQSS.
16317 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
16318                             TargetLowering::DAGCombinerInfo &DCI,
16319                             const X86Subtarget *Subtarget) {
16320   unsigned opcode;
16321
16322   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
16323   // we're requiring SSE2 for both.
16324   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
16325     SDValue N0 = N->getOperand(0);
16326     SDValue N1 = N->getOperand(1);
16327     SDValue CMP0 = N0->getOperand(1);
16328     SDValue CMP1 = N1->getOperand(1);
16329     SDLoc DL(N);
16330
16331     // The SETCCs should both refer to the same CMP.
16332     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
16333       return SDValue();
16334
16335     SDValue CMP00 = CMP0->getOperand(0);
16336     SDValue CMP01 = CMP0->getOperand(1);
16337     EVT     VT    = CMP00.getValueType();
16338
16339     if (VT == MVT::f32 || VT == MVT::f64) {
16340       bool ExpectingFlags = false;
16341       // Check for any users that want flags:
16342       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
16343            !ExpectingFlags && UI != UE; ++UI)
16344         switch (UI->getOpcode()) {
16345         default:
16346         case ISD::BR_CC:
16347         case ISD::BRCOND:
16348         case ISD::SELECT:
16349           ExpectingFlags = true;
16350           break;
16351         case ISD::CopyToReg:
16352         case ISD::SIGN_EXTEND:
16353         case ISD::ZERO_EXTEND:
16354         case ISD::ANY_EXTEND:
16355           break;
16356         }
16357
16358       if (!ExpectingFlags) {
16359         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
16360         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
16361
16362         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
16363           X86::CondCode tmp = cc0;
16364           cc0 = cc1;
16365           cc1 = tmp;
16366         }
16367
16368         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
16369             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
16370           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
16371           X86ISD::NodeType NTOperator = is64BitFP ?
16372             X86ISD::FSETCCsd : X86ISD::FSETCCss;
16373           // FIXME: need symbolic constants for these magic numbers.
16374           // See X86ATTInstPrinter.cpp:printSSECC().
16375           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
16376           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
16377                                               DAG.getConstant(x86cc, MVT::i8));
16378           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
16379                                               OnesOrZeroesF);
16380           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
16381                                       DAG.getConstant(1, MVT::i32));
16382           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
16383           return OneBitOfTruth;
16384         }
16385       }
16386     }
16387   }
16388   return SDValue();
16389 }
16390
16391 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
16392 /// so it can be folded inside ANDNP.
16393 static bool CanFoldXORWithAllOnes(const SDNode *N) {
16394   EVT VT = N->getValueType(0);
16395
16396   // Match direct AllOnes for 128 and 256-bit vectors
16397   if (ISD::isBuildVectorAllOnes(N))
16398     return true;
16399
16400   // Look through a bit convert.
16401   if (N->getOpcode() == ISD::BITCAST)
16402     N = N->getOperand(0).getNode();
16403
16404   // Sometimes the operand may come from a insert_subvector building a 256-bit
16405   // allones vector
16406   if (VT.is256BitVector() &&
16407       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
16408     SDValue V1 = N->getOperand(0);
16409     SDValue V2 = N->getOperand(1);
16410
16411     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
16412         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
16413         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
16414         ISD::isBuildVectorAllOnes(V2.getNode()))
16415       return true;
16416   }
16417
16418   return false;
16419 }
16420
16421 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
16422 // register. In most cases we actually compare or select YMM-sized registers
16423 // and mixing the two types creates horrible code. This method optimizes
16424 // some of the transition sequences.
16425 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
16426                                  TargetLowering::DAGCombinerInfo &DCI,
16427                                  const X86Subtarget *Subtarget) {
16428   EVT VT = N->getValueType(0);
16429   if (!VT.is256BitVector())
16430     return SDValue();
16431
16432   assert((N->getOpcode() == ISD::ANY_EXTEND ||
16433           N->getOpcode() == ISD::ZERO_EXTEND ||
16434           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
16435
16436   SDValue Narrow = N->getOperand(0);
16437   EVT NarrowVT = Narrow->getValueType(0);
16438   if (!NarrowVT.is128BitVector())
16439     return SDValue();
16440
16441   if (Narrow->getOpcode() != ISD::XOR &&
16442       Narrow->getOpcode() != ISD::AND &&
16443       Narrow->getOpcode() != ISD::OR)
16444     return SDValue();
16445
16446   SDValue N0  = Narrow->getOperand(0);
16447   SDValue N1  = Narrow->getOperand(1);
16448   SDLoc DL(Narrow);
16449
16450   // The Left side has to be a trunc.
16451   if (N0.getOpcode() != ISD::TRUNCATE)
16452     return SDValue();
16453
16454   // The type of the truncated inputs.
16455   EVT WideVT = N0->getOperand(0)->getValueType(0);
16456   if (WideVT != VT)
16457     return SDValue();
16458
16459   // The right side has to be a 'trunc' or a constant vector.
16460   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
16461   bool RHSConst = (isSplatVector(N1.getNode()) &&
16462                    isa<ConstantSDNode>(N1->getOperand(0)));
16463   if (!RHSTrunc && !RHSConst)
16464     return SDValue();
16465
16466   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16467
16468   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
16469     return SDValue();
16470
16471   // Set N0 and N1 to hold the inputs to the new wide operation.
16472   N0 = N0->getOperand(0);
16473   if (RHSConst) {
16474     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
16475                      N1->getOperand(0));
16476     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
16477     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, &C[0], C.size());
16478   } else if (RHSTrunc) {
16479     N1 = N1->getOperand(0);
16480   }
16481
16482   // Generate the wide operation.
16483   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
16484   unsigned Opcode = N->getOpcode();
16485   switch (Opcode) {
16486   case ISD::ANY_EXTEND:
16487     return Op;
16488   case ISD::ZERO_EXTEND: {
16489     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
16490     APInt Mask = APInt::getAllOnesValue(InBits);
16491     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
16492     return DAG.getNode(ISD::AND, DL, VT,
16493                        Op, DAG.getConstant(Mask, VT));
16494   }
16495   case ISD::SIGN_EXTEND:
16496     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
16497                        Op, DAG.getValueType(NarrowVT));
16498   default:
16499     llvm_unreachable("Unexpected opcode");
16500   }
16501 }
16502
16503 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
16504                                  TargetLowering::DAGCombinerInfo &DCI,
16505                                  const X86Subtarget *Subtarget) {
16506   EVT VT = N->getValueType(0);
16507   if (DCI.isBeforeLegalizeOps())
16508     return SDValue();
16509
16510   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16511   if (R.getNode())
16512     return R;
16513
16514   // Create BLSI, and BLSR instructions
16515   // BLSI is X & (-X)
16516   // BLSR is X & (X-1)
16517   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
16518     SDValue N0 = N->getOperand(0);
16519     SDValue N1 = N->getOperand(1);
16520     SDLoc DL(N);
16521
16522     // Check LHS for neg
16523     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
16524         isZero(N0.getOperand(0)))
16525       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
16526
16527     // Check RHS for neg
16528     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
16529         isZero(N1.getOperand(0)))
16530       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
16531
16532     // Check LHS for X-1
16533     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16534         isAllOnes(N0.getOperand(1)))
16535       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
16536
16537     // Check RHS for X-1
16538     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16539         isAllOnes(N1.getOperand(1)))
16540       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
16541
16542     return SDValue();
16543   }
16544
16545   // Want to form ANDNP nodes:
16546   // 1) In the hopes of then easily combining them with OR and AND nodes
16547   //    to form PBLEND/PSIGN.
16548   // 2) To match ANDN packed intrinsics
16549   if (VT != MVT::v2i64 && VT != MVT::v4i64)
16550     return SDValue();
16551
16552   SDValue N0 = N->getOperand(0);
16553   SDValue N1 = N->getOperand(1);
16554   SDLoc DL(N);
16555
16556   // Check LHS for vnot
16557   if (N0.getOpcode() == ISD::XOR &&
16558       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
16559       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
16560     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
16561
16562   // Check RHS for vnot
16563   if (N1.getOpcode() == ISD::XOR &&
16564       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
16565       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
16566     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
16567
16568   return SDValue();
16569 }
16570
16571 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
16572                                 TargetLowering::DAGCombinerInfo &DCI,
16573                                 const X86Subtarget *Subtarget) {
16574   EVT VT = N->getValueType(0);
16575   if (DCI.isBeforeLegalizeOps())
16576     return SDValue();
16577
16578   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
16579   if (R.getNode())
16580     return R;
16581
16582   SDValue N0 = N->getOperand(0);
16583   SDValue N1 = N->getOperand(1);
16584
16585   // look for psign/blend
16586   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
16587     if (!Subtarget->hasSSSE3() ||
16588         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
16589       return SDValue();
16590
16591     // Canonicalize pandn to RHS
16592     if (N0.getOpcode() == X86ISD::ANDNP)
16593       std::swap(N0, N1);
16594     // or (and (m, y), (pandn m, x))
16595     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
16596       SDValue Mask = N1.getOperand(0);
16597       SDValue X    = N1.getOperand(1);
16598       SDValue Y;
16599       if (N0.getOperand(0) == Mask)
16600         Y = N0.getOperand(1);
16601       if (N0.getOperand(1) == Mask)
16602         Y = N0.getOperand(0);
16603
16604       // Check to see if the mask appeared in both the AND and ANDNP and
16605       if (!Y.getNode())
16606         return SDValue();
16607
16608       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
16609       // Look through mask bitcast.
16610       if (Mask.getOpcode() == ISD::BITCAST)
16611         Mask = Mask.getOperand(0);
16612       if (X.getOpcode() == ISD::BITCAST)
16613         X = X.getOperand(0);
16614       if (Y.getOpcode() == ISD::BITCAST)
16615         Y = Y.getOperand(0);
16616
16617       EVT MaskVT = Mask.getValueType();
16618
16619       // Validate that the Mask operand is a vector sra node.
16620       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
16621       // there is no psrai.b
16622       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
16623       unsigned SraAmt = ~0;
16624       if (Mask.getOpcode() == ISD::SRA) {
16625         SDValue Amt = Mask.getOperand(1);
16626         if (isSplatVector(Amt.getNode())) {
16627           SDValue SclrAmt = Amt->getOperand(0);
16628           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
16629             SraAmt = C->getZExtValue();
16630         }
16631       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
16632         SDValue SraC = Mask.getOperand(1);
16633         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
16634       }
16635       if ((SraAmt + 1) != EltBits)
16636         return SDValue();
16637
16638       SDLoc DL(N);
16639
16640       // Now we know we at least have a plendvb with the mask val.  See if
16641       // we can form a psignb/w/d.
16642       // psign = x.type == y.type == mask.type && y = sub(0, x);
16643       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
16644           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
16645           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
16646         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
16647                "Unsupported VT for PSIGN");
16648         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
16649         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16650       }
16651       // PBLENDVB only available on SSE 4.1
16652       if (!Subtarget->hasSSE41())
16653         return SDValue();
16654
16655       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
16656
16657       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
16658       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
16659       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
16660       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
16661       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
16662     }
16663   }
16664
16665   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
16666     return SDValue();
16667
16668   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
16669   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
16670     std::swap(N0, N1);
16671   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
16672     return SDValue();
16673   if (!N0.hasOneUse() || !N1.hasOneUse())
16674     return SDValue();
16675
16676   SDValue ShAmt0 = N0.getOperand(1);
16677   if (ShAmt0.getValueType() != MVT::i8)
16678     return SDValue();
16679   SDValue ShAmt1 = N1.getOperand(1);
16680   if (ShAmt1.getValueType() != MVT::i8)
16681     return SDValue();
16682   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
16683     ShAmt0 = ShAmt0.getOperand(0);
16684   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
16685     ShAmt1 = ShAmt1.getOperand(0);
16686
16687   SDLoc DL(N);
16688   unsigned Opc = X86ISD::SHLD;
16689   SDValue Op0 = N0.getOperand(0);
16690   SDValue Op1 = N1.getOperand(0);
16691   if (ShAmt0.getOpcode() == ISD::SUB) {
16692     Opc = X86ISD::SHRD;
16693     std::swap(Op0, Op1);
16694     std::swap(ShAmt0, ShAmt1);
16695   }
16696
16697   unsigned Bits = VT.getSizeInBits();
16698   if (ShAmt1.getOpcode() == ISD::SUB) {
16699     SDValue Sum = ShAmt1.getOperand(0);
16700     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
16701       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
16702       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
16703         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
16704       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
16705         return DAG.getNode(Opc, DL, VT,
16706                            Op0, Op1,
16707                            DAG.getNode(ISD::TRUNCATE, DL,
16708                                        MVT::i8, ShAmt0));
16709     }
16710   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
16711     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
16712     if (ShAmt0C &&
16713         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
16714       return DAG.getNode(Opc, DL, VT,
16715                          N0.getOperand(0), N1.getOperand(0),
16716                          DAG.getNode(ISD::TRUNCATE, DL,
16717                                        MVT::i8, ShAmt0));
16718   }
16719
16720   return SDValue();
16721 }
16722
16723 // Generate NEG and CMOV for integer abs.
16724 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
16725   EVT VT = N->getValueType(0);
16726
16727   // Since X86 does not have CMOV for 8-bit integer, we don't convert
16728   // 8-bit integer abs to NEG and CMOV.
16729   if (VT.isInteger() && VT.getSizeInBits() == 8)
16730     return SDValue();
16731
16732   SDValue N0 = N->getOperand(0);
16733   SDValue N1 = N->getOperand(1);
16734   SDLoc DL(N);
16735
16736   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
16737   // and change it to SUB and CMOV.
16738   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
16739       N0.getOpcode() == ISD::ADD &&
16740       N0.getOperand(1) == N1 &&
16741       N1.getOpcode() == ISD::SRA &&
16742       N1.getOperand(0) == N0.getOperand(0))
16743     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
16744       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
16745         // Generate SUB & CMOV.
16746         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
16747                                   DAG.getConstant(0, VT), N0.getOperand(0));
16748
16749         SDValue Ops[] = { N0.getOperand(0), Neg,
16750                           DAG.getConstant(X86::COND_GE, MVT::i8),
16751                           SDValue(Neg.getNode(), 1) };
16752         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue),
16753                            Ops, array_lengthof(Ops));
16754       }
16755   return SDValue();
16756 }
16757
16758 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
16759 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
16760                                  TargetLowering::DAGCombinerInfo &DCI,
16761                                  const X86Subtarget *Subtarget) {
16762   EVT VT = N->getValueType(0);
16763   if (DCI.isBeforeLegalizeOps())
16764     return SDValue();
16765
16766   if (Subtarget->hasCMov()) {
16767     SDValue RV = performIntegerAbsCombine(N, DAG);
16768     if (RV.getNode())
16769       return RV;
16770   }
16771
16772   // Try forming BMI if it is available.
16773   if (!Subtarget->hasBMI())
16774     return SDValue();
16775
16776   if (VT != MVT::i32 && VT != MVT::i64)
16777     return SDValue();
16778
16779   assert(Subtarget->hasBMI() && "Creating BLSMSK requires BMI instructions");
16780
16781   // Create BLSMSK instructions by finding X ^ (X-1)
16782   SDValue N0 = N->getOperand(0);
16783   SDValue N1 = N->getOperand(1);
16784   SDLoc DL(N);
16785
16786   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
16787       isAllOnes(N0.getOperand(1)))
16788     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
16789
16790   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
16791       isAllOnes(N1.getOperand(1)))
16792     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
16793
16794   return SDValue();
16795 }
16796
16797 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
16798 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
16799                                   TargetLowering::DAGCombinerInfo &DCI,
16800                                   const X86Subtarget *Subtarget) {
16801   LoadSDNode *Ld = cast<LoadSDNode>(N);
16802   EVT RegVT = Ld->getValueType(0);
16803   EVT MemVT = Ld->getMemoryVT();
16804   SDLoc dl(Ld);
16805   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16806   unsigned RegSz = RegVT.getSizeInBits();
16807
16808   // On Sandybridge unaligned 256bit loads are inefficient.
16809   ISD::LoadExtType Ext = Ld->getExtensionType();
16810   unsigned Alignment = Ld->getAlignment();
16811   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
16812   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
16813       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
16814     unsigned NumElems = RegVT.getVectorNumElements();
16815     if (NumElems < 2)
16816       return SDValue();
16817
16818     SDValue Ptr = Ld->getBasePtr();
16819     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
16820
16821     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16822                                   NumElems/2);
16823     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16824                                 Ld->getPointerInfo(), Ld->isVolatile(),
16825                                 Ld->isNonTemporal(), Ld->isInvariant(),
16826                                 Alignment);
16827     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16828     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
16829                                 Ld->getPointerInfo(), Ld->isVolatile(),
16830                                 Ld->isNonTemporal(), Ld->isInvariant(),
16831                                 std::min(16U, Alignment));
16832     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
16833                              Load1.getValue(1),
16834                              Load2.getValue(1));
16835
16836     SDValue NewVec = DAG.getUNDEF(RegVT);
16837     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
16838     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
16839     return DCI.CombineTo(N, NewVec, TF, true);
16840   }
16841
16842   // If this is a vector EXT Load then attempt to optimize it using a
16843   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
16844   // expansion is still better than scalar code.
16845   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
16846   // emit a shuffle and a arithmetic shift.
16847   // TODO: It is possible to support ZExt by zeroing the undef values
16848   // during the shuffle phase or after the shuffle.
16849   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
16850       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
16851     assert(MemVT != RegVT && "Cannot extend to the same type");
16852     assert(MemVT.isVector() && "Must load a vector from memory");
16853
16854     unsigned NumElems = RegVT.getVectorNumElements();
16855     unsigned MemSz = MemVT.getSizeInBits();
16856     assert(RegSz > MemSz && "Register size must be greater than the mem size");
16857
16858     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
16859       return SDValue();
16860
16861     // All sizes must be a power of two.
16862     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
16863       return SDValue();
16864
16865     // Attempt to load the original value using scalar loads.
16866     // Find the largest scalar type that divides the total loaded size.
16867     MVT SclrLoadTy = MVT::i8;
16868     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
16869          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
16870       MVT Tp = (MVT::SimpleValueType)tp;
16871       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
16872         SclrLoadTy = Tp;
16873       }
16874     }
16875
16876     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
16877     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
16878         (64 <= MemSz))
16879       SclrLoadTy = MVT::f64;
16880
16881     // Calculate the number of scalar loads that we need to perform
16882     // in order to load our vector from memory.
16883     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
16884     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
16885       return SDValue();
16886
16887     unsigned loadRegZize = RegSz;
16888     if (Ext == ISD::SEXTLOAD && RegSz == 256)
16889       loadRegZize /= 2;
16890
16891     // Represent our vector as a sequence of elements which are the
16892     // largest scalar that we can load.
16893     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
16894       loadRegZize/SclrLoadTy.getSizeInBits());
16895
16896     // Represent the data using the same element type that is stored in
16897     // memory. In practice, we ''widen'' MemVT.
16898     EVT WideVecVT =
16899           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
16900                        loadRegZize/MemVT.getScalarType().getSizeInBits());
16901
16902     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
16903       "Invalid vector type");
16904
16905     // We can't shuffle using an illegal type.
16906     if (!TLI.isTypeLegal(WideVecVT))
16907       return SDValue();
16908
16909     SmallVector<SDValue, 8> Chains;
16910     SDValue Ptr = Ld->getBasePtr();
16911     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
16912                                         TLI.getPointerTy());
16913     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
16914
16915     for (unsigned i = 0; i < NumLoads; ++i) {
16916       // Perform a single load.
16917       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
16918                                        Ptr, Ld->getPointerInfo(),
16919                                        Ld->isVolatile(), Ld->isNonTemporal(),
16920                                        Ld->isInvariant(), Ld->getAlignment());
16921       Chains.push_back(ScalarLoad.getValue(1));
16922       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
16923       // another round of DAGCombining.
16924       if (i == 0)
16925         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
16926       else
16927         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
16928                           ScalarLoad, DAG.getIntPtrConstant(i));
16929
16930       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
16931     }
16932
16933     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
16934                                Chains.size());
16935
16936     // Bitcast the loaded value to a vector of the original element type, in
16937     // the size of the target vector type.
16938     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
16939     unsigned SizeRatio = RegSz/MemSz;
16940
16941     if (Ext == ISD::SEXTLOAD) {
16942       // If we have SSE4.1 we can directly emit a VSEXT node.
16943       if (Subtarget->hasSSE41()) {
16944         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
16945         return DCI.CombineTo(N, Sext, TF, true);
16946       }
16947
16948       // Otherwise we'll shuffle the small elements in the high bits of the
16949       // larger type and perform an arithmetic shift. If the shift is not legal
16950       // it's better to scalarize.
16951       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
16952         return SDValue();
16953
16954       // Redistribute the loaded elements into the different locations.
16955       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16956       for (unsigned i = 0; i != NumElems; ++i)
16957         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
16958
16959       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16960                                            DAG.getUNDEF(WideVecVT),
16961                                            &ShuffleVec[0]);
16962
16963       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16964
16965       // Build the arithmetic shift.
16966       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
16967                      MemVT.getVectorElementType().getSizeInBits();
16968       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
16969                           DAG.getConstant(Amt, RegVT));
16970
16971       return DCI.CombineTo(N, Shuff, TF, true);
16972     }
16973
16974     // Redistribute the loaded elements into the different locations.
16975     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
16976     for (unsigned i = 0; i != NumElems; ++i)
16977       ShuffleVec[i*SizeRatio] = i;
16978
16979     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
16980                                          DAG.getUNDEF(WideVecVT),
16981                                          &ShuffleVec[0]);
16982
16983     // Bitcast to the requested type.
16984     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
16985     // Replace the original load with the new sequence
16986     // and return the new chain.
16987     return DCI.CombineTo(N, Shuff, TF, true);
16988   }
16989
16990   return SDValue();
16991 }
16992
16993 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
16994 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
16995                                    const X86Subtarget *Subtarget) {
16996   StoreSDNode *St = cast<StoreSDNode>(N);
16997   EVT VT = St->getValue().getValueType();
16998   EVT StVT = St->getMemoryVT();
16999   SDLoc dl(St);
17000   SDValue StoredVal = St->getOperand(1);
17001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17002
17003   // If we are saving a concatenation of two XMM registers, perform two stores.
17004   // On Sandy Bridge, 256-bit memory operations are executed by two
17005   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
17006   // memory  operation.
17007   unsigned Alignment = St->getAlignment();
17008   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
17009   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
17010       StVT == VT && !IsAligned) {
17011     unsigned NumElems = VT.getVectorNumElements();
17012     if (NumElems < 2)
17013       return SDValue();
17014
17015     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
17016     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
17017
17018     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
17019     SDValue Ptr0 = St->getBasePtr();
17020     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
17021
17022     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
17023                                 St->getPointerInfo(), St->isVolatile(),
17024                                 St->isNonTemporal(), Alignment);
17025     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
17026                                 St->getPointerInfo(), St->isVolatile(),
17027                                 St->isNonTemporal(),
17028                                 std::min(16U, Alignment));
17029     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
17030   }
17031
17032   // Optimize trunc store (of multiple scalars) to shuffle and store.
17033   // First, pack all of the elements in one place. Next, store to memory
17034   // in fewer chunks.
17035   if (St->isTruncatingStore() && VT.isVector()) {
17036     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17037     unsigned NumElems = VT.getVectorNumElements();
17038     assert(StVT != VT && "Cannot truncate to the same type");
17039     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
17040     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
17041
17042     // From, To sizes and ElemCount must be pow of two
17043     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
17044     // We are going to use the original vector elt for storing.
17045     // Accumulated smaller vector elements must be a multiple of the store size.
17046     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
17047
17048     unsigned SizeRatio  = FromSz / ToSz;
17049
17050     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
17051
17052     // Create a type on which we perform the shuffle
17053     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
17054             StVT.getScalarType(), NumElems*SizeRatio);
17055
17056     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
17057
17058     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
17059     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
17060     for (unsigned i = 0; i != NumElems; ++i)
17061       ShuffleVec[i] = i * SizeRatio;
17062
17063     // Can't shuffle using an illegal type.
17064     if (!TLI.isTypeLegal(WideVecVT))
17065       return SDValue();
17066
17067     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
17068                                          DAG.getUNDEF(WideVecVT),
17069                                          &ShuffleVec[0]);
17070     // At this point all of the data is stored at the bottom of the
17071     // register. We now need to save it to mem.
17072
17073     // Find the largest store unit
17074     MVT StoreType = MVT::i8;
17075     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
17076          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
17077       MVT Tp = (MVT::SimpleValueType)tp;
17078       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
17079         StoreType = Tp;
17080     }
17081
17082     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
17083     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
17084         (64 <= NumElems * ToSz))
17085       StoreType = MVT::f64;
17086
17087     // Bitcast the original vector into a vector of store-size units
17088     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
17089             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
17090     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
17091     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
17092     SmallVector<SDValue, 8> Chains;
17093     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
17094                                         TLI.getPointerTy());
17095     SDValue Ptr = St->getBasePtr();
17096
17097     // Perform one or more big stores into memory.
17098     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
17099       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
17100                                    StoreType, ShuffWide,
17101                                    DAG.getIntPtrConstant(i));
17102       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
17103                                 St->getPointerInfo(), St->isVolatile(),
17104                                 St->isNonTemporal(), St->getAlignment());
17105       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
17106       Chains.push_back(Ch);
17107     }
17108
17109     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
17110                                Chains.size());
17111   }
17112
17113   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
17114   // the FP state in cases where an emms may be missing.
17115   // A preferable solution to the general problem is to figure out the right
17116   // places to insert EMMS.  This qualifies as a quick hack.
17117
17118   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
17119   if (VT.getSizeInBits() != 64)
17120     return SDValue();
17121
17122   const Function *F = DAG.getMachineFunction().getFunction();
17123   bool NoImplicitFloatOps = F->getAttributes().
17124     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
17125   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
17126                      && Subtarget->hasSSE2();
17127   if ((VT.isVector() ||
17128        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
17129       isa<LoadSDNode>(St->getValue()) &&
17130       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
17131       St->getChain().hasOneUse() && !St->isVolatile()) {
17132     SDNode* LdVal = St->getValue().getNode();
17133     LoadSDNode *Ld = 0;
17134     int TokenFactorIndex = -1;
17135     SmallVector<SDValue, 8> Ops;
17136     SDNode* ChainVal = St->getChain().getNode();
17137     // Must be a store of a load.  We currently handle two cases:  the load
17138     // is a direct child, and it's under an intervening TokenFactor.  It is
17139     // possible to dig deeper under nested TokenFactors.
17140     if (ChainVal == LdVal)
17141       Ld = cast<LoadSDNode>(St->getChain());
17142     else if (St->getValue().hasOneUse() &&
17143              ChainVal->getOpcode() == ISD::TokenFactor) {
17144       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
17145         if (ChainVal->getOperand(i).getNode() == LdVal) {
17146           TokenFactorIndex = i;
17147           Ld = cast<LoadSDNode>(St->getValue());
17148         } else
17149           Ops.push_back(ChainVal->getOperand(i));
17150       }
17151     }
17152
17153     if (!Ld || !ISD::isNormalLoad(Ld))
17154       return SDValue();
17155
17156     // If this is not the MMX case, i.e. we are just turning i64 load/store
17157     // into f64 load/store, avoid the transformation if there are multiple
17158     // uses of the loaded value.
17159     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
17160       return SDValue();
17161
17162     SDLoc LdDL(Ld);
17163     SDLoc StDL(N);
17164     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
17165     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
17166     // pair instead.
17167     if (Subtarget->is64Bit() || F64IsLegal) {
17168       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
17169       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
17170                                   Ld->getPointerInfo(), Ld->isVolatile(),
17171                                   Ld->isNonTemporal(), Ld->isInvariant(),
17172                                   Ld->getAlignment());
17173       SDValue NewChain = NewLd.getValue(1);
17174       if (TokenFactorIndex != -1) {
17175         Ops.push_back(NewChain);
17176         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17177                                Ops.size());
17178       }
17179       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
17180                           St->getPointerInfo(),
17181                           St->isVolatile(), St->isNonTemporal(),
17182                           St->getAlignment());
17183     }
17184
17185     // Otherwise, lower to two pairs of 32-bit loads / stores.
17186     SDValue LoAddr = Ld->getBasePtr();
17187     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
17188                                  DAG.getConstant(4, MVT::i32));
17189
17190     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
17191                                Ld->getPointerInfo(),
17192                                Ld->isVolatile(), Ld->isNonTemporal(),
17193                                Ld->isInvariant(), Ld->getAlignment());
17194     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
17195                                Ld->getPointerInfo().getWithOffset(4),
17196                                Ld->isVolatile(), Ld->isNonTemporal(),
17197                                Ld->isInvariant(),
17198                                MinAlign(Ld->getAlignment(), 4));
17199
17200     SDValue NewChain = LoLd.getValue(1);
17201     if (TokenFactorIndex != -1) {
17202       Ops.push_back(LoLd);
17203       Ops.push_back(HiLd);
17204       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
17205                              Ops.size());
17206     }
17207
17208     LoAddr = St->getBasePtr();
17209     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
17210                          DAG.getConstant(4, MVT::i32));
17211
17212     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
17213                                 St->getPointerInfo(),
17214                                 St->isVolatile(), St->isNonTemporal(),
17215                                 St->getAlignment());
17216     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
17217                                 St->getPointerInfo().getWithOffset(4),
17218                                 St->isVolatile(),
17219                                 St->isNonTemporal(),
17220                                 MinAlign(St->getAlignment(), 4));
17221     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
17222   }
17223   return SDValue();
17224 }
17225
17226 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
17227 /// and return the operands for the horizontal operation in LHS and RHS.  A
17228 /// horizontal operation performs the binary operation on successive elements
17229 /// of its first operand, then on successive elements of its second operand,
17230 /// returning the resulting values in a vector.  For example, if
17231 ///   A = < float a0, float a1, float a2, float a3 >
17232 /// and
17233 ///   B = < float b0, float b1, float b2, float b3 >
17234 /// then the result of doing a horizontal operation on A and B is
17235 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
17236 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
17237 /// A horizontal-op B, for some already available A and B, and if so then LHS is
17238 /// set to A, RHS to B, and the routine returns 'true'.
17239 /// Note that the binary operation should have the property that if one of the
17240 /// operands is UNDEF then the result is UNDEF.
17241 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
17242   // Look for the following pattern: if
17243   //   A = < float a0, float a1, float a2, float a3 >
17244   //   B = < float b0, float b1, float b2, float b3 >
17245   // and
17246   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
17247   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
17248   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
17249   // which is A horizontal-op B.
17250
17251   // At least one of the operands should be a vector shuffle.
17252   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
17253       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
17254     return false;
17255
17256   EVT VT = LHS.getValueType();
17257
17258   assert((VT.is128BitVector() || VT.is256BitVector()) &&
17259          "Unsupported vector type for horizontal add/sub");
17260
17261   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
17262   // operate independently on 128-bit lanes.
17263   unsigned NumElts = VT.getVectorNumElements();
17264   unsigned NumLanes = VT.getSizeInBits()/128;
17265   unsigned NumLaneElts = NumElts / NumLanes;
17266   assert((NumLaneElts % 2 == 0) &&
17267          "Vector type should have an even number of elements in each lane");
17268   unsigned HalfLaneElts = NumLaneElts/2;
17269
17270   // View LHS in the form
17271   //   LHS = VECTOR_SHUFFLE A, B, LMask
17272   // If LHS is not a shuffle then pretend it is the shuffle
17273   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
17274   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
17275   // type VT.
17276   SDValue A, B;
17277   SmallVector<int, 16> LMask(NumElts);
17278   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17279     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
17280       A = LHS.getOperand(0);
17281     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
17282       B = LHS.getOperand(1);
17283     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
17284     std::copy(Mask.begin(), Mask.end(), LMask.begin());
17285   } else {
17286     if (LHS.getOpcode() != ISD::UNDEF)
17287       A = LHS;
17288     for (unsigned i = 0; i != NumElts; ++i)
17289       LMask[i] = i;
17290   }
17291
17292   // Likewise, view RHS in the form
17293   //   RHS = VECTOR_SHUFFLE C, D, RMask
17294   SDValue C, D;
17295   SmallVector<int, 16> RMask(NumElts);
17296   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
17297     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
17298       C = RHS.getOperand(0);
17299     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
17300       D = RHS.getOperand(1);
17301     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
17302     std::copy(Mask.begin(), Mask.end(), RMask.begin());
17303   } else {
17304     if (RHS.getOpcode() != ISD::UNDEF)
17305       C = RHS;
17306     for (unsigned i = 0; i != NumElts; ++i)
17307       RMask[i] = i;
17308   }
17309
17310   // Check that the shuffles are both shuffling the same vectors.
17311   if (!(A == C && B == D) && !(A == D && B == C))
17312     return false;
17313
17314   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
17315   if (!A.getNode() && !B.getNode())
17316     return false;
17317
17318   // If A and B occur in reverse order in RHS, then "swap" them (which means
17319   // rewriting the mask).
17320   if (A != C)
17321     CommuteVectorShuffleMask(RMask, NumElts);
17322
17323   // At this point LHS and RHS are equivalent to
17324   //   LHS = VECTOR_SHUFFLE A, B, LMask
17325   //   RHS = VECTOR_SHUFFLE A, B, RMask
17326   // Check that the masks correspond to performing a horizontal operation.
17327   for (unsigned i = 0; i != NumElts; ++i) {
17328     int LIdx = LMask[i], RIdx = RMask[i];
17329
17330     // Ignore any UNDEF components.
17331     if (LIdx < 0 || RIdx < 0 ||
17332         (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
17333         (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
17334       continue;
17335
17336     // Check that successive elements are being operated on.  If not, this is
17337     // not a horizontal operation.
17338     unsigned Src = (i/HalfLaneElts) % 2; // each lane is split between srcs
17339     unsigned LaneStart = (i/NumLaneElts) * NumLaneElts;
17340     int Index = 2*(i%HalfLaneElts) + NumElts*Src + LaneStart;
17341     if (!(LIdx == Index && RIdx == Index + 1) &&
17342         !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
17343       return false;
17344   }
17345
17346   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
17347   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
17348   return true;
17349 }
17350
17351 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
17352 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
17353                                   const X86Subtarget *Subtarget) {
17354   EVT VT = N->getValueType(0);
17355   SDValue LHS = N->getOperand(0);
17356   SDValue RHS = N->getOperand(1);
17357
17358   // Try to synthesize horizontal adds from adds of shuffles.
17359   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17360        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17361       isHorizontalBinOp(LHS, RHS, true))
17362     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
17363   return SDValue();
17364 }
17365
17366 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
17367 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
17368                                   const X86Subtarget *Subtarget) {
17369   EVT VT = N->getValueType(0);
17370   SDValue LHS = N->getOperand(0);
17371   SDValue RHS = N->getOperand(1);
17372
17373   // Try to synthesize horizontal subs from subs of shuffles.
17374   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
17375        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
17376       isHorizontalBinOp(LHS, RHS, false))
17377     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
17378   return SDValue();
17379 }
17380
17381 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
17382 /// X86ISD::FXOR nodes.
17383 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
17384   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
17385   // F[X]OR(0.0, x) -> x
17386   // F[X]OR(x, 0.0) -> x
17387   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17388     if (C->getValueAPF().isPosZero())
17389       return N->getOperand(1);
17390   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17391     if (C->getValueAPF().isPosZero())
17392       return N->getOperand(0);
17393   return SDValue();
17394 }
17395
17396 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
17397 /// X86ISD::FMAX nodes.
17398 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
17399   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
17400
17401   // Only perform optimizations if UnsafeMath is used.
17402   if (!DAG.getTarget().Options.UnsafeFPMath)
17403     return SDValue();
17404
17405   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
17406   // into FMINC and FMAXC, which are Commutative operations.
17407   unsigned NewOp = 0;
17408   switch (N->getOpcode()) {
17409     default: llvm_unreachable("unknown opcode");
17410     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
17411     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
17412   }
17413
17414   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
17415                      N->getOperand(0), N->getOperand(1));
17416 }
17417
17418 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
17419 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
17420   // FAND(0.0, x) -> 0.0
17421   // FAND(x, 0.0) -> 0.0
17422   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
17423     if (C->getValueAPF().isPosZero())
17424       return N->getOperand(0);
17425   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
17426     if (C->getValueAPF().isPosZero())
17427       return N->getOperand(1);
17428   return SDValue();
17429 }
17430
17431 static SDValue PerformBTCombine(SDNode *N,
17432                                 SelectionDAG &DAG,
17433                                 TargetLowering::DAGCombinerInfo &DCI) {
17434   // BT ignores high bits in the bit index operand.
17435   SDValue Op1 = N->getOperand(1);
17436   if (Op1.hasOneUse()) {
17437     unsigned BitWidth = Op1.getValueSizeInBits();
17438     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
17439     APInt KnownZero, KnownOne;
17440     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
17441                                           !DCI.isBeforeLegalizeOps());
17442     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17443     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
17444         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
17445       DCI.CommitTargetLoweringOpt(TLO);
17446   }
17447   return SDValue();
17448 }
17449
17450 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
17451   SDValue Op = N->getOperand(0);
17452   if (Op.getOpcode() == ISD::BITCAST)
17453     Op = Op.getOperand(0);
17454   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
17455   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
17456       VT.getVectorElementType().getSizeInBits() ==
17457       OpVT.getVectorElementType().getSizeInBits()) {
17458     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
17459   }
17460   return SDValue();
17461 }
17462
17463 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
17464                                                const X86Subtarget *Subtarget) {
17465   EVT VT = N->getValueType(0);
17466   if (!VT.isVector())
17467     return SDValue();
17468
17469   SDValue N0 = N->getOperand(0);
17470   SDValue N1 = N->getOperand(1);
17471   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
17472   SDLoc dl(N);
17473
17474   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
17475   // both SSE and AVX2 since there is no sign-extended shift right
17476   // operation on a vector with 64-bit elements.
17477   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
17478   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
17479   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
17480       N0.getOpcode() == ISD::SIGN_EXTEND)) {
17481     SDValue N00 = N0.getOperand(0);
17482
17483     // EXTLOAD has a better solution on AVX2,
17484     // it may be replaced with X86ISD::VSEXT node.
17485     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
17486       if (!ISD::isNormalLoad(N00.getNode()))
17487         return SDValue();
17488
17489     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
17490         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
17491                                   N00, N1);
17492       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
17493     }
17494   }
17495   return SDValue();
17496 }
17497
17498 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
17499                                   TargetLowering::DAGCombinerInfo &DCI,
17500                                   const X86Subtarget *Subtarget) {
17501   if (!DCI.isBeforeLegalizeOps())
17502     return SDValue();
17503
17504   if (!Subtarget->hasFp256())
17505     return SDValue();
17506
17507   EVT VT = N->getValueType(0);
17508   if (VT.isVector() && VT.getSizeInBits() == 256) {
17509     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17510     if (R.getNode())
17511       return R;
17512   }
17513
17514   return SDValue();
17515 }
17516
17517 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
17518                                  const X86Subtarget* Subtarget) {
17519   SDLoc dl(N);
17520   EVT VT = N->getValueType(0);
17521
17522   // Let legalize expand this if it isn't a legal type yet.
17523   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17524     return SDValue();
17525
17526   EVT ScalarVT = VT.getScalarType();
17527   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
17528       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
17529     return SDValue();
17530
17531   SDValue A = N->getOperand(0);
17532   SDValue B = N->getOperand(1);
17533   SDValue C = N->getOperand(2);
17534
17535   bool NegA = (A.getOpcode() == ISD::FNEG);
17536   bool NegB = (B.getOpcode() == ISD::FNEG);
17537   bool NegC = (C.getOpcode() == ISD::FNEG);
17538
17539   // Negative multiplication when NegA xor NegB
17540   bool NegMul = (NegA != NegB);
17541   if (NegA)
17542     A = A.getOperand(0);
17543   if (NegB)
17544     B = B.getOperand(0);
17545   if (NegC)
17546     C = C.getOperand(0);
17547
17548   unsigned Opcode;
17549   if (!NegMul)
17550     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
17551   else
17552     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
17553
17554   return DAG.getNode(Opcode, dl, VT, A, B, C);
17555 }
17556
17557 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
17558                                   TargetLowering::DAGCombinerInfo &DCI,
17559                                   const X86Subtarget *Subtarget) {
17560   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
17561   //           (and (i32 x86isd::setcc_carry), 1)
17562   // This eliminates the zext. This transformation is necessary because
17563   // ISD::SETCC is always legalized to i8.
17564   SDLoc dl(N);
17565   SDValue N0 = N->getOperand(0);
17566   EVT VT = N->getValueType(0);
17567
17568   if (N0.getOpcode() == ISD::AND &&
17569       N0.hasOneUse() &&
17570       N0.getOperand(0).hasOneUse()) {
17571     SDValue N00 = N0.getOperand(0);
17572     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
17573       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
17574       if (!C || C->getZExtValue() != 1)
17575         return SDValue();
17576       return DAG.getNode(ISD::AND, dl, VT,
17577                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
17578                                      N00.getOperand(0), N00.getOperand(1)),
17579                          DAG.getConstant(1, VT));
17580     }
17581   }
17582
17583   if (VT.is256BitVector()) {
17584     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
17585     if (R.getNode())
17586       return R;
17587   }
17588
17589   return SDValue();
17590 }
17591
17592 // Optimize x == -y --> x+y == 0
17593 //          x != -y --> x+y != 0
17594 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG) {
17595   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
17596   SDValue LHS = N->getOperand(0);
17597   SDValue RHS = N->getOperand(1);
17598
17599   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
17600     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
17601       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
17602         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17603                                    LHS.getValueType(), RHS, LHS.getOperand(1));
17604         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17605                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17606       }
17607   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
17608     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
17609       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
17610         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
17611                                    RHS.getValueType(), LHS, RHS.getOperand(1));
17612         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
17613                             addV, DAG.getConstant(0, addV.getValueType()), CC);
17614       }
17615   return SDValue();
17616 }
17617
17618 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
17619 // as "sbb reg,reg", since it can be extended without zext and produces
17620 // an all-ones bit which is more useful than 0/1 in some cases.
17621 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG) {
17622   return DAG.getNode(ISD::AND, DL, MVT::i8,
17623                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
17624                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
17625                      DAG.getConstant(1, MVT::i8));
17626 }
17627
17628 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
17629 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
17630                                    TargetLowering::DAGCombinerInfo &DCI,
17631                                    const X86Subtarget *Subtarget) {
17632   SDLoc DL(N);
17633   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
17634   SDValue EFLAGS = N->getOperand(1);
17635
17636   if (CC == X86::COND_A) {
17637     // Try to convert COND_A into COND_B in an attempt to facilitate
17638     // materializing "setb reg".
17639     //
17640     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
17641     // cannot take an immediate as its first operand.
17642     //
17643     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
17644         EFLAGS.getValueType().isInteger() &&
17645         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
17646       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
17647                                    EFLAGS.getNode()->getVTList(),
17648                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
17649       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
17650       return MaterializeSETB(DL, NewEFLAGS, DAG);
17651     }
17652   }
17653
17654   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
17655   // a zext and produces an all-ones bit which is more useful than 0/1 in some
17656   // cases.
17657   if (CC == X86::COND_B)
17658     return MaterializeSETB(DL, EFLAGS, DAG);
17659
17660   SDValue Flags;
17661
17662   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17663   if (Flags.getNode()) {
17664     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17665     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
17666   }
17667
17668   return SDValue();
17669 }
17670
17671 // Optimize branch condition evaluation.
17672 //
17673 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
17674                                     TargetLowering::DAGCombinerInfo &DCI,
17675                                     const X86Subtarget *Subtarget) {
17676   SDLoc DL(N);
17677   SDValue Chain = N->getOperand(0);
17678   SDValue Dest = N->getOperand(1);
17679   SDValue EFLAGS = N->getOperand(3);
17680   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
17681
17682   SDValue Flags;
17683
17684   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
17685   if (Flags.getNode()) {
17686     SDValue Cond = DAG.getConstant(CC, MVT::i8);
17687     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
17688                        Flags);
17689   }
17690
17691   return SDValue();
17692 }
17693
17694 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
17695                                         const X86TargetLowering *XTLI) {
17696   SDValue Op0 = N->getOperand(0);
17697   EVT InVT = Op0->getValueType(0);
17698
17699   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
17700   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
17701     SDLoc dl(N);
17702     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
17703     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
17704     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
17705   }
17706
17707   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
17708   // a 32-bit target where SSE doesn't support i64->FP operations.
17709   if (Op0.getOpcode() == ISD::LOAD) {
17710     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
17711     EVT VT = Ld->getValueType(0);
17712     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
17713         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
17714         !XTLI->getSubtarget()->is64Bit() &&
17715         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17716       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
17717                                           Ld->getChain(), Op0, DAG);
17718       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
17719       return FILDChain;
17720     }
17721   }
17722   return SDValue();
17723 }
17724
17725 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
17726 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
17727                                  X86TargetLowering::DAGCombinerInfo &DCI) {
17728   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
17729   // the result is either zero or one (depending on the input carry bit).
17730   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
17731   if (X86::isZeroNode(N->getOperand(0)) &&
17732       X86::isZeroNode(N->getOperand(1)) &&
17733       // We don't have a good way to replace an EFLAGS use, so only do this when
17734       // dead right now.
17735       SDValue(N, 1).use_empty()) {
17736     SDLoc DL(N);
17737     EVT VT = N->getValueType(0);
17738     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
17739     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
17740                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
17741                                            DAG.getConstant(X86::COND_B,MVT::i8),
17742                                            N->getOperand(2)),
17743                                DAG.getConstant(1, VT));
17744     return DCI.CombineTo(N, Res1, CarryOut);
17745   }
17746
17747   return SDValue();
17748 }
17749
17750 // fold (add Y, (sete  X, 0)) -> adc  0, Y
17751 //      (add Y, (setne X, 0)) -> sbb -1, Y
17752 //      (sub (sete  X, 0), Y) -> sbb  0, Y
17753 //      (sub (setne X, 0), Y) -> adc -1, Y
17754 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
17755   SDLoc DL(N);
17756
17757   // Look through ZExts.
17758   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
17759   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
17760     return SDValue();
17761
17762   SDValue SetCC = Ext.getOperand(0);
17763   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
17764     return SDValue();
17765
17766   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
17767   if (CC != X86::COND_E && CC != X86::COND_NE)
17768     return SDValue();
17769
17770   SDValue Cmp = SetCC.getOperand(1);
17771   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
17772       !X86::isZeroNode(Cmp.getOperand(1)) ||
17773       !Cmp.getOperand(0).getValueType().isInteger())
17774     return SDValue();
17775
17776   SDValue CmpOp0 = Cmp.getOperand(0);
17777   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
17778                                DAG.getConstant(1, CmpOp0.getValueType()));
17779
17780   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
17781   if (CC == X86::COND_NE)
17782     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
17783                        DL, OtherVal.getValueType(), OtherVal,
17784                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
17785   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
17786                      DL, OtherVal.getValueType(), OtherVal,
17787                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
17788 }
17789
17790 /// PerformADDCombine - Do target-specific dag combines on integer adds.
17791 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
17792                                  const X86Subtarget *Subtarget) {
17793   EVT VT = N->getValueType(0);
17794   SDValue Op0 = N->getOperand(0);
17795   SDValue Op1 = N->getOperand(1);
17796
17797   // Try to synthesize horizontal adds from adds of shuffles.
17798   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17799        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17800       isHorizontalBinOp(Op0, Op1, true))
17801     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
17802
17803   return OptimizeConditionalInDecrement(N, DAG);
17804 }
17805
17806 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
17807                                  const X86Subtarget *Subtarget) {
17808   SDValue Op0 = N->getOperand(0);
17809   SDValue Op1 = N->getOperand(1);
17810
17811   // X86 can't encode an immediate LHS of a sub. See if we can push the
17812   // negation into a preceding instruction.
17813   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
17814     // If the RHS of the sub is a XOR with one use and a constant, invert the
17815     // immediate. Then add one to the LHS of the sub so we can turn
17816     // X-Y -> X+~Y+1, saving one register.
17817     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
17818         isa<ConstantSDNode>(Op1.getOperand(1))) {
17819       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
17820       EVT VT = Op0.getValueType();
17821       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
17822                                    Op1.getOperand(0),
17823                                    DAG.getConstant(~XorC, VT));
17824       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
17825                          DAG.getConstant(C->getAPIntValue()+1, VT));
17826     }
17827   }
17828
17829   // Try to synthesize horizontal adds from adds of shuffles.
17830   EVT VT = N->getValueType(0);
17831   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
17832        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
17833       isHorizontalBinOp(Op0, Op1, true))
17834     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
17835
17836   return OptimizeConditionalInDecrement(N, DAG);
17837 }
17838
17839 /// performVZEXTCombine - Performs build vector combines
17840 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
17841                                         TargetLowering::DAGCombinerInfo &DCI,
17842                                         const X86Subtarget *Subtarget) {
17843   // (vzext (bitcast (vzext (x)) -> (vzext x)
17844   SDValue In = N->getOperand(0);
17845   while (In.getOpcode() == ISD::BITCAST)
17846     In = In.getOperand(0);
17847
17848   if (In.getOpcode() != X86ISD::VZEXT)
17849     return SDValue();
17850
17851   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
17852                      In.getOperand(0));
17853 }
17854
17855 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
17856                                              DAGCombinerInfo &DCI) const {
17857   SelectionDAG &DAG = DCI.DAG;
17858   switch (N->getOpcode()) {
17859   default: break;
17860   case ISD::EXTRACT_VECTOR_ELT:
17861     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
17862   case ISD::VSELECT:
17863   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
17864   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
17865   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
17866   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
17867   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
17868   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
17869   case ISD::SHL:
17870   case ISD::SRA:
17871   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
17872   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
17873   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
17874   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
17875   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
17876   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
17877   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
17878   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
17879   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
17880   case X86ISD::FXOR:
17881   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
17882   case X86ISD::FMIN:
17883   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
17884   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
17885   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
17886   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
17887   case ISD::ANY_EXTEND:
17888   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
17889   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
17890   case ISD::SIGN_EXTEND_INREG: return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
17891   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
17892   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG);
17893   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
17894   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
17895   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
17896   case X86ISD::SHUFP:       // Handle all target specific shuffles
17897   case X86ISD::PALIGNR:
17898   case X86ISD::UNPCKH:
17899   case X86ISD::UNPCKL:
17900   case X86ISD::MOVHLPS:
17901   case X86ISD::MOVLHPS:
17902   case X86ISD::PSHUFD:
17903   case X86ISD::PSHUFHW:
17904   case X86ISD::PSHUFLW:
17905   case X86ISD::MOVSS:
17906   case X86ISD::MOVSD:
17907   case X86ISD::VPERMILP:
17908   case X86ISD::VPERM2X128:
17909   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
17910   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
17911   }
17912
17913   return SDValue();
17914 }
17915
17916 /// isTypeDesirableForOp - Return true if the target has native support for
17917 /// the specified value type and it is 'desirable' to use the type for the
17918 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
17919 /// instruction encodings are longer and some i16 instructions are slow.
17920 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
17921   if (!isTypeLegal(VT))
17922     return false;
17923   if (VT != MVT::i16)
17924     return true;
17925
17926   switch (Opc) {
17927   default:
17928     return true;
17929   case ISD::LOAD:
17930   case ISD::SIGN_EXTEND:
17931   case ISD::ZERO_EXTEND:
17932   case ISD::ANY_EXTEND:
17933   case ISD::SHL:
17934   case ISD::SRL:
17935   case ISD::SUB:
17936   case ISD::ADD:
17937   case ISD::MUL:
17938   case ISD::AND:
17939   case ISD::OR:
17940   case ISD::XOR:
17941     return false;
17942   }
17943 }
17944
17945 /// IsDesirableToPromoteOp - This method query the target whether it is
17946 /// beneficial for dag combiner to promote the specified node. If true, it
17947 /// should return the desired promotion type by reference.
17948 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
17949   EVT VT = Op.getValueType();
17950   if (VT != MVT::i16)
17951     return false;
17952
17953   bool Promote = false;
17954   bool Commute = false;
17955   switch (Op.getOpcode()) {
17956   default: break;
17957   case ISD::LOAD: {
17958     LoadSDNode *LD = cast<LoadSDNode>(Op);
17959     // If the non-extending load has a single use and it's not live out, then it
17960     // might be folded.
17961     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
17962                                                      Op.hasOneUse()*/) {
17963       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
17964              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
17965         // The only case where we'd want to promote LOAD (rather then it being
17966         // promoted as an operand is when it's only use is liveout.
17967         if (UI->getOpcode() != ISD::CopyToReg)
17968           return false;
17969       }
17970     }
17971     Promote = true;
17972     break;
17973   }
17974   case ISD::SIGN_EXTEND:
17975   case ISD::ZERO_EXTEND:
17976   case ISD::ANY_EXTEND:
17977     Promote = true;
17978     break;
17979   case ISD::SHL:
17980   case ISD::SRL: {
17981     SDValue N0 = Op.getOperand(0);
17982     // Look out for (store (shl (load), x)).
17983     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
17984       return false;
17985     Promote = true;
17986     break;
17987   }
17988   case ISD::ADD:
17989   case ISD::MUL:
17990   case ISD::AND:
17991   case ISD::OR:
17992   case ISD::XOR:
17993     Commute = true;
17994     // fallthrough
17995   case ISD::SUB: {
17996     SDValue N0 = Op.getOperand(0);
17997     SDValue N1 = Op.getOperand(1);
17998     if (!Commute && MayFoldLoad(N1))
17999       return false;
18000     // Avoid disabling potential load folding opportunities.
18001     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
18002       return false;
18003     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
18004       return false;
18005     Promote = true;
18006   }
18007   }
18008
18009   PVT = MVT::i32;
18010   return Promote;
18011 }
18012
18013 //===----------------------------------------------------------------------===//
18014 //                           X86 Inline Assembly Support
18015 //===----------------------------------------------------------------------===//
18016
18017 namespace {
18018   // Helper to match a string separated by whitespace.
18019   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
18020     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
18021
18022     for (unsigned i = 0, e = args.size(); i != e; ++i) {
18023       StringRef piece(*args[i]);
18024       if (!s.startswith(piece)) // Check if the piece matches.
18025         return false;
18026
18027       s = s.substr(piece.size());
18028       StringRef::size_type pos = s.find_first_not_of(" \t");
18029       if (pos == 0) // We matched a prefix.
18030         return false;
18031
18032       s = s.substr(pos);
18033     }
18034
18035     return s.empty();
18036   }
18037   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
18038 }
18039
18040 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
18041   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
18042
18043   std::string AsmStr = IA->getAsmString();
18044
18045   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
18046   if (!Ty || Ty->getBitWidth() % 16 != 0)
18047     return false;
18048
18049   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
18050   SmallVector<StringRef, 4> AsmPieces;
18051   SplitString(AsmStr, AsmPieces, ";\n");
18052
18053   switch (AsmPieces.size()) {
18054   default: return false;
18055   case 1:
18056     // FIXME: this should verify that we are targeting a 486 or better.  If not,
18057     // we will turn this bswap into something that will be lowered to logical
18058     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
18059     // lower so don't worry about this.
18060     // bswap $0
18061     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
18062         matchAsm(AsmPieces[0], "bswapl", "$0") ||
18063         matchAsm(AsmPieces[0], "bswapq", "$0") ||
18064         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
18065         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
18066         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
18067       // No need to check constraints, nothing other than the equivalent of
18068       // "=r,0" would be valid here.
18069       return IntrinsicLowering::LowerToByteSwap(CI);
18070     }
18071
18072     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
18073     if (CI->getType()->isIntegerTy(16) &&
18074         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18075         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
18076          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
18077       AsmPieces.clear();
18078       const std::string &ConstraintsStr = IA->getConstraintString();
18079       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18080       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18081       if (AsmPieces.size() == 4 &&
18082           AsmPieces[0] == "~{cc}" &&
18083           AsmPieces[1] == "~{dirflag}" &&
18084           AsmPieces[2] == "~{flags}" &&
18085           AsmPieces[3] == "~{fpsr}")
18086       return IntrinsicLowering::LowerToByteSwap(CI);
18087     }
18088     break;
18089   case 3:
18090     if (CI->getType()->isIntegerTy(32) &&
18091         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
18092         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
18093         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
18094         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
18095       AsmPieces.clear();
18096       const std::string &ConstraintsStr = IA->getConstraintString();
18097       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
18098       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
18099       if (AsmPieces.size() == 4 &&
18100           AsmPieces[0] == "~{cc}" &&
18101           AsmPieces[1] == "~{dirflag}" &&
18102           AsmPieces[2] == "~{flags}" &&
18103           AsmPieces[3] == "~{fpsr}")
18104         return IntrinsicLowering::LowerToByteSwap(CI);
18105     }
18106
18107     if (CI->getType()->isIntegerTy(64)) {
18108       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
18109       if (Constraints.size() >= 2 &&
18110           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
18111           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
18112         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
18113         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
18114             matchAsm(AsmPieces[1], "bswap", "%edx") &&
18115             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
18116           return IntrinsicLowering::LowerToByteSwap(CI);
18117       }
18118     }
18119     break;
18120   }
18121   return false;
18122 }
18123
18124 /// getConstraintType - Given a constraint letter, return the type of
18125 /// constraint it is for this target.
18126 X86TargetLowering::ConstraintType
18127 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
18128   if (Constraint.size() == 1) {
18129     switch (Constraint[0]) {
18130     case 'R':
18131     case 'q':
18132     case 'Q':
18133     case 'f':
18134     case 't':
18135     case 'u':
18136     case 'y':
18137     case 'x':
18138     case 'Y':
18139     case 'l':
18140       return C_RegisterClass;
18141     case 'a':
18142     case 'b':
18143     case 'c':
18144     case 'd':
18145     case 'S':
18146     case 'D':
18147     case 'A':
18148       return C_Register;
18149     case 'I':
18150     case 'J':
18151     case 'K':
18152     case 'L':
18153     case 'M':
18154     case 'N':
18155     case 'G':
18156     case 'C':
18157     case 'e':
18158     case 'Z':
18159       return C_Other;
18160     default:
18161       break;
18162     }
18163   }
18164   return TargetLowering::getConstraintType(Constraint);
18165 }
18166
18167 /// Examine constraint type and operand type and determine a weight value.
18168 /// This object must already have been set up with the operand type
18169 /// and the current alternative constraint selected.
18170 TargetLowering::ConstraintWeight
18171   X86TargetLowering::getSingleConstraintMatchWeight(
18172     AsmOperandInfo &info, const char *constraint) const {
18173   ConstraintWeight weight = CW_Invalid;
18174   Value *CallOperandVal = info.CallOperandVal;
18175     // If we don't have a value, we can't do a match,
18176     // but allow it at the lowest weight.
18177   if (CallOperandVal == NULL)
18178     return CW_Default;
18179   Type *type = CallOperandVal->getType();
18180   // Look at the constraint type.
18181   switch (*constraint) {
18182   default:
18183     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
18184   case 'R':
18185   case 'q':
18186   case 'Q':
18187   case 'a':
18188   case 'b':
18189   case 'c':
18190   case 'd':
18191   case 'S':
18192   case 'D':
18193   case 'A':
18194     if (CallOperandVal->getType()->isIntegerTy())
18195       weight = CW_SpecificReg;
18196     break;
18197   case 'f':
18198   case 't':
18199   case 'u':
18200     if (type->isFloatingPointTy())
18201       weight = CW_SpecificReg;
18202     break;
18203   case 'y':
18204     if (type->isX86_MMXTy() && Subtarget->hasMMX())
18205       weight = CW_SpecificReg;
18206     break;
18207   case 'x':
18208   case 'Y':
18209     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
18210         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
18211       weight = CW_Register;
18212     break;
18213   case 'I':
18214     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
18215       if (C->getZExtValue() <= 31)
18216         weight = CW_Constant;
18217     }
18218     break;
18219   case 'J':
18220     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18221       if (C->getZExtValue() <= 63)
18222         weight = CW_Constant;
18223     }
18224     break;
18225   case 'K':
18226     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18227       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
18228         weight = CW_Constant;
18229     }
18230     break;
18231   case 'L':
18232     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18233       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
18234         weight = CW_Constant;
18235     }
18236     break;
18237   case 'M':
18238     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18239       if (C->getZExtValue() <= 3)
18240         weight = CW_Constant;
18241     }
18242     break;
18243   case 'N':
18244     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18245       if (C->getZExtValue() <= 0xff)
18246         weight = CW_Constant;
18247     }
18248     break;
18249   case 'G':
18250   case 'C':
18251     if (dyn_cast<ConstantFP>(CallOperandVal)) {
18252       weight = CW_Constant;
18253     }
18254     break;
18255   case 'e':
18256     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18257       if ((C->getSExtValue() >= -0x80000000LL) &&
18258           (C->getSExtValue() <= 0x7fffffffLL))
18259         weight = CW_Constant;
18260     }
18261     break;
18262   case 'Z':
18263     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
18264       if (C->getZExtValue() <= 0xffffffff)
18265         weight = CW_Constant;
18266     }
18267     break;
18268   }
18269   return weight;
18270 }
18271
18272 /// LowerXConstraint - try to replace an X constraint, which matches anything,
18273 /// with another that has more specific requirements based on the type of the
18274 /// corresponding operand.
18275 const char *X86TargetLowering::
18276 LowerXConstraint(EVT ConstraintVT) const {
18277   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
18278   // 'f' like normal targets.
18279   if (ConstraintVT.isFloatingPoint()) {
18280     if (Subtarget->hasSSE2())
18281       return "Y";
18282     if (Subtarget->hasSSE1())
18283       return "x";
18284   }
18285
18286   return TargetLowering::LowerXConstraint(ConstraintVT);
18287 }
18288
18289 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
18290 /// vector.  If it is invalid, don't add anything to Ops.
18291 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
18292                                                      std::string &Constraint,
18293                                                      std::vector<SDValue>&Ops,
18294                                                      SelectionDAG &DAG) const {
18295   SDValue Result(0, 0);
18296
18297   // Only support length 1 constraints for now.
18298   if (Constraint.length() > 1) return;
18299
18300   char ConstraintLetter = Constraint[0];
18301   switch (ConstraintLetter) {
18302   default: break;
18303   case 'I':
18304     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18305       if (C->getZExtValue() <= 31) {
18306         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18307         break;
18308       }
18309     }
18310     return;
18311   case 'J':
18312     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18313       if (C->getZExtValue() <= 63) {
18314         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18315         break;
18316       }
18317     }
18318     return;
18319   case 'K':
18320     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18321       if (isInt<8>(C->getSExtValue())) {
18322         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18323         break;
18324       }
18325     }
18326     return;
18327   case 'N':
18328     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18329       if (C->getZExtValue() <= 255) {
18330         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18331         break;
18332       }
18333     }
18334     return;
18335   case 'e': {
18336     // 32-bit signed value
18337     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18338       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18339                                            C->getSExtValue())) {
18340         // Widen to 64 bits here to get it sign extended.
18341         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
18342         break;
18343       }
18344     // FIXME gcc accepts some relocatable values here too, but only in certain
18345     // memory models; it's complicated.
18346     }
18347     return;
18348   }
18349   case 'Z': {
18350     // 32-bit unsigned value
18351     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
18352       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
18353                                            C->getZExtValue())) {
18354         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
18355         break;
18356       }
18357     }
18358     // FIXME gcc accepts some relocatable values here too, but only in certain
18359     // memory models; it's complicated.
18360     return;
18361   }
18362   case 'i': {
18363     // Literal immediates are always ok.
18364     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
18365       // Widen to 64 bits here to get it sign extended.
18366       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
18367       break;
18368     }
18369
18370     // In any sort of PIC mode addresses need to be computed at runtime by
18371     // adding in a register or some sort of table lookup.  These can't
18372     // be used as immediates.
18373     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
18374       return;
18375
18376     // If we are in non-pic codegen mode, we allow the address of a global (with
18377     // an optional displacement) to be used with 'i'.
18378     GlobalAddressSDNode *GA = 0;
18379     int64_t Offset = 0;
18380
18381     // Match either (GA), (GA+C), (GA+C1+C2), etc.
18382     while (1) {
18383       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
18384         Offset += GA->getOffset();
18385         break;
18386       } else if (Op.getOpcode() == ISD::ADD) {
18387         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18388           Offset += C->getZExtValue();
18389           Op = Op.getOperand(0);
18390           continue;
18391         }
18392       } else if (Op.getOpcode() == ISD::SUB) {
18393         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
18394           Offset += -C->getZExtValue();
18395           Op = Op.getOperand(0);
18396           continue;
18397         }
18398       }
18399
18400       // Otherwise, this isn't something we can handle, reject it.
18401       return;
18402     }
18403
18404     const GlobalValue *GV = GA->getGlobal();
18405     // If we require an extra load to get this address, as in PIC mode, we
18406     // can't accept it.
18407     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
18408                                                         getTargetMachine())))
18409       return;
18410
18411     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
18412                                         GA->getValueType(0), Offset);
18413     break;
18414   }
18415   }
18416
18417   if (Result.getNode()) {
18418     Ops.push_back(Result);
18419     return;
18420   }
18421   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
18422 }
18423
18424 std::pair<unsigned, const TargetRegisterClass*>
18425 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
18426                                                 MVT VT) const {
18427   // First, see if this is a constraint that directly corresponds to an LLVM
18428   // register class.
18429   if (Constraint.size() == 1) {
18430     // GCC Constraint Letters
18431     switch (Constraint[0]) {
18432     default: break;
18433       // TODO: Slight differences here in allocation order and leaving
18434       // RIP in the class. Do they matter any more here than they do
18435       // in the normal allocation?
18436     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
18437       if (Subtarget->is64Bit()) {
18438         if (VT == MVT::i32 || VT == MVT::f32)
18439           return std::make_pair(0U, &X86::GR32RegClass);
18440         if (VT == MVT::i16)
18441           return std::make_pair(0U, &X86::GR16RegClass);
18442         if (VT == MVT::i8 || VT == MVT::i1)
18443           return std::make_pair(0U, &X86::GR8RegClass);
18444         if (VT == MVT::i64 || VT == MVT::f64)
18445           return std::make_pair(0U, &X86::GR64RegClass);
18446         break;
18447       }
18448       // 32-bit fallthrough
18449     case 'Q':   // Q_REGS
18450       if (VT == MVT::i32 || VT == MVT::f32)
18451         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
18452       if (VT == MVT::i16)
18453         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
18454       if (VT == MVT::i8 || VT == MVT::i1)
18455         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
18456       if (VT == MVT::i64)
18457         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
18458       break;
18459     case 'r':   // GENERAL_REGS
18460     case 'l':   // INDEX_REGS
18461       if (VT == MVT::i8 || VT == MVT::i1)
18462         return std::make_pair(0U, &X86::GR8RegClass);
18463       if (VT == MVT::i16)
18464         return std::make_pair(0U, &X86::GR16RegClass);
18465       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
18466         return std::make_pair(0U, &X86::GR32RegClass);
18467       return std::make_pair(0U, &X86::GR64RegClass);
18468     case 'R':   // LEGACY_REGS
18469       if (VT == MVT::i8 || VT == MVT::i1)
18470         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
18471       if (VT == MVT::i16)
18472         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
18473       if (VT == MVT::i32 || !Subtarget->is64Bit())
18474         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
18475       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
18476     case 'f':  // FP Stack registers.
18477       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
18478       // value to the correct fpstack register class.
18479       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
18480         return std::make_pair(0U, &X86::RFP32RegClass);
18481       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
18482         return std::make_pair(0U, &X86::RFP64RegClass);
18483       return std::make_pair(0U, &X86::RFP80RegClass);
18484     case 'y':   // MMX_REGS if MMX allowed.
18485       if (!Subtarget->hasMMX()) break;
18486       return std::make_pair(0U, &X86::VR64RegClass);
18487     case 'Y':   // SSE_REGS if SSE2 allowed
18488       if (!Subtarget->hasSSE2()) break;
18489       // FALL THROUGH.
18490     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
18491       if (!Subtarget->hasSSE1()) break;
18492
18493       switch (VT.SimpleTy) {
18494       default: break;
18495       // Scalar SSE types.
18496       case MVT::f32:
18497       case MVT::i32:
18498         return std::make_pair(0U, &X86::FR32RegClass);
18499       case MVT::f64:
18500       case MVT::i64:
18501         return std::make_pair(0U, &X86::FR64RegClass);
18502       // Vector types.
18503       case MVT::v16i8:
18504       case MVT::v8i16:
18505       case MVT::v4i32:
18506       case MVT::v2i64:
18507       case MVT::v4f32:
18508       case MVT::v2f64:
18509         return std::make_pair(0U, &X86::VR128RegClass);
18510       // AVX types.
18511       case MVT::v32i8:
18512       case MVT::v16i16:
18513       case MVT::v8i32:
18514       case MVT::v4i64:
18515       case MVT::v8f32:
18516       case MVT::v4f64:
18517         return std::make_pair(0U, &X86::VR256RegClass);
18518       }
18519       break;
18520     }
18521   }
18522
18523   // Use the default implementation in TargetLowering to convert the register
18524   // constraint into a member of a register class.
18525   std::pair<unsigned, const TargetRegisterClass*> Res;
18526   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
18527
18528   // Not found as a standard register?
18529   if (Res.second == 0) {
18530     // Map st(0) -> st(7) -> ST0
18531     if (Constraint.size() == 7 && Constraint[0] == '{' &&
18532         tolower(Constraint[1]) == 's' &&
18533         tolower(Constraint[2]) == 't' &&
18534         Constraint[3] == '(' &&
18535         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
18536         Constraint[5] == ')' &&
18537         Constraint[6] == '}') {
18538
18539       Res.first = X86::ST0+Constraint[4]-'0';
18540       Res.second = &X86::RFP80RegClass;
18541       return Res;
18542     }
18543
18544     // GCC allows "st(0)" to be called just plain "st".
18545     if (StringRef("{st}").equals_lower(Constraint)) {
18546       Res.first = X86::ST0;
18547       Res.second = &X86::RFP80RegClass;
18548       return Res;
18549     }
18550
18551     // flags -> EFLAGS
18552     if (StringRef("{flags}").equals_lower(Constraint)) {
18553       Res.first = X86::EFLAGS;
18554       Res.second = &X86::CCRRegClass;
18555       return Res;
18556     }
18557
18558     // 'A' means EAX + EDX.
18559     if (Constraint == "A") {
18560       Res.first = X86::EAX;
18561       Res.second = &X86::GR32_ADRegClass;
18562       return Res;
18563     }
18564     return Res;
18565   }
18566
18567   // Otherwise, check to see if this is a register class of the wrong value
18568   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
18569   // turn into {ax},{dx}.
18570   if (Res.second->hasType(VT))
18571     return Res;   // Correct type already, nothing to do.
18572
18573   // All of the single-register GCC register classes map their values onto
18574   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
18575   // really want an 8-bit or 32-bit register, map to the appropriate register
18576   // class and return the appropriate register.
18577   if (Res.second == &X86::GR16RegClass) {
18578     if (VT == MVT::i8 || VT == MVT::i1) {
18579       unsigned DestReg = 0;
18580       switch (Res.first) {
18581       default: break;
18582       case X86::AX: DestReg = X86::AL; break;
18583       case X86::DX: DestReg = X86::DL; break;
18584       case X86::CX: DestReg = X86::CL; break;
18585       case X86::BX: DestReg = X86::BL; break;
18586       }
18587       if (DestReg) {
18588         Res.first = DestReg;
18589         Res.second = &X86::GR8RegClass;
18590       }
18591     } else if (VT == MVT::i32 || VT == MVT::f32) {
18592       unsigned DestReg = 0;
18593       switch (Res.first) {
18594       default: break;
18595       case X86::AX: DestReg = X86::EAX; break;
18596       case X86::DX: DestReg = X86::EDX; break;
18597       case X86::CX: DestReg = X86::ECX; break;
18598       case X86::BX: DestReg = X86::EBX; break;
18599       case X86::SI: DestReg = X86::ESI; break;
18600       case X86::DI: DestReg = X86::EDI; break;
18601       case X86::BP: DestReg = X86::EBP; break;
18602       case X86::SP: DestReg = X86::ESP; break;
18603       }
18604       if (DestReg) {
18605         Res.first = DestReg;
18606         Res.second = &X86::GR32RegClass;
18607       }
18608     } else if (VT == MVT::i64 || VT == MVT::f64) {
18609       unsigned DestReg = 0;
18610       switch (Res.first) {
18611       default: break;
18612       case X86::AX: DestReg = X86::RAX; break;
18613       case X86::DX: DestReg = X86::RDX; break;
18614       case X86::CX: DestReg = X86::RCX; break;
18615       case X86::BX: DestReg = X86::RBX; break;
18616       case X86::SI: DestReg = X86::RSI; break;
18617       case X86::DI: DestReg = X86::RDI; break;
18618       case X86::BP: DestReg = X86::RBP; break;
18619       case X86::SP: DestReg = X86::RSP; break;
18620       }
18621       if (DestReg) {
18622         Res.first = DestReg;
18623         Res.second = &X86::GR64RegClass;
18624       }
18625     }
18626   } else if (Res.second == &X86::FR32RegClass ||
18627              Res.second == &X86::FR64RegClass ||
18628              Res.second == &X86::VR128RegClass) {
18629     // Handle references to XMM physical registers that got mapped into the
18630     // wrong class.  This can happen with constraints like {xmm0} where the
18631     // target independent register mapper will just pick the first match it can
18632     // find, ignoring the required type.
18633
18634     if (VT == MVT::f32 || VT == MVT::i32)
18635       Res.second = &X86::FR32RegClass;
18636     else if (VT == MVT::f64 || VT == MVT::i64)
18637       Res.second = &X86::FR64RegClass;
18638     else if (X86::VR128RegClass.hasType(VT))
18639       Res.second = &X86::VR128RegClass;
18640     else if (X86::VR256RegClass.hasType(VT))
18641       Res.second = &X86::VR256RegClass;
18642   }
18643
18644   return Res;
18645 }