a5bfe1ac8fe9742c3827327eed69e58bac49ef51
[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 "X86.h"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "Utils/X86ShuffleDecode.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/IntrinsicLowering.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 using namespace llvm;
55 using namespace dwarf;
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue Insert128BitVector(SDValue Result,
64                                   SDValue Vec,
65                                   SDValue Idx,
66                                   SelectionDAG &DAG,
67                                   DebugLoc dl);
68
69 static SDValue Extract128BitVector(SDValue Vec,
70                                    SDValue Idx,
71                                    SelectionDAG &DAG,
72                                    DebugLoc dl);
73
74 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
75 /// sets things up to match to an AVX VEXTRACTF128 instruction or a
76 /// simple subregister reference.  Idx is an index in the 128 bits we
77 /// want.  It need not be aligned to a 128-bit bounday.  That makes
78 /// lowering EXTRACT_VECTOR_ELT operations easier.
79 static SDValue Extract128BitVector(SDValue Vec,
80                                    SDValue Idx,
81                                    SelectionDAG &DAG,
82                                    DebugLoc dl) {
83   EVT VT = Vec.getValueType();
84   assert(VT.getSizeInBits() == 256 && "Unexpected vector size!");
85   EVT ElVT = VT.getVectorElementType();
86   int Factor = VT.getSizeInBits()/128;
87   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
88                                   VT.getVectorNumElements()/Factor);
89
90   // Extract from UNDEF is UNDEF.
91   if (Vec.getOpcode() == ISD::UNDEF)
92     return DAG.getNode(ISD::UNDEF, dl, ResultVT);
93
94   if (isa<ConstantSDNode>(Idx)) {
95     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
96
97     // Extract the relevant 128 bits.  Generate an EXTRACT_SUBVECTOR
98     // we can match to VEXTRACTF128.
99     unsigned ElemsPerChunk = 128 / ElVT.getSizeInBits();
100
101     // This is the index of the first element of the 128-bit chunk
102     // we want.
103     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / 128)
104                                  * ElemsPerChunk);
105
106     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
107     SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                  VecIdx);
109
110     return Result;
111   }
112
113   return SDValue();
114 }
115
116 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
117 /// sets things up to match to an AVX VINSERTF128 instruction or a
118 /// simple superregister reference.  Idx is an index in the 128 bits
119 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
120 /// lowering INSERT_VECTOR_ELT operations easier.
121 static SDValue Insert128BitVector(SDValue Result,
122                                   SDValue Vec,
123                                   SDValue Idx,
124                                   SelectionDAG &DAG,
125                                   DebugLoc dl) {
126   if (isa<ConstantSDNode>(Idx)) {
127     EVT VT = Vec.getValueType();
128     assert(VT.getSizeInBits() == 128 && "Unexpected vector size!");
129
130     EVT ElVT = VT.getVectorElementType();
131     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
132     EVT ResultVT = Result.getValueType();
133
134     // Insert the relevant 128 bits.
135     unsigned ElemsPerChunk = 128/ElVT.getSizeInBits();
136
137     // This is the index of the first element of the 128-bit chunk
138     // we want.
139     unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/128)
140                                  * ElemsPerChunk);
141
142     SDValue VecIdx = DAG.getConstant(NormalizedIdxVal, MVT::i32);
143     Result = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
144                          VecIdx);
145     return Result;
146   }
147
148   return SDValue();
149 }
150
151 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
152   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
153   bool is64Bit = Subtarget->is64Bit();
154
155   if (Subtarget->isTargetEnvMacho()) {
156     if (is64Bit)
157       return new X8664_MachoTargetObjectFile();
158     return new TargetLoweringObjectFileMachO();
159   }
160
161   if (Subtarget->isTargetELF())
162     return new TargetLoweringObjectFileELF();
163   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
164     return new TargetLoweringObjectFileCOFF();
165   llvm_unreachable("unknown subtarget type");
166 }
167
168 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
169   : TargetLowering(TM, createTLOF(TM)) {
170   Subtarget = &TM.getSubtarget<X86Subtarget>();
171   X86ScalarSSEf64 = Subtarget->hasXMMInt();
172   X86ScalarSSEf32 = Subtarget->hasXMM();
173   X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
174
175   RegInfo = TM.getRegisterInfo();
176   TD = getTargetData();
177
178   // Set up the TargetLowering object.
179   static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
180
181   // X86 is weird, it always uses i8 for shift amounts and setcc results.
182   setBooleanContents(ZeroOrOneBooleanContent);
183   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
184   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
185
186   // For 64-bit since we have so many registers use the ILP scheduler, for
187   // 32-bit code use the register pressure specific scheduling.
188   if (Subtarget->is64Bit())
189     setSchedulingPreference(Sched::ILP);
190   else
191     setSchedulingPreference(Sched::RegPressure);
192   setStackPointerRegisterToSaveRestore(X86StackPtr);
193
194   if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
195     // Setup Windows compiler runtime calls.
196     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
197     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
198     setLibcallName(RTLIB::SREM_I64, "_allrem");
199     setLibcallName(RTLIB::UREM_I64, "_aullrem");
200     setLibcallName(RTLIB::MUL_I64, "_allmul");
201     setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
202     setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
203     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
204     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
205     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
206     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
207     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
208     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
209     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
210   }
211
212   if (Subtarget->isTargetDarwin()) {
213     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
214     setUseUnderscoreSetJmp(false);
215     setUseUnderscoreLongJmp(false);
216   } else if (Subtarget->isTargetMingw()) {
217     // MS runtime is weird: it exports _setjmp, but longjmp!
218     setUseUnderscoreSetJmp(true);
219     setUseUnderscoreLongJmp(false);
220   } else {
221     setUseUnderscoreSetJmp(true);
222     setUseUnderscoreLongJmp(true);
223   }
224
225   // Set up the register classes.
226   addRegisterClass(MVT::i8, X86::GR8RegisterClass);
227   addRegisterClass(MVT::i16, X86::GR16RegisterClass);
228   addRegisterClass(MVT::i32, X86::GR32RegisterClass);
229   if (Subtarget->is64Bit())
230     addRegisterClass(MVT::i64, X86::GR64RegisterClass);
231
232   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
233
234   // We don't accept any truncstore of integer registers.
235   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
236   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
237   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
238   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
239   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
240   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
241
242   // SETOEQ and SETUNE require checking two conditions.
243   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
244   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
245   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
246   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
247   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
248   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
249
250   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
251   // operation.
252   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
253   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
254   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
255
256   if (Subtarget->is64Bit()) {
257     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
258     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Expand);
259   } else if (!UseSoftFloat) {
260     // We have an algorithm for SSE2->double, and we turn this into a
261     // 64-bit FILD followed by conditional FADD for other targets.
262     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
263     // We have an algorithm for SSE2, and we turn this into a 64-bit
264     // FILD for other targets.
265     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
266   }
267
268   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
269   // this operation.
270   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
271   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
272
273   if (!UseSoftFloat) {
274     // SSE has no i16 to fp conversion, only i32
275     if (X86ScalarSSEf32) {
276       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
277       // f32 and f64 cases are Legal, f80 case is not
278       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
279     } else {
280       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
281       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
282     }
283   } else {
284     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
285     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
286   }
287
288   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
289   // are Legal, f80 is custom lowered.
290   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
291   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
292
293   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
294   // this operation.
295   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
296   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
297
298   if (X86ScalarSSEf32) {
299     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
300     // f32 and f64 cases are Legal, f80 case is not
301     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
302   } else {
303     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
304     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
305   }
306
307   // Handle FP_TO_UINT by promoting the destination to a larger signed
308   // conversion.
309   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
310   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
311   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
312
313   if (Subtarget->is64Bit()) {
314     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
315     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
316   } else if (!UseSoftFloat) {
317     // Since AVX is a superset of SSE3, only check for SSE here.
318     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
319       // Expand FP_TO_UINT into a select.
320       // FIXME: We would like to use a Custom expander here eventually to do
321       // the optimal thing for SSE vs. the default expansion in the legalizer.
322       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
323     else
324       // With SSE3 we can use fisttpll to convert to a signed i64; without
325       // SSE, we're stuck with a fistpll.
326       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
327   }
328
329   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
330   if (!X86ScalarSSEf64) {
331     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
332     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
333     if (Subtarget->is64Bit()) {
334       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
335       // Without SSE, i64->f64 goes through memory.
336       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
337     }
338   }
339
340   // Scalar integer divide and remainder are lowered to use operations that
341   // produce two results, to match the available instructions. This exposes
342   // the two-result form to trivial CSE, which is able to combine x/y and x%y
343   // into a single instruction.
344   //
345   // Scalar integer multiply-high is also lowered to use two-result
346   // operations, to match the available instructions. However, plain multiply
347   // (low) operations are left as Legal, as there are single-result
348   // instructions for this in x86. Using the two-result multiply instructions
349   // when both high and low results are needed must be arranged by dagcombine.
350   for (unsigned i = 0, e = 4; i != e; ++i) {
351     MVT VT = IntVTs[i];
352     setOperationAction(ISD::MULHS, VT, Expand);
353     setOperationAction(ISD::MULHU, VT, Expand);
354     setOperationAction(ISD::SDIV, VT, Expand);
355     setOperationAction(ISD::UDIV, VT, Expand);
356     setOperationAction(ISD::SREM, VT, Expand);
357     setOperationAction(ISD::UREM, VT, Expand);
358
359     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
360     setOperationAction(ISD::ADDC, VT, Custom);
361     setOperationAction(ISD::ADDE, VT, Custom);
362     setOperationAction(ISD::SUBC, VT, Custom);
363     setOperationAction(ISD::SUBE, VT, Custom);
364   }
365
366   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
367   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
368   setOperationAction(ISD::BR_CC            , MVT::Other, Expand);
369   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
370   if (Subtarget->is64Bit())
371     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
372   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
373   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
374   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
375   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
376   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
377   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
378   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
379   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
380
381   if (Subtarget->hasBMI()) {
382     setOperationAction(ISD::CTTZ           , MVT::i8   , Promote);
383   } else {
384     setOperationAction(ISD::CTTZ           , MVT::i8   , Custom);
385     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
386     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
387     if (Subtarget->is64Bit())
388       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
389   }
390
391   if (Subtarget->hasLZCNT()) {
392     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
393   } else {
394     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
395     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
396     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
397     if (Subtarget->is64Bit())
398       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
399   }
400
401   if (Subtarget->hasPOPCNT()) {
402     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
403   } else {
404     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
405     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
406     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
407     if (Subtarget->is64Bit())
408       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
409   }
410
411   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
412   setOperationAction(ISD::BSWAP            , MVT::i16  , Expand);
413
414   // These should be promoted to a larger select which is supported.
415   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
416   // X86 wants to expand cmov itself.
417   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
418   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
419   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
420   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
421   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
422   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
423   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
424   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
425   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
426   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
427   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
428   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
429   if (Subtarget->is64Bit()) {
430     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
431     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
432   }
433   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
434
435   // Darwin ABI issue.
436   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
437   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
438   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
439   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
440   if (Subtarget->is64Bit())
441     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
442   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
443   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
444   if (Subtarget->is64Bit()) {
445     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
446     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
447     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
448     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
449     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
450   }
451   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
452   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
453   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
454   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
455   if (Subtarget->is64Bit()) {
456     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
457     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
458     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
459   }
460
461   if (Subtarget->hasXMM())
462     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
463
464   setOperationAction(ISD::MEMBARRIER    , MVT::Other, Custom);
465   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
466
467   // On X86 and X86-64, atomic operations are lowered to locked instructions.
468   // Locked instructions, in turn, have implicit fence semantics (all memory
469   // operations are flushed before issuing the locked instruction, and they
470   // are not buffered), so we can fold away the common pattern of
471   // fence-atomic-fence.
472   setShouldFoldAtomicFences(true);
473
474   // Expand certain atomics
475   for (unsigned i = 0, e = 4; i != e; ++i) {
476     MVT VT = IntVTs[i];
477     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
478     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
479     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
480   }
481
482   if (!Subtarget->is64Bit()) {
483     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
484     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
485     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
486     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
487     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
488     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
489     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
490     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
491   }
492
493   if (Subtarget->hasCmpxchg16b()) {
494     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
495   }
496
497   // FIXME - use subtarget debug flags
498   if (!Subtarget->isTargetDarwin() &&
499       !Subtarget->isTargetELF() &&
500       !Subtarget->isTargetCygMing()) {
501     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
502   }
503
504   setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
505   setOperationAction(ISD::EHSELECTION,   MVT::i64, Expand);
506   setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
507   setOperationAction(ISD::EHSELECTION,   MVT::i32, Expand);
508   if (Subtarget->is64Bit()) {
509     setExceptionPointerRegister(X86::RAX);
510     setExceptionSelectorRegister(X86::RDX);
511   } else {
512     setExceptionPointerRegister(X86::EAX);
513     setExceptionSelectorRegister(X86::EDX);
514   }
515   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
516   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
517
518   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
519   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
520
521   setOperationAction(ISD::TRAP, MVT::Other, Legal);
522
523   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
524   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
525   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
526   if (Subtarget->is64Bit()) {
527     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
528     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
529   } else {
530     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
531     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
532   }
533
534   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
535   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
536
537   if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho())
538     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
539                        MVT::i64 : MVT::i32, Custom);
540   else if (EnableSegmentedStacks)
541     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
542                        MVT::i64 : MVT::i32, Custom);
543   else
544     setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
545                        MVT::i64 : MVT::i32, Expand);
546
547   if (!UseSoftFloat && X86ScalarSSEf64) {
548     // f32 and f64 use SSE.
549     // Set up the FP register classes.
550     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
551     addRegisterClass(MVT::f64, X86::FR64RegisterClass);
552
553     // Use ANDPD to simulate FABS.
554     setOperationAction(ISD::FABS , MVT::f64, Custom);
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f64, Custom);
559     setOperationAction(ISD::FNEG , MVT::f32, Custom);
560
561     // Use ANDPD and ORPD to simulate FCOPYSIGN.
562     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
563     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
564
565     // Lower this to FGETSIGNx86 plus an AND.
566     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
567     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
568
569     // We don't support sin/cos/fmod
570     setOperationAction(ISD::FSIN , MVT::f64, Expand);
571     setOperationAction(ISD::FCOS , MVT::f64, Expand);
572     setOperationAction(ISD::FSIN , MVT::f32, Expand);
573     setOperationAction(ISD::FCOS , MVT::f32, Expand);
574
575     // Expand FP immediates into loads from the stack, except for the special
576     // cases we handle.
577     addLegalFPImmediate(APFloat(+0.0)); // xorpd
578     addLegalFPImmediate(APFloat(+0.0f)); // xorps
579   } else if (!UseSoftFloat && X86ScalarSSEf32) {
580     // Use SSE for f32, x87 for f64.
581     // Set up the FP register classes.
582     addRegisterClass(MVT::f32, X86::FR32RegisterClass);
583     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
584
585     // Use ANDPS to simulate FABS.
586     setOperationAction(ISD::FABS , MVT::f32, Custom);
587
588     // Use XORP to simulate FNEG.
589     setOperationAction(ISD::FNEG , MVT::f32, Custom);
590
591     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
592
593     // Use ANDPS and ORPS to simulate FCOPYSIGN.
594     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
595     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
596
597     // We don't support sin/cos/fmod
598     setOperationAction(ISD::FSIN , MVT::f32, Expand);
599     setOperationAction(ISD::FCOS , MVT::f32, Expand);
600
601     // Special cases we handle for FP constants.
602     addLegalFPImmediate(APFloat(+0.0f)); // xorps
603     addLegalFPImmediate(APFloat(+0.0)); // FLD0
604     addLegalFPImmediate(APFloat(+1.0)); // FLD1
605     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
606     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
607
608     if (!UnsafeFPMath) {
609       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
610       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
611     }
612   } else if (!UseSoftFloat) {
613     // f32 and f64 in x87.
614     // Set up the FP register classes.
615     addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
616     addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
617
618     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
619     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
621     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
622
623     if (!UnsafeFPMath) {
624       setOperationAction(ISD::FSIN           , MVT::f64  , Expand);
625       setOperationAction(ISD::FCOS           , MVT::f64  , Expand);
626     }
627     addLegalFPImmediate(APFloat(+0.0)); // FLD0
628     addLegalFPImmediate(APFloat(+1.0)); // FLD1
629     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
630     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
631     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
632     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
633     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
634     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
635   }
636
637   // We don't support FMA.
638   setOperationAction(ISD::FMA, MVT::f64, Expand);
639   setOperationAction(ISD::FMA, MVT::f32, Expand);
640
641   // Long double always uses X87.
642   if (!UseSoftFloat) {
643     addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
644     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
645     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
646     {
647       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
648       addLegalFPImmediate(TmpFlt);  // FLD0
649       TmpFlt.changeSign();
650       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
651
652       bool ignored;
653       APFloat TmpFlt2(+1.0);
654       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
655                       &ignored);
656       addLegalFPImmediate(TmpFlt2);  // FLD1
657       TmpFlt2.changeSign();
658       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
659     }
660
661     if (!UnsafeFPMath) {
662       setOperationAction(ISD::FSIN           , MVT::f80  , Expand);
663       setOperationAction(ISD::FCOS           , MVT::f80  , Expand);
664     }
665
666     setOperationAction(ISD::FMA, MVT::f80, Expand);
667   }
668
669   // Always use a library call for pow.
670   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
671   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
672   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
673
674   setOperationAction(ISD::FLOG, MVT::f80, Expand);
675   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
676   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
677   setOperationAction(ISD::FEXP, MVT::f80, Expand);
678   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
679
680   // First set operation action for all vector types to either promote
681   // (for widening) or expand (for scalarization). Then we will selectively
682   // turn on ones that can be effectively codegen'd.
683   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
684        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
685     setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
686     setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
687     setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
688     setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
689     setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
690     setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
691     setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
692     setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
693     setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
694     setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
695     setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
696     setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
697     setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
698     setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
699     setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
700     setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
701     setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
702     setOperationAction(ISD::INSERT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
703     setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
704     setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
705     setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
706     setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
707     setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
708     setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
709     setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
710     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
711     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
712     setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
713     setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
714     setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
715     setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
716     setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
717     setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
718     setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
719     setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
720     setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
721     setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
722     setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
723     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
724     setOperationAction(ISD::SETCC, (MVT::SimpleValueType)VT, Expand);
725     setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
726     setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
727     setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
728     setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
729     setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
730     setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
731     setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
732     setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
733     setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
734     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
735     setOperationAction(ISD::TRUNCATE,  (MVT::SimpleValueType)VT, Expand);
736     setOperationAction(ISD::SIGN_EXTEND,  (MVT::SimpleValueType)VT, Expand);
737     setOperationAction(ISD::ZERO_EXTEND,  (MVT::SimpleValueType)VT, Expand);
738     setOperationAction(ISD::ANY_EXTEND,  (MVT::SimpleValueType)VT, Expand);
739     setOperationAction(ISD::VSELECT,  (MVT::SimpleValueType)VT, Expand);
740     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
741          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
742       setTruncStoreAction((MVT::SimpleValueType)VT,
743                           (MVT::SimpleValueType)InnerVT, Expand);
744     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
745     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
746     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
747   }
748
749   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
750   // with -msoft-float, disable use of MMX as well.
751   if (!UseSoftFloat && Subtarget->hasMMX()) {
752     addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
753     // No operations on x86mmx supported, everything uses intrinsics.
754   }
755
756   // MMX-sized vectors (other than x86mmx) are expected to be expanded
757   // into smaller operations.
758   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
759   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
760   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
761   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
762   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
763   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
764   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
765   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
766   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
767   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
768   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
769   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
770   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
771   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
772   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
773   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
774   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
775   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
776   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
777   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
778   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
779   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
780   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
781   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
782   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
783   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
784   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
785   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
786   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
787
788   if (!UseSoftFloat && Subtarget->hasXMM()) {
789     addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
790
791     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
792     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
793     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
794     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
795     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
796     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
797     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
798     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
799     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
800     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
801     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
802     setOperationAction(ISD::SETCC,              MVT::v4f32, Custom);
803   }
804
805   if (!UseSoftFloat && Subtarget->hasXMMInt()) {
806     addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
807
808     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
809     // registers cannot be used even for integer operations.
810     addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
811     addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
812     addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
813     addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
814
815     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
816     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
817     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
818     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
820     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
821     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
822     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
823     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
824     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
825     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
826     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
827     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
828     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
829     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
830     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
831
832     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
833     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
836
837     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
839     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
842
843     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2f64, Custom);
844     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v2i64, Custom);
845     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i8, Custom);
846     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i16, Custom);
847     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i32, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
851       EVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,
859                          VT.getSimpleVT().SimpleTy, Custom);
860       setOperationAction(ISD::VECTOR_SHUFFLE,
861                          VT.getSimpleVT().SimpleTy, Custom);
862       setOperationAction(ISD::EXTRACT_VECTOR_ELT,
863                          VT.getSimpleVT().SimpleTy, Custom);
864     }
865
866     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
867     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
868     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
869     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
870     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
871     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
872
873     if (Subtarget->is64Bit()) {
874       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
875       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
876     }
877
878     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
879     for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
880       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
881       EVT VT = SVT;
882
883       // Do not attempt to promote non-128-bit vectors
884       if (!VT.is128BitVector())
885         continue;
886
887       setOperationAction(ISD::AND,    SVT, Promote);
888       AddPromotedToType (ISD::AND,    SVT, MVT::v2i64);
889       setOperationAction(ISD::OR,     SVT, Promote);
890       AddPromotedToType (ISD::OR,     SVT, MVT::v2i64);
891       setOperationAction(ISD::XOR,    SVT, Promote);
892       AddPromotedToType (ISD::XOR,    SVT, MVT::v2i64);
893       setOperationAction(ISD::LOAD,   SVT, Promote);
894       AddPromotedToType (ISD::LOAD,   SVT, MVT::v2i64);
895       setOperationAction(ISD::SELECT, SVT, Promote);
896       AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
897     }
898
899     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
900
901     // Custom lower v2i64 and v2f64 selects.
902     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
903     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
904     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
905     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
906
907     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
908     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
909   }
910
911   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
912     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
913     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
914     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
915     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
916     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
917     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
918     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
919     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
920     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
921     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
922
923     // FIXME: Do we need to handle scalar-to-vector here?
924     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
925
926     setOperationAction(ISD::VSELECT,            MVT::v2f64, Legal);
927     setOperationAction(ISD::VSELECT,            MVT::v2i64, Legal);
928     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
929     setOperationAction(ISD::VSELECT,            MVT::v4i32, Legal);
930     setOperationAction(ISD::VSELECT,            MVT::v4f32, Legal);
931
932     // i8 and i16 vectors are custom , because the source register and source
933     // source memory operand types are not the same width.  f32 vectors are
934     // custom since the immediate controlling the insert encodes additional
935     // information.
936     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
937     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
938     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
939     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
940
941     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
942     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
943     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
944     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
945
946     // FIXME: these should be Legal but thats only for the case where
947     // the index is constant.  For now custom expand to deal with that
948     if (Subtarget->is64Bit()) {
949       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
950       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
951     }
952   }
953
954   if (Subtarget->hasXMMInt()) {
955     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
956     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
957
958     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
959     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
960
961     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
962     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
963
964     if (Subtarget->hasAVX2()) {
965       setOperationAction(ISD::SRL,             MVT::v2i64, Legal);
966       setOperationAction(ISD::SRL,             MVT::v4i32, Legal);
967
968       setOperationAction(ISD::SHL,             MVT::v2i64, Legal);
969       setOperationAction(ISD::SHL,             MVT::v4i32, Legal);
970
971       setOperationAction(ISD::SRA,             MVT::v4i32, Legal);
972     } else {
973       setOperationAction(ISD::SRL,             MVT::v2i64, Custom);
974       setOperationAction(ISD::SRL,             MVT::v4i32, Custom);
975
976       setOperationAction(ISD::SHL,             MVT::v2i64, Custom);
977       setOperationAction(ISD::SHL,             MVT::v4i32, Custom);
978
979       setOperationAction(ISD::SRA,             MVT::v4i32, Custom);
980     }
981   }
982
983   if (Subtarget->hasSSE42() || Subtarget->hasAVX())
984     setOperationAction(ISD::SETCC,             MVT::v2i64, Custom);
985
986   if (!UseSoftFloat && Subtarget->hasAVX()) {
987     addRegisterClass(MVT::v32i8,  X86::VR256RegisterClass);
988     addRegisterClass(MVT::v16i16, X86::VR256RegisterClass);
989     addRegisterClass(MVT::v8i32,  X86::VR256RegisterClass);
990     addRegisterClass(MVT::v8f32,  X86::VR256RegisterClass);
991     addRegisterClass(MVT::v4i64,  X86::VR256RegisterClass);
992     addRegisterClass(MVT::v4f64,  X86::VR256RegisterClass);
993
994     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
995     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
996     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
997
998     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
999     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1000     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1001     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1002     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1003     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1004
1005     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1006     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1007     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1008     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1009     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1010     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1011
1012     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1013     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1014     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1015
1016     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4f64,  Custom);
1017     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i64,  Custom);
1018     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f32,  Custom);
1019     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i32,  Custom);
1020     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i8,  Custom);
1021     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i16, Custom);
1022
1023     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1024     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1025
1026     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1027     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1028
1029     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1030     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1031
1032     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1033     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1034     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1035     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1036
1037     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1038     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1039     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1040
1041     setOperationAction(ISD::VSELECT,           MVT::v4f64, Legal);
1042     setOperationAction(ISD::VSELECT,           MVT::v4i64, Legal);
1043     setOperationAction(ISD::VSELECT,           MVT::v8i32, Legal);
1044     setOperationAction(ISD::VSELECT,           MVT::v8f32, Legal);
1045
1046     if (Subtarget->hasAVX2()) {
1047       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1048       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1049       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1050       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1051
1052       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1053       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1054       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1055       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1056
1057       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1058       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1059       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1060       // Don't lower v32i8 because there is no 128-bit byte mul
1061
1062       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1063
1064       setOperationAction(ISD::SRL,             MVT::v4i64, Legal);
1065       setOperationAction(ISD::SRL,             MVT::v8i32, Legal);
1066
1067       setOperationAction(ISD::SHL,             MVT::v4i64, Legal);
1068       setOperationAction(ISD::SHL,             MVT::v8i32, Legal);
1069
1070       setOperationAction(ISD::SRA,             MVT::v8i32, Legal);
1071     } else {
1072       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1073       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1074       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1075       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1076
1077       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1078       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1079       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1080       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1081
1082       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1083       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1084       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1085       // Don't lower v32i8 because there is no 128-bit byte mul
1086
1087       setOperationAction(ISD::SRL,             MVT::v4i64, Custom);
1088       setOperationAction(ISD::SRL,             MVT::v8i32, Custom);
1089
1090       setOperationAction(ISD::SHL,             MVT::v4i64, Custom);
1091       setOperationAction(ISD::SHL,             MVT::v8i32, Custom);
1092
1093       setOperationAction(ISD::SRA,             MVT::v8i32, Custom);
1094     }
1095
1096     // Custom lower several nodes for 256-bit types.
1097     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1098                   i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
1099       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1100       EVT VT = SVT;
1101
1102       // Extract subvector is special because the value type
1103       // (result) is 128-bit but the source is 256-bit wide.
1104       if (VT.is128BitVector())
1105         setOperationAction(ISD::EXTRACT_SUBVECTOR, SVT, Custom);
1106
1107       // Do not attempt to custom lower other non-256-bit vectors
1108       if (!VT.is256BitVector())
1109         continue;
1110
1111       setOperationAction(ISD::BUILD_VECTOR,       SVT, Custom);
1112       setOperationAction(ISD::VECTOR_SHUFFLE,     SVT, Custom);
1113       setOperationAction(ISD::INSERT_VECTOR_ELT,  SVT, Custom);
1114       setOperationAction(ISD::EXTRACT_VECTOR_ELT, SVT, Custom);
1115       setOperationAction(ISD::SCALAR_TO_VECTOR,   SVT, Custom);
1116       setOperationAction(ISD::INSERT_SUBVECTOR,   SVT, Custom);
1117     }
1118
1119     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1120     for (unsigned i = (unsigned)MVT::v32i8; i != (unsigned)MVT::v4i64; ++i) {
1121       MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
1122       EVT VT = SVT;
1123
1124       // Do not attempt to promote non-256-bit vectors
1125       if (!VT.is256BitVector())
1126         continue;
1127
1128       setOperationAction(ISD::AND,    SVT, Promote);
1129       AddPromotedToType (ISD::AND,    SVT, MVT::v4i64);
1130       setOperationAction(ISD::OR,     SVT, Promote);
1131       AddPromotedToType (ISD::OR,     SVT, MVT::v4i64);
1132       setOperationAction(ISD::XOR,    SVT, Promote);
1133       AddPromotedToType (ISD::XOR,    SVT, MVT::v4i64);
1134       setOperationAction(ISD::LOAD,   SVT, Promote);
1135       AddPromotedToType (ISD::LOAD,   SVT, MVT::v4i64);
1136       setOperationAction(ISD::SELECT, SVT, Promote);
1137       AddPromotedToType (ISD::SELECT, SVT, MVT::v4i64);
1138     }
1139   }
1140
1141   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1142   // of this type with custom code.
1143   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1144          VT != (unsigned)MVT::LAST_VECTOR_VALUETYPE; VT++) {
1145     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT, Custom);
1146   }
1147
1148   // We want to custom lower some of our intrinsics.
1149   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1150
1151
1152   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1153   // handle type legalization for these operations here.
1154   //
1155   // FIXME: We really should do custom legalization for addition and
1156   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1157   // than generic legalization for 64-bit multiplication-with-overflow, though.
1158   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1159     // Add/Sub/Mul with overflow operations are custom lowered.
1160     MVT VT = IntVTs[i];
1161     setOperationAction(ISD::SADDO, VT, Custom);
1162     setOperationAction(ISD::UADDO, VT, Custom);
1163     setOperationAction(ISD::SSUBO, VT, Custom);
1164     setOperationAction(ISD::USUBO, VT, Custom);
1165     setOperationAction(ISD::SMULO, VT, Custom);
1166     setOperationAction(ISD::UMULO, VT, Custom);
1167   }
1168
1169   // There are no 8-bit 3-address imul/mul instructions
1170   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1171   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1172
1173   if (!Subtarget->is64Bit()) {
1174     // These libcalls are not available in 32-bit.
1175     setLibcallName(RTLIB::SHL_I128, 0);
1176     setLibcallName(RTLIB::SRL_I128, 0);
1177     setLibcallName(RTLIB::SRA_I128, 0);
1178   }
1179
1180   // We have target-specific dag combine patterns for the following nodes:
1181   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1182   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1183   setTargetDAGCombine(ISD::BUILD_VECTOR);
1184   setTargetDAGCombine(ISD::VSELECT);
1185   setTargetDAGCombine(ISD::SELECT);
1186   setTargetDAGCombine(ISD::SHL);
1187   setTargetDAGCombine(ISD::SRA);
1188   setTargetDAGCombine(ISD::SRL);
1189   setTargetDAGCombine(ISD::OR);
1190   setTargetDAGCombine(ISD::AND);
1191   setTargetDAGCombine(ISD::ADD);
1192   setTargetDAGCombine(ISD::FADD);
1193   setTargetDAGCombine(ISD::FSUB);
1194   setTargetDAGCombine(ISD::SUB);
1195   setTargetDAGCombine(ISD::LOAD);
1196   setTargetDAGCombine(ISD::STORE);
1197   setTargetDAGCombine(ISD::ZERO_EXTEND);
1198   setTargetDAGCombine(ISD::SINT_TO_FP);
1199   if (Subtarget->is64Bit())
1200     setTargetDAGCombine(ISD::MUL);
1201   if (Subtarget->hasBMI())
1202     setTargetDAGCombine(ISD::XOR);
1203
1204   computeRegisterProperties();
1205
1206   // On Darwin, -Os means optimize for size without hurting performance,
1207   // do not reduce the limit.
1208   maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1209   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1210   maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1211   maxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1212   maxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1213   maxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1214   setPrefLoopAlignment(16);
1215   benefitFromCodePlacementOpt = true;
1216
1217   setPrefFunctionAlignment(4);
1218 }
1219
1220
1221 EVT X86TargetLowering::getSetCCResultType(EVT VT) const {
1222   if (!VT.isVector()) return MVT::i8;
1223   return VT.changeVectorElementTypeToInteger();
1224 }
1225
1226
1227 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1228 /// the desired ByVal argument alignment.
1229 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1230   if (MaxAlign == 16)
1231     return;
1232   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1233     if (VTy->getBitWidth() == 128)
1234       MaxAlign = 16;
1235   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1236     unsigned EltAlign = 0;
1237     getMaxByValAlign(ATy->getElementType(), EltAlign);
1238     if (EltAlign > MaxAlign)
1239       MaxAlign = EltAlign;
1240   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1241     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1242       unsigned EltAlign = 0;
1243       getMaxByValAlign(STy->getElementType(i), EltAlign);
1244       if (EltAlign > MaxAlign)
1245         MaxAlign = EltAlign;
1246       if (MaxAlign == 16)
1247         break;
1248     }
1249   }
1250   return;
1251 }
1252
1253 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1254 /// function arguments in the caller parameter area. For X86, aggregates
1255 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1256 /// are at 4-byte boundaries.
1257 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1258   if (Subtarget->is64Bit()) {
1259     // Max of 8 and alignment of type.
1260     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1261     if (TyAlign > 8)
1262       return TyAlign;
1263     return 8;
1264   }
1265
1266   unsigned Align = 4;
1267   if (Subtarget->hasXMM())
1268     getMaxByValAlign(Ty, Align);
1269   return Align;
1270 }
1271
1272 /// getOptimalMemOpType - Returns the target specific optimal type for load
1273 /// and store operations as a result of memset, memcpy, and memmove
1274 /// lowering. If DstAlign is zero that means it's safe to destination
1275 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1276 /// means there isn't a need to check it against alignment requirement,
1277 /// probably because the source does not need to be loaded. If
1278 /// 'IsZeroVal' is true, that means it's safe to return a
1279 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1280 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1281 /// constant so it does not need to be loaded.
1282 /// It returns EVT::Other if the type should be determined using generic
1283 /// target-independent logic.
1284 EVT
1285 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1286                                        unsigned DstAlign, unsigned SrcAlign,
1287                                        bool IsZeroVal,
1288                                        bool MemcpyStrSrc,
1289                                        MachineFunction &MF) const {
1290   // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1291   // linux.  This is because the stack realignment code can't handle certain
1292   // cases like PR2962.  This should be removed when PR2962 is fixed.
1293   const Function *F = MF.getFunction();
1294   if (IsZeroVal &&
1295       !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1296     if (Size >= 16 &&
1297         (Subtarget->isUnalignedMemAccessFast() ||
1298          ((DstAlign == 0 || DstAlign >= 16) &&
1299           (SrcAlign == 0 || SrcAlign >= 16))) &&
1300         Subtarget->getStackAlignment() >= 16) {
1301       if (Subtarget->hasAVX() &&
1302           Subtarget->getStackAlignment() >= 32)
1303         return MVT::v8f32;
1304       if (Subtarget->hasXMMInt())
1305         return MVT::v4i32;
1306       if (Subtarget->hasXMM())
1307         return MVT::v4f32;
1308     } else if (!MemcpyStrSrc && Size >= 8 &&
1309                !Subtarget->is64Bit() &&
1310                Subtarget->getStackAlignment() >= 8 &&
1311                Subtarget->hasXMMInt()) {
1312       // Do not use f64 to lower memcpy if source is string constant. It's
1313       // better to use i32 to avoid the loads.
1314       return MVT::f64;
1315     }
1316   }
1317   if (Subtarget->is64Bit() && Size >= 8)
1318     return MVT::i64;
1319   return MVT::i32;
1320 }
1321
1322 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1323 /// current function.  The returned value is a member of the
1324 /// MachineJumpTableInfo::JTEntryKind enum.
1325 unsigned X86TargetLowering::getJumpTableEncoding() const {
1326   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1327   // symbol.
1328   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1329       Subtarget->isPICStyleGOT())
1330     return MachineJumpTableInfo::EK_Custom32;
1331
1332   // Otherwise, use the normal jump table encoding heuristics.
1333   return TargetLowering::getJumpTableEncoding();
1334 }
1335
1336 const MCExpr *
1337 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1338                                              const MachineBasicBlock *MBB,
1339                                              unsigned uid,MCContext &Ctx) const{
1340   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1341          Subtarget->isPICStyleGOT());
1342   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1343   // entries.
1344   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1345                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1346 }
1347
1348 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1349 /// jumptable.
1350 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1351                                                     SelectionDAG &DAG) const {
1352   if (!Subtarget->is64Bit())
1353     // This doesn't have DebugLoc associated with it, but is not really the
1354     // same as a Register.
1355     return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1356   return Table;
1357 }
1358
1359 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1360 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1361 /// MCExpr.
1362 const MCExpr *X86TargetLowering::
1363 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1364                              MCContext &Ctx) const {
1365   // X86-64 uses RIP relative addressing based on the jump table label.
1366   if (Subtarget->isPICStyleRIPRel())
1367     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1368
1369   // Otherwise, the reference is relative to the PIC base.
1370   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1371 }
1372
1373 // FIXME: Why this routine is here? Move to RegInfo!
1374 std::pair<const TargetRegisterClass*, uint8_t>
1375 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1376   const TargetRegisterClass *RRC = 0;
1377   uint8_t Cost = 1;
1378   switch (VT.getSimpleVT().SimpleTy) {
1379   default:
1380     return TargetLowering::findRepresentativeClass(VT);
1381   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1382     RRC = (Subtarget->is64Bit()
1383            ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1384     break;
1385   case MVT::x86mmx:
1386     RRC = X86::VR64RegisterClass;
1387     break;
1388   case MVT::f32: case MVT::f64:
1389   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1390   case MVT::v4f32: case MVT::v2f64:
1391   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1392   case MVT::v4f64:
1393     RRC = X86::VR128RegisterClass;
1394     break;
1395   }
1396   return std::make_pair(RRC, Cost);
1397 }
1398
1399 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1400                                                unsigned &Offset) const {
1401   if (!Subtarget->isTargetLinux())
1402     return false;
1403
1404   if (Subtarget->is64Bit()) {
1405     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1406     Offset = 0x28;
1407     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1408       AddressSpace = 256;
1409     else
1410       AddressSpace = 257;
1411   } else {
1412     // %gs:0x14 on i386
1413     Offset = 0x14;
1414     AddressSpace = 256;
1415   }
1416   return true;
1417 }
1418
1419
1420 //===----------------------------------------------------------------------===//
1421 //               Return Value Calling Convention Implementation
1422 //===----------------------------------------------------------------------===//
1423
1424 #include "X86GenCallingConv.inc"
1425
1426 bool
1427 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1428                                   MachineFunction &MF, bool isVarArg,
1429                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1430                         LLVMContext &Context) const {
1431   SmallVector<CCValAssign, 16> RVLocs;
1432   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1433                  RVLocs, Context);
1434   return CCInfo.CheckReturn(Outs, RetCC_X86);
1435 }
1436
1437 SDValue
1438 X86TargetLowering::LowerReturn(SDValue Chain,
1439                                CallingConv::ID CallConv, bool isVarArg,
1440                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1441                                const SmallVectorImpl<SDValue> &OutVals,
1442                                DebugLoc dl, SelectionDAG &DAG) const {
1443   MachineFunction &MF = DAG.getMachineFunction();
1444   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1445
1446   SmallVector<CCValAssign, 16> RVLocs;
1447   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1448                  RVLocs, *DAG.getContext());
1449   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1450
1451   // Add the regs to the liveout set for the function.
1452   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1453   for (unsigned i = 0; i != RVLocs.size(); ++i)
1454     if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1455       MRI.addLiveOut(RVLocs[i].getLocReg());
1456
1457   SDValue Flag;
1458
1459   SmallVector<SDValue, 6> RetOps;
1460   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1461   // Operand #1 = Bytes To Pop
1462   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1463                    MVT::i16));
1464
1465   // Copy the result values into the output registers.
1466   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1467     CCValAssign &VA = RVLocs[i];
1468     assert(VA.isRegLoc() && "Can only return in registers!");
1469     SDValue ValToCopy = OutVals[i];
1470     EVT ValVT = ValToCopy.getValueType();
1471
1472     // If this is x86-64, and we disabled SSE, we can't return FP values,
1473     // or SSE or MMX vectors.
1474     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1475          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1476           (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1477       report_fatal_error("SSE register return with SSE disabled");
1478     }
1479     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1480     // llvm-gcc has never done it right and no one has noticed, so this
1481     // should be OK for now.
1482     if (ValVT == MVT::f64 &&
1483         (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1484       report_fatal_error("SSE2 register return with SSE2 disabled");
1485
1486     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1487     // the RET instruction and handled by the FP Stackifier.
1488     if (VA.getLocReg() == X86::ST0 ||
1489         VA.getLocReg() == X86::ST1) {
1490       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1491       // change the value to the FP stack register class.
1492       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1493         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1494       RetOps.push_back(ValToCopy);
1495       // Don't emit a copytoreg.
1496       continue;
1497     }
1498
1499     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1500     // which is returned in RAX / RDX.
1501     if (Subtarget->is64Bit()) {
1502       if (ValVT == MVT::x86mmx) {
1503         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1504           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1505           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1506                                   ValToCopy);
1507           // If we don't have SSE2 available, convert to v4f32 so the generated
1508           // register is legal.
1509           if (!Subtarget->hasXMMInt())
1510             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1511         }
1512       }
1513     }
1514
1515     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1516     Flag = Chain.getValue(1);
1517   }
1518
1519   // The x86-64 ABI for returning structs by value requires that we copy
1520   // the sret argument into %rax for the return. We saved the argument into
1521   // a virtual register in the entry block, so now we copy the value out
1522   // and into %rax.
1523   if (Subtarget->is64Bit() &&
1524       DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1525     MachineFunction &MF = DAG.getMachineFunction();
1526     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1527     unsigned Reg = FuncInfo->getSRetReturnReg();
1528     assert(Reg &&
1529            "SRetReturnReg should have been set in LowerFormalArguments().");
1530     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1531
1532     Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1533     Flag = Chain.getValue(1);
1534
1535     // RAX now acts like a return value.
1536     MRI.addLiveOut(X86::RAX);
1537   }
1538
1539   RetOps[0] = Chain;  // Update chain.
1540
1541   // Add the flag if we have it.
1542   if (Flag.getNode())
1543     RetOps.push_back(Flag);
1544
1545   return DAG.getNode(X86ISD::RET_FLAG, dl,
1546                      MVT::Other, &RetOps[0], RetOps.size());
1547 }
1548
1549 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1550   if (N->getNumValues() != 1)
1551     return false;
1552   if (!N->hasNUsesOfValue(1, 0))
1553     return false;
1554
1555   SDNode *Copy = *N->use_begin();
1556   if (Copy->getOpcode() != ISD::CopyToReg &&
1557       Copy->getOpcode() != ISD::FP_EXTEND)
1558     return false;
1559
1560   bool HasRet = false;
1561   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1562        UI != UE; ++UI) {
1563     if (UI->getOpcode() != X86ISD::RET_FLAG)
1564       return false;
1565     HasRet = true;
1566   }
1567
1568   return HasRet;
1569 }
1570
1571 EVT
1572 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
1573                                             ISD::NodeType ExtendKind) const {
1574   MVT ReturnMVT;
1575   // TODO: Is this also valid on 32-bit?
1576   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1577     ReturnMVT = MVT::i8;
1578   else
1579     ReturnMVT = MVT::i32;
1580
1581   EVT MinVT = getRegisterType(Context, ReturnMVT);
1582   return VT.bitsLT(MinVT) ? MinVT : VT;
1583 }
1584
1585 /// LowerCallResult - Lower the result values of a call into the
1586 /// appropriate copies out of appropriate physical registers.
1587 ///
1588 SDValue
1589 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1590                                    CallingConv::ID CallConv, bool isVarArg,
1591                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1592                                    DebugLoc dl, SelectionDAG &DAG,
1593                                    SmallVectorImpl<SDValue> &InVals) const {
1594
1595   // Assign locations to each value returned by this call.
1596   SmallVector<CCValAssign, 16> RVLocs;
1597   bool Is64Bit = Subtarget->is64Bit();
1598   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1599                  getTargetMachine(), RVLocs, *DAG.getContext());
1600   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1601
1602   // Copy all of the result registers out of their specified physreg.
1603   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1604     CCValAssign &VA = RVLocs[i];
1605     EVT CopyVT = VA.getValVT();
1606
1607     // If this is x86-64, and we disabled SSE, we can't return FP values
1608     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1609         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1610       report_fatal_error("SSE register return with SSE disabled");
1611     }
1612
1613     SDValue Val;
1614
1615     // If this is a call to a function that returns an fp value on the floating
1616     // point stack, we must guarantee the the value is popped from the stack, so
1617     // a CopyFromReg is not good enough - the copy instruction may be eliminated
1618     // if the return value is not used. We use the FpPOP_RETVAL instruction
1619     // instead.
1620     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1621       // If we prefer to use the value in xmm registers, copy it out as f80 and
1622       // use a truncate to move it from fp stack reg to xmm reg.
1623       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1624       SDValue Ops[] = { Chain, InFlag };
1625       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
1626                                          MVT::Other, MVT::Glue, Ops, 2), 1);
1627       Val = Chain.getValue(0);
1628
1629       // Round the f80 to the right size, which also moves it to the appropriate
1630       // xmm register.
1631       if (CopyVT != VA.getValVT())
1632         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1633                           // This truncation won't change the value.
1634                           DAG.getIntPtrConstant(1));
1635     } else {
1636       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1637                                  CopyVT, InFlag).getValue(1);
1638       Val = Chain.getValue(0);
1639     }
1640     InFlag = Chain.getValue(2);
1641     InVals.push_back(Val);
1642   }
1643
1644   return Chain;
1645 }
1646
1647
1648 //===----------------------------------------------------------------------===//
1649 //                C & StdCall & Fast Calling Convention implementation
1650 //===----------------------------------------------------------------------===//
1651 //  StdCall calling convention seems to be standard for many Windows' API
1652 //  routines and around. It differs from C calling convention just a little:
1653 //  callee should clean up the stack, not caller. Symbols should be also
1654 //  decorated in some fancy way :) It doesn't support any vector arguments.
1655 //  For info on fast calling convention see Fast Calling Convention (tail call)
1656 //  implementation LowerX86_32FastCCCallTo.
1657
1658 /// CallIsStructReturn - Determines whether a call uses struct return
1659 /// semantics.
1660 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1661   if (Outs.empty())
1662     return false;
1663
1664   return Outs[0].Flags.isSRet();
1665 }
1666
1667 /// ArgsAreStructReturn - Determines whether a function uses struct
1668 /// return semantics.
1669 static bool
1670 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1671   if (Ins.empty())
1672     return false;
1673
1674   return Ins[0].Flags.isSRet();
1675 }
1676
1677 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1678 /// by "Src" to address "Dst" with size and alignment information specified by
1679 /// the specific parameter attribute. The copy will be passed as a byval
1680 /// function parameter.
1681 static SDValue
1682 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1683                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1684                           DebugLoc dl) {
1685   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1686
1687   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1688                        /*isVolatile*/false, /*AlwaysInline=*/true,
1689                        MachinePointerInfo(), MachinePointerInfo());
1690 }
1691
1692 /// IsTailCallConvention - Return true if the calling convention is one that
1693 /// supports tail call optimization.
1694 static bool IsTailCallConvention(CallingConv::ID CC) {
1695   return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1696 }
1697
1698 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1699   if (!CI->isTailCall())
1700     return false;
1701
1702   CallSite CS(CI);
1703   CallingConv::ID CalleeCC = CS.getCallingConv();
1704   if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
1705     return false;
1706
1707   return true;
1708 }
1709
1710 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1711 /// a tailcall target by changing its ABI.
1712 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1713   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1714 }
1715
1716 SDValue
1717 X86TargetLowering::LowerMemArgument(SDValue Chain,
1718                                     CallingConv::ID CallConv,
1719                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1720                                     DebugLoc dl, SelectionDAG &DAG,
1721                                     const CCValAssign &VA,
1722                                     MachineFrameInfo *MFI,
1723                                     unsigned i) const {
1724   // Create the nodes corresponding to a load from this parameter slot.
1725   ISD::ArgFlagsTy Flags = Ins[i].Flags;
1726   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1727   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1728   EVT ValVT;
1729
1730   // If value is passed by pointer we have address passed instead of the value
1731   // itself.
1732   if (VA.getLocInfo() == CCValAssign::Indirect)
1733     ValVT = VA.getLocVT();
1734   else
1735     ValVT = VA.getValVT();
1736
1737   // FIXME: For now, all byval parameter objects are marked mutable. This can be
1738   // changed with more analysis.
1739   // In case of tail call optimization mark all arguments mutable. Since they
1740   // could be overwritten by lowering of arguments in case of a tail call.
1741   if (Flags.isByVal()) {
1742     unsigned Bytes = Flags.getByValSize();
1743     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
1744     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
1745     return DAG.getFrameIndex(FI, getPointerTy());
1746   } else {
1747     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1748                                     VA.getLocMemOffset(), isImmutable);
1749     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1750     return DAG.getLoad(ValVT, dl, Chain, FIN,
1751                        MachinePointerInfo::getFixedStack(FI),
1752                        false, false, false, 0);
1753   }
1754 }
1755
1756 SDValue
1757 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1758                                         CallingConv::ID CallConv,
1759                                         bool isVarArg,
1760                                       const SmallVectorImpl<ISD::InputArg> &Ins,
1761                                         DebugLoc dl,
1762                                         SelectionDAG &DAG,
1763                                         SmallVectorImpl<SDValue> &InVals)
1764                                           const {
1765   MachineFunction &MF = DAG.getMachineFunction();
1766   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1767
1768   const Function* Fn = MF.getFunction();
1769   if (Fn->hasExternalLinkage() &&
1770       Subtarget->isTargetCygMing() &&
1771       Fn->getName() == "main")
1772     FuncInfo->setForceFramePointer(true);
1773
1774   MachineFrameInfo *MFI = MF.getFrameInfo();
1775   bool Is64Bit = Subtarget->is64Bit();
1776   bool IsWin64 = Subtarget->isTargetWin64();
1777
1778   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1779          "Var args not supported with calling convention fastcc or ghc");
1780
1781   // Assign locations to all of the incoming arguments.
1782   SmallVector<CCValAssign, 16> ArgLocs;
1783   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1784                  ArgLocs, *DAG.getContext());
1785
1786   // Allocate shadow area for Win64
1787   if (IsWin64) {
1788     CCInfo.AllocateStack(32, 8);
1789   }
1790
1791   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1792
1793   unsigned LastVal = ~0U;
1794   SDValue ArgValue;
1795   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1796     CCValAssign &VA = ArgLocs[i];
1797     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1798     // places.
1799     assert(VA.getValNo() != LastVal &&
1800            "Don't support value assigned to multiple locs yet");
1801     (void)LastVal;
1802     LastVal = VA.getValNo();
1803
1804     if (VA.isRegLoc()) {
1805       EVT RegVT = VA.getLocVT();
1806       TargetRegisterClass *RC = NULL;
1807       if (RegVT == MVT::i32)
1808         RC = X86::GR32RegisterClass;
1809       else if (Is64Bit && RegVT == MVT::i64)
1810         RC = X86::GR64RegisterClass;
1811       else if (RegVT == MVT::f32)
1812         RC = X86::FR32RegisterClass;
1813       else if (RegVT == MVT::f64)
1814         RC = X86::FR64RegisterClass;
1815       else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1816         RC = X86::VR256RegisterClass;
1817       else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1818         RC = X86::VR128RegisterClass;
1819       else if (RegVT == MVT::x86mmx)
1820         RC = X86::VR64RegisterClass;
1821       else
1822         llvm_unreachable("Unknown argument type!");
1823
1824       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1825       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1826
1827       // If this is an 8 or 16-bit value, it is really passed promoted to 32
1828       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
1829       // right size.
1830       if (VA.getLocInfo() == CCValAssign::SExt)
1831         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1832                                DAG.getValueType(VA.getValVT()));
1833       else if (VA.getLocInfo() == CCValAssign::ZExt)
1834         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1835                                DAG.getValueType(VA.getValVT()));
1836       else if (VA.getLocInfo() == CCValAssign::BCvt)
1837         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1838
1839       if (VA.isExtInLoc()) {
1840         // Handle MMX values passed in XMM regs.
1841         if (RegVT.isVector()) {
1842           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1843                                  ArgValue);
1844         } else
1845           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1846       }
1847     } else {
1848       assert(VA.isMemLoc());
1849       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1850     }
1851
1852     // If value is passed via pointer - do a load.
1853     if (VA.getLocInfo() == CCValAssign::Indirect)
1854       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1855                              MachinePointerInfo(), false, false, false, 0);
1856
1857     InVals.push_back(ArgValue);
1858   }
1859
1860   // The x86-64 ABI for returning structs by value requires that we copy
1861   // the sret argument into %rax for the return. Save the argument into
1862   // a virtual register so that we can access it from the return points.
1863   if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1864     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1865     unsigned Reg = FuncInfo->getSRetReturnReg();
1866     if (!Reg) {
1867       Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1868       FuncInfo->setSRetReturnReg(Reg);
1869     }
1870     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1871     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1872   }
1873
1874   unsigned StackSize = CCInfo.getNextStackOffset();
1875   // Align stack specially for tail calls.
1876   if (FuncIsMadeTailCallSafe(CallConv))
1877     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1878
1879   // If the function takes variable number of arguments, make a frame index for
1880   // the start of the first vararg value... for expansion of llvm.va_start.
1881   if (isVarArg) {
1882     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1883                     CallConv != CallingConv::X86_ThisCall)) {
1884       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1885     }
1886     if (Is64Bit) {
1887       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1888
1889       // FIXME: We should really autogenerate these arrays
1890       static const unsigned GPR64ArgRegsWin64[] = {
1891         X86::RCX, X86::RDX, X86::R8,  X86::R9
1892       };
1893       static const unsigned GPR64ArgRegs64Bit[] = {
1894         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1895       };
1896       static const unsigned XMMArgRegs64Bit[] = {
1897         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1898         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1899       };
1900       const unsigned *GPR64ArgRegs;
1901       unsigned NumXMMRegs = 0;
1902
1903       if (IsWin64) {
1904         // The XMM registers which might contain var arg parameters are shadowed
1905         // in their paired GPR.  So we only need to save the GPR to their home
1906         // slots.
1907         TotalNumIntRegs = 4;
1908         GPR64ArgRegs = GPR64ArgRegsWin64;
1909       } else {
1910         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1911         GPR64ArgRegs = GPR64ArgRegs64Bit;
1912
1913         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1914       }
1915       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1916                                                        TotalNumIntRegs);
1917
1918       bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1919       assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1920              "SSE register cannot be used when SSE is disabled!");
1921       assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1922              "SSE register cannot be used when SSE is disabled!");
1923       if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1924         // Kernel mode asks for SSE to be disabled, so don't push them
1925         // on the stack.
1926         TotalNumXMMRegs = 0;
1927
1928       if (IsWin64) {
1929         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
1930         // Get to the caller-allocated home save location.  Add 8 to account
1931         // for the return address.
1932         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1933         FuncInfo->setRegSaveFrameIndex(
1934           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1935         // Fixup to set vararg frame on shadow area (4 x i64).
1936         if (NumIntRegs < 4)
1937           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1938       } else {
1939         // For X86-64, if there are vararg parameters that are passed via
1940         // registers, then we must store them to their spots on the stack so they
1941         // may be loaded by deferencing the result of va_next.
1942         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1943         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1944         FuncInfo->setRegSaveFrameIndex(
1945           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1946                                false));
1947       }
1948
1949       // Store the integer parameter registers.
1950       SmallVector<SDValue, 8> MemOps;
1951       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1952                                         getPointerTy());
1953       unsigned Offset = FuncInfo->getVarArgsGPOffset();
1954       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1955         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1956                                   DAG.getIntPtrConstant(Offset));
1957         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1958                                      X86::GR64RegisterClass);
1959         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1960         SDValue Store =
1961           DAG.getStore(Val.getValue(1), dl, Val, FIN,
1962                        MachinePointerInfo::getFixedStack(
1963                          FuncInfo->getRegSaveFrameIndex(), Offset),
1964                        false, false, 0);
1965         MemOps.push_back(Store);
1966         Offset += 8;
1967       }
1968
1969       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1970         // Now store the XMM (fp + vector) parameter registers.
1971         SmallVector<SDValue, 11> SaveXMMOps;
1972         SaveXMMOps.push_back(Chain);
1973
1974         unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1975         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1976         SaveXMMOps.push_back(ALVal);
1977
1978         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1979                                FuncInfo->getRegSaveFrameIndex()));
1980         SaveXMMOps.push_back(DAG.getIntPtrConstant(
1981                                FuncInfo->getVarArgsFPOffset()));
1982
1983         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1984           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1985                                        X86::VR128RegisterClass);
1986           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1987           SaveXMMOps.push_back(Val);
1988         }
1989         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1990                                      MVT::Other,
1991                                      &SaveXMMOps[0], SaveXMMOps.size()));
1992       }
1993
1994       if (!MemOps.empty())
1995         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1996                             &MemOps[0], MemOps.size());
1997     }
1998   }
1999
2000   // Some CCs need callee pop.
2001   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt)) {
2002     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2003   } else {
2004     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2005     // If this is an sret function, the return should pop the hidden pointer.
2006     if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
2007       FuncInfo->setBytesToPopOnReturn(4);
2008   }
2009
2010   if (!Is64Bit) {
2011     // RegSaveFrameIndex is X86-64 only.
2012     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2013     if (CallConv == CallingConv::X86_FastCall ||
2014         CallConv == CallingConv::X86_ThisCall)
2015       // fastcc functions can't have varargs.
2016       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2017   }
2018
2019   FuncInfo->setArgumentStackSize(StackSize);
2020
2021   return Chain;
2022 }
2023
2024 SDValue
2025 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2026                                     SDValue StackPtr, SDValue Arg,
2027                                     DebugLoc dl, SelectionDAG &DAG,
2028                                     const CCValAssign &VA,
2029                                     ISD::ArgFlagsTy Flags) const {
2030   unsigned LocMemOffset = VA.getLocMemOffset();
2031   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2032   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2033   if (Flags.isByVal())
2034     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2035
2036   return DAG.getStore(Chain, dl, Arg, PtrOff,
2037                       MachinePointerInfo::getStack(LocMemOffset),
2038                       false, false, 0);
2039 }
2040
2041 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2042 /// optimization is performed and it is required.
2043 SDValue
2044 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2045                                            SDValue &OutRetAddr, SDValue Chain,
2046                                            bool IsTailCall, bool Is64Bit,
2047                                            int FPDiff, DebugLoc dl) const {
2048   // Adjust the Return address stack slot.
2049   EVT VT = getPointerTy();
2050   OutRetAddr = getReturnAddressFrameIndex(DAG);
2051
2052   // Load the "old" Return address.
2053   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2054                            false, false, false, 0);
2055   return SDValue(OutRetAddr.getNode(), 1);
2056 }
2057
2058 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2059 /// optimization is performed and it is required (FPDiff!=0).
2060 static SDValue
2061 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
2062                          SDValue Chain, SDValue RetAddrFrIdx,
2063                          bool Is64Bit, int FPDiff, DebugLoc dl) {
2064   // Store the return address to the appropriate stack slot.
2065   if (!FPDiff) return Chain;
2066   // Calculate the new stack slot for the return address.
2067   int SlotSize = Is64Bit ? 8 : 4;
2068   int NewReturnAddrFI =
2069     MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
2070   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2071   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
2072   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2073                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2074                        false, false, 0);
2075   return Chain;
2076 }
2077
2078 SDValue
2079 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
2080                              CallingConv::ID CallConv, bool isVarArg,
2081                              bool &isTailCall,
2082                              const SmallVectorImpl<ISD::OutputArg> &Outs,
2083                              const SmallVectorImpl<SDValue> &OutVals,
2084                              const SmallVectorImpl<ISD::InputArg> &Ins,
2085                              DebugLoc dl, SelectionDAG &DAG,
2086                              SmallVectorImpl<SDValue> &InVals) const {
2087   MachineFunction &MF = DAG.getMachineFunction();
2088   bool Is64Bit        = Subtarget->is64Bit();
2089   bool IsWin64        = Subtarget->isTargetWin64();
2090   bool IsStructRet    = CallIsStructReturn(Outs);
2091   bool IsSibcall      = false;
2092
2093   if (isTailCall) {
2094     // Check if it's really possible to do a tail call.
2095     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2096                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
2097                                                    Outs, OutVals, Ins, DAG);
2098
2099     // Sibcalls are automatically detected tailcalls which do not require
2100     // ABI changes.
2101     if (!GuaranteedTailCallOpt && isTailCall)
2102       IsSibcall = true;
2103
2104     if (isTailCall)
2105       ++NumTailCalls;
2106   }
2107
2108   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2109          "Var args not supported with calling convention fastcc or ghc");
2110
2111   // Analyze operands of the call, assigning locations to each operand.
2112   SmallVector<CCValAssign, 16> ArgLocs;
2113   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2114                  ArgLocs, *DAG.getContext());
2115
2116   // Allocate shadow area for Win64
2117   if (IsWin64) {
2118     CCInfo.AllocateStack(32, 8);
2119   }
2120
2121   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2122
2123   // Get a count of how many bytes are to be pushed on the stack.
2124   unsigned NumBytes = CCInfo.getNextStackOffset();
2125   if (IsSibcall)
2126     // This is a sibcall. The memory operands are available in caller's
2127     // own caller's stack.
2128     NumBytes = 0;
2129   else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
2130     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2131
2132   int FPDiff = 0;
2133   if (isTailCall && !IsSibcall) {
2134     // Lower arguments at fp - stackoffset + fpdiff.
2135     unsigned NumBytesCallerPushed =
2136       MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
2137     FPDiff = NumBytesCallerPushed - NumBytes;
2138
2139     // Set the delta of movement of the returnaddr stackslot.
2140     // But only set if delta is greater than previous delta.
2141     if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
2142       MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
2143   }
2144
2145   if (!IsSibcall)
2146     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
2147
2148   SDValue RetAddrFrIdx;
2149   // Load return address for tail calls.
2150   if (isTailCall && FPDiff)
2151     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2152                                     Is64Bit, FPDiff, dl);
2153
2154   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2155   SmallVector<SDValue, 8> MemOpChains;
2156   SDValue StackPtr;
2157
2158   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2159   // of tail call optimization arguments are handle later.
2160   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2161     CCValAssign &VA = ArgLocs[i];
2162     EVT RegVT = VA.getLocVT();
2163     SDValue Arg = OutVals[i];
2164     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2165     bool isByVal = Flags.isByVal();
2166
2167     // Promote the value if needed.
2168     switch (VA.getLocInfo()) {
2169     default: llvm_unreachable("Unknown loc info!");
2170     case CCValAssign::Full: break;
2171     case CCValAssign::SExt:
2172       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2173       break;
2174     case CCValAssign::ZExt:
2175       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2176       break;
2177     case CCValAssign::AExt:
2178       if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
2179         // Special case: passing MMX values in XMM registers.
2180         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2181         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2182         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2183       } else
2184         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2185       break;
2186     case CCValAssign::BCvt:
2187       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2188       break;
2189     case CCValAssign::Indirect: {
2190       // Store the argument.
2191       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2192       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2193       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2194                            MachinePointerInfo::getFixedStack(FI),
2195                            false, false, 0);
2196       Arg = SpillSlot;
2197       break;
2198     }
2199     }
2200
2201     if (VA.isRegLoc()) {
2202       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2203       if (isVarArg && IsWin64) {
2204         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2205         // shadow reg if callee is a varargs function.
2206         unsigned ShadowReg = 0;
2207         switch (VA.getLocReg()) {
2208         case X86::XMM0: ShadowReg = X86::RCX; break;
2209         case X86::XMM1: ShadowReg = X86::RDX; break;
2210         case X86::XMM2: ShadowReg = X86::R8; break;
2211         case X86::XMM3: ShadowReg = X86::R9; break;
2212         }
2213         if (ShadowReg)
2214           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2215       }
2216     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2217       assert(VA.isMemLoc());
2218       if (StackPtr.getNode() == 0)
2219         StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2220       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2221                                              dl, DAG, VA, Flags));
2222     }
2223   }
2224
2225   if (!MemOpChains.empty())
2226     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2227                         &MemOpChains[0], MemOpChains.size());
2228
2229   // Build a sequence of copy-to-reg nodes chained together with token chain
2230   // and flag operands which copy the outgoing args into registers.
2231   SDValue InFlag;
2232   // Tail call byval lowering might overwrite argument registers so in case of
2233   // tail call optimization the copies to registers are lowered later.
2234   if (!isTailCall)
2235     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2236       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2237                                RegsToPass[i].second, InFlag);
2238       InFlag = Chain.getValue(1);
2239     }
2240
2241   if (Subtarget->isPICStyleGOT()) {
2242     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2243     // GOT pointer.
2244     if (!isTailCall) {
2245       Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2246                                DAG.getNode(X86ISD::GlobalBaseReg,
2247                                            DebugLoc(), getPointerTy()),
2248                                InFlag);
2249       InFlag = Chain.getValue(1);
2250     } else {
2251       // If we are tail calling and generating PIC/GOT style code load the
2252       // address of the callee into ECX. The value in ecx is used as target of
2253       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2254       // for tail calls on PIC/GOT architectures. Normally we would just put the
2255       // address of GOT into ebx and then call target@PLT. But for tail calls
2256       // ebx would be restored (since ebx is callee saved) before jumping to the
2257       // target@PLT.
2258
2259       // Note: The actual moving to ECX is done further down.
2260       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2261       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2262           !G->getGlobal()->hasProtectedVisibility())
2263         Callee = LowerGlobalAddress(Callee, DAG);
2264       else if (isa<ExternalSymbolSDNode>(Callee))
2265         Callee = LowerExternalSymbol(Callee, DAG);
2266     }
2267   }
2268
2269   if (Is64Bit && isVarArg && !IsWin64) {
2270     // From AMD64 ABI document:
2271     // For calls that may call functions that use varargs or stdargs
2272     // (prototype-less calls or calls to functions containing ellipsis (...) in
2273     // the declaration) %al is used as hidden argument to specify the number
2274     // of SSE registers used. The contents of %al do not need to match exactly
2275     // the number of registers, but must be an ubound on the number of SSE
2276     // registers used and is in the range 0 - 8 inclusive.
2277
2278     // Count the number of XMM registers allocated.
2279     static const unsigned XMMArgRegs[] = {
2280       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2281       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2282     };
2283     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2284     assert((Subtarget->hasXMM() || !NumXMMRegs)
2285            && "SSE registers cannot be used when SSE is disabled");
2286
2287     Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2288                              DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2289     InFlag = Chain.getValue(1);
2290   }
2291
2292
2293   // For tail calls lower the arguments to the 'real' stack slot.
2294   if (isTailCall) {
2295     // Force all the incoming stack arguments to be loaded from the stack
2296     // before any new outgoing arguments are stored to the stack, because the
2297     // outgoing stack slots may alias the incoming argument stack slots, and
2298     // the alias isn't otherwise explicit. This is slightly more conservative
2299     // than necessary, because it means that each store effectively depends
2300     // on every argument instead of just those arguments it would clobber.
2301     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2302
2303     SmallVector<SDValue, 8> MemOpChains2;
2304     SDValue FIN;
2305     int FI = 0;
2306     // Do not flag preceding copytoreg stuff together with the following stuff.
2307     InFlag = SDValue();
2308     if (GuaranteedTailCallOpt) {
2309       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2310         CCValAssign &VA = ArgLocs[i];
2311         if (VA.isRegLoc())
2312           continue;
2313         assert(VA.isMemLoc());
2314         SDValue Arg = OutVals[i];
2315         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2316         // Create frame index.
2317         int32_t Offset = VA.getLocMemOffset()+FPDiff;
2318         uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2319         FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2320         FIN = DAG.getFrameIndex(FI, getPointerTy());
2321
2322         if (Flags.isByVal()) {
2323           // Copy relative to framepointer.
2324           SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2325           if (StackPtr.getNode() == 0)
2326             StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2327                                           getPointerTy());
2328           Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2329
2330           MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2331                                                            ArgChain,
2332                                                            Flags, DAG, dl));
2333         } else {
2334           // Store relative to framepointer.
2335           MemOpChains2.push_back(
2336             DAG.getStore(ArgChain, dl, Arg, FIN,
2337                          MachinePointerInfo::getFixedStack(FI),
2338                          false, false, 0));
2339         }
2340       }
2341     }
2342
2343     if (!MemOpChains2.empty())
2344       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2345                           &MemOpChains2[0], MemOpChains2.size());
2346
2347     // Copy arguments to their registers.
2348     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2349       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2350                                RegsToPass[i].second, InFlag);
2351       InFlag = Chain.getValue(1);
2352     }
2353     InFlag =SDValue();
2354
2355     // Store the return address to the appropriate stack slot.
2356     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2357                                      FPDiff, dl);
2358   }
2359
2360   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2361     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2362     // In the 64-bit large code model, we have to make all calls
2363     // through a register, since the call instruction's 32-bit
2364     // pc-relative offset may not be large enough to hold the whole
2365     // address.
2366   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2367     // If the callee is a GlobalAddress node (quite common, every direct call
2368     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2369     // it.
2370
2371     // We should use extra load for direct calls to dllimported functions in
2372     // non-JIT mode.
2373     const GlobalValue *GV = G->getGlobal();
2374     if (!GV->hasDLLImportLinkage()) {
2375       unsigned char OpFlags = 0;
2376       bool ExtraLoad = false;
2377       unsigned WrapperKind = ISD::DELETED_NODE;
2378
2379       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2380       // external symbols most go through the PLT in PIC mode.  If the symbol
2381       // has hidden or protected visibility, or if it is static or local, then
2382       // we don't need to use the PLT - we can directly call it.
2383       if (Subtarget->isTargetELF() &&
2384           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2385           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2386         OpFlags = X86II::MO_PLT;
2387       } else if (Subtarget->isPICStyleStubAny() &&
2388                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2389                  (!Subtarget->getTargetTriple().isMacOSX() ||
2390                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2391         // PC-relative references to external symbols should go through $stub,
2392         // unless we're building with the leopard linker or later, which
2393         // automatically synthesizes these stubs.
2394         OpFlags = X86II::MO_DARWIN_STUB;
2395       } else if (Subtarget->isPICStyleRIPRel() &&
2396                  isa<Function>(GV) &&
2397                  cast<Function>(GV)->hasFnAttr(Attribute::NonLazyBind)) {
2398         // If the function is marked as non-lazy, generate an indirect call
2399         // which loads from the GOT directly. This avoids runtime overhead
2400         // at the cost of eager binding (and one extra byte of encoding).
2401         OpFlags = X86II::MO_GOTPCREL;
2402         WrapperKind = X86ISD::WrapperRIP;
2403         ExtraLoad = true;
2404       }
2405
2406       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2407                                           G->getOffset(), OpFlags);
2408
2409       // Add a wrapper if needed.
2410       if (WrapperKind != ISD::DELETED_NODE)
2411         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2412       // Add extra indirection if needed.
2413       if (ExtraLoad)
2414         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2415                              MachinePointerInfo::getGOT(),
2416                              false, false, false, 0);
2417     }
2418   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2419     unsigned char OpFlags = 0;
2420
2421     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2422     // external symbols should go through the PLT.
2423     if (Subtarget->isTargetELF() &&
2424         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2425       OpFlags = X86II::MO_PLT;
2426     } else if (Subtarget->isPICStyleStubAny() &&
2427                (!Subtarget->getTargetTriple().isMacOSX() ||
2428                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2429       // PC-relative references to external symbols should go through $stub,
2430       // unless we're building with the leopard linker or later, which
2431       // automatically synthesizes these stubs.
2432       OpFlags = X86II::MO_DARWIN_STUB;
2433     }
2434
2435     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2436                                          OpFlags);
2437   }
2438
2439   // Returns a chain & a flag for retval copy to use.
2440   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2441   SmallVector<SDValue, 8> Ops;
2442
2443   if (!IsSibcall && isTailCall) {
2444     Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2445                            DAG.getIntPtrConstant(0, true), InFlag);
2446     InFlag = Chain.getValue(1);
2447   }
2448
2449   Ops.push_back(Chain);
2450   Ops.push_back(Callee);
2451
2452   if (isTailCall)
2453     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2454
2455   // Add argument registers to the end of the list so that they are known live
2456   // into the call.
2457   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2458     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2459                                   RegsToPass[i].second.getValueType()));
2460
2461   // Add an implicit use GOT pointer in EBX.
2462   if (!isTailCall && Subtarget->isPICStyleGOT())
2463     Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2464
2465   // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2466   if (Is64Bit && isVarArg && !IsWin64)
2467     Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2468
2469   if (InFlag.getNode())
2470     Ops.push_back(InFlag);
2471
2472   if (isTailCall) {
2473     // We used to do:
2474     //// If this is the first return lowered for this function, add the regs
2475     //// to the liveout set for the function.
2476     // This isn't right, although it's probably harmless on x86; liveouts
2477     // should be computed from returns not tail calls.  Consider a void
2478     // function making a tail call to a function returning int.
2479     return DAG.getNode(X86ISD::TC_RETURN, dl,
2480                        NodeTys, &Ops[0], Ops.size());
2481   }
2482
2483   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2484   InFlag = Chain.getValue(1);
2485
2486   // Create the CALLSEQ_END node.
2487   unsigned NumBytesForCalleeToPush;
2488   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg, GuaranteedTailCallOpt))
2489     NumBytesForCalleeToPush = NumBytes;    // Callee pops everything
2490   else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2491     // If this is a call to a struct-return function, the callee
2492     // pops the hidden struct pointer, so we have to push it back.
2493     // This is common for Darwin/X86, Linux & Mingw32 targets.
2494     NumBytesForCalleeToPush = 4;
2495   else
2496     NumBytesForCalleeToPush = 0;  // Callee pops nothing.
2497
2498   // Returns a flag for retval copy to use.
2499   if (!IsSibcall) {
2500     Chain = DAG.getCALLSEQ_END(Chain,
2501                                DAG.getIntPtrConstant(NumBytes, true),
2502                                DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2503                                                      true),
2504                                InFlag);
2505     InFlag = Chain.getValue(1);
2506   }
2507
2508   // Handle result values, copying them out of physregs into vregs that we
2509   // return.
2510   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2511                          Ins, dl, DAG, InVals);
2512 }
2513
2514
2515 //===----------------------------------------------------------------------===//
2516 //                Fast Calling Convention (tail call) implementation
2517 //===----------------------------------------------------------------------===//
2518
2519 //  Like std call, callee cleans arguments, convention except that ECX is
2520 //  reserved for storing the tail called function address. Only 2 registers are
2521 //  free for argument passing (inreg). Tail call optimization is performed
2522 //  provided:
2523 //                * tailcallopt is enabled
2524 //                * caller/callee are fastcc
2525 //  On X86_64 architecture with GOT-style position independent code only local
2526 //  (within module) calls are supported at the moment.
2527 //  To keep the stack aligned according to platform abi the function
2528 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
2529 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2530 //  If a tail called function callee has more arguments than the caller the
2531 //  caller needs to make sure that there is room to move the RETADDR to. This is
2532 //  achieved by reserving an area the size of the argument delta right after the
2533 //  original REtADDR, but before the saved framepointer or the spilled registers
2534 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2535 //  stack layout:
2536 //    arg1
2537 //    arg2
2538 //    RETADDR
2539 //    [ new RETADDR
2540 //      move area ]
2541 //    (possible EBP)
2542 //    ESI
2543 //    EDI
2544 //    local1 ..
2545
2546 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2547 /// for a 16 byte align requirement.
2548 unsigned
2549 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2550                                                SelectionDAG& DAG) const {
2551   MachineFunction &MF = DAG.getMachineFunction();
2552   const TargetMachine &TM = MF.getTarget();
2553   const TargetFrameLowering &TFI = *TM.getFrameLowering();
2554   unsigned StackAlignment = TFI.getStackAlignment();
2555   uint64_t AlignMask = StackAlignment - 1;
2556   int64_t Offset = StackSize;
2557   uint64_t SlotSize = TD->getPointerSize();
2558   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2559     // Number smaller than 12 so just add the difference.
2560     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2561   } else {
2562     // Mask out lower bits, add stackalignment once plus the 12 bytes.
2563     Offset = ((~AlignMask) & Offset) + StackAlignment +
2564       (StackAlignment-SlotSize);
2565   }
2566   return Offset;
2567 }
2568
2569 /// MatchingStackOffset - Return true if the given stack call argument is
2570 /// already available in the same position (relatively) of the caller's
2571 /// incoming argument stack.
2572 static
2573 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2574                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2575                          const X86InstrInfo *TII) {
2576   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2577   int FI = INT_MAX;
2578   if (Arg.getOpcode() == ISD::CopyFromReg) {
2579     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2580     if (!TargetRegisterInfo::isVirtualRegister(VR))
2581       return false;
2582     MachineInstr *Def = MRI->getVRegDef(VR);
2583     if (!Def)
2584       return false;
2585     if (!Flags.isByVal()) {
2586       if (!TII->isLoadFromStackSlot(Def, FI))
2587         return false;
2588     } else {
2589       unsigned Opcode = Def->getOpcode();
2590       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2591           Def->getOperand(1).isFI()) {
2592         FI = Def->getOperand(1).getIndex();
2593         Bytes = Flags.getByValSize();
2594       } else
2595         return false;
2596     }
2597   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2598     if (Flags.isByVal())
2599       // ByVal argument is passed in as a pointer but it's now being
2600       // dereferenced. e.g.
2601       // define @foo(%struct.X* %A) {
2602       //   tail call @bar(%struct.X* byval %A)
2603       // }
2604       return false;
2605     SDValue Ptr = Ld->getBasePtr();
2606     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2607     if (!FINode)
2608       return false;
2609     FI = FINode->getIndex();
2610   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
2611     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
2612     FI = FINode->getIndex();
2613     Bytes = Flags.getByValSize();
2614   } else
2615     return false;
2616
2617   assert(FI != INT_MAX);
2618   if (!MFI->isFixedObjectIndex(FI))
2619     return false;
2620   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2621 }
2622
2623 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2624 /// for tail call optimization. Targets which want to do tail call
2625 /// optimization should implement this function.
2626 bool
2627 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2628                                                      CallingConv::ID CalleeCC,
2629                                                      bool isVarArg,
2630                                                      bool isCalleeStructRet,
2631                                                      bool isCallerStructRet,
2632                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2633                                     const SmallVectorImpl<SDValue> &OutVals,
2634                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2635                                                      SelectionDAG& DAG) const {
2636   if (!IsTailCallConvention(CalleeCC) &&
2637       CalleeCC != CallingConv::C)
2638     return false;
2639
2640   // If -tailcallopt is specified, make fastcc functions tail-callable.
2641   const MachineFunction &MF = DAG.getMachineFunction();
2642   const Function *CallerF = DAG.getMachineFunction().getFunction();
2643   CallingConv::ID CallerCC = CallerF->getCallingConv();
2644   bool CCMatch = CallerCC == CalleeCC;
2645
2646   if (GuaranteedTailCallOpt) {
2647     if (IsTailCallConvention(CalleeCC) && CCMatch)
2648       return true;
2649     return false;
2650   }
2651
2652   // Look for obvious safe cases to perform tail call optimization that do not
2653   // require ABI changes. This is what gcc calls sibcall.
2654
2655   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2656   // emit a special epilogue.
2657   if (RegInfo->needsStackRealignment(MF))
2658     return false;
2659
2660   // Also avoid sibcall optimization if either caller or callee uses struct
2661   // return semantics.
2662   if (isCalleeStructRet || isCallerStructRet)
2663     return false;
2664
2665   // An stdcall caller is expected to clean up its arguments; the callee
2666   // isn't going to do that.
2667   if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2668     return false;
2669
2670   // Do not sibcall optimize vararg calls unless all arguments are passed via
2671   // registers.
2672   if (isVarArg && !Outs.empty()) {
2673
2674     // Optimizing for varargs on Win64 is unlikely to be safe without
2675     // additional testing.
2676     if (Subtarget->isTargetWin64())
2677       return false;
2678
2679     SmallVector<CCValAssign, 16> ArgLocs;
2680     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2681                    getTargetMachine(), ArgLocs, *DAG.getContext());
2682
2683     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2684     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2685       if (!ArgLocs[i].isRegLoc())
2686         return false;
2687   }
2688
2689   // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2690   // Therefore if it's not used by the call it is not safe to optimize this into
2691   // a sibcall.
2692   bool Unused = false;
2693   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2694     if (!Ins[i].Used) {
2695       Unused = true;
2696       break;
2697     }
2698   }
2699   if (Unused) {
2700     SmallVector<CCValAssign, 16> RVLocs;
2701     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
2702                    getTargetMachine(), RVLocs, *DAG.getContext());
2703     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2704     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2705       CCValAssign &VA = RVLocs[i];
2706       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2707         return false;
2708     }
2709   }
2710
2711   // If the calling conventions do not match, then we'd better make sure the
2712   // results are returned in the same way as what the caller expects.
2713   if (!CCMatch) {
2714     SmallVector<CCValAssign, 16> RVLocs1;
2715     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
2716                     getTargetMachine(), RVLocs1, *DAG.getContext());
2717     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2718
2719     SmallVector<CCValAssign, 16> RVLocs2;
2720     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
2721                     getTargetMachine(), RVLocs2, *DAG.getContext());
2722     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2723
2724     if (RVLocs1.size() != RVLocs2.size())
2725       return false;
2726     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2727       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2728         return false;
2729       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2730         return false;
2731       if (RVLocs1[i].isRegLoc()) {
2732         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2733           return false;
2734       } else {
2735         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2736           return false;
2737       }
2738     }
2739   }
2740
2741   // If the callee takes no arguments then go on to check the results of the
2742   // call.
2743   if (!Outs.empty()) {
2744     // Check if stack adjustment is needed. For now, do not do this if any
2745     // argument is passed on the stack.
2746     SmallVector<CCValAssign, 16> ArgLocs;
2747     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2748                    getTargetMachine(), ArgLocs, *DAG.getContext());
2749
2750     // Allocate shadow area for Win64
2751     if (Subtarget->isTargetWin64()) {
2752       CCInfo.AllocateStack(32, 8);
2753     }
2754
2755     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2756     if (CCInfo.getNextStackOffset()) {
2757       MachineFunction &MF = DAG.getMachineFunction();
2758       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2759         return false;
2760
2761       // Check if the arguments are already laid out in the right way as
2762       // the caller's fixed stack objects.
2763       MachineFrameInfo *MFI = MF.getFrameInfo();
2764       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2765       const X86InstrInfo *TII =
2766         ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2767       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2768         CCValAssign &VA = ArgLocs[i];
2769         SDValue Arg = OutVals[i];
2770         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2771         if (VA.getLocInfo() == CCValAssign::Indirect)
2772           return false;
2773         if (!VA.isRegLoc()) {
2774           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2775                                    MFI, MRI, TII))
2776             return false;
2777         }
2778       }
2779     }
2780
2781     // If the tailcall address may be in a register, then make sure it's
2782     // possible to register allocate for it. In 32-bit, the call address can
2783     // only target EAX, EDX, or ECX since the tail call must be scheduled after
2784     // callee-saved registers are restored. These happen to be the same
2785     // registers used to pass 'inreg' arguments so watch out for those.
2786     if (!Subtarget->is64Bit() &&
2787         !isa<GlobalAddressSDNode>(Callee) &&
2788         !isa<ExternalSymbolSDNode>(Callee)) {
2789       unsigned NumInRegs = 0;
2790       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2791         CCValAssign &VA = ArgLocs[i];
2792         if (!VA.isRegLoc())
2793           continue;
2794         unsigned Reg = VA.getLocReg();
2795         switch (Reg) {
2796         default: break;
2797         case X86::EAX: case X86::EDX: case X86::ECX:
2798           if (++NumInRegs == 3)
2799             return false;
2800           break;
2801         }
2802       }
2803     }
2804   }
2805
2806   return true;
2807 }
2808
2809 FastISel *
2810 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2811   return X86::createFastISel(funcInfo);
2812 }
2813
2814
2815 //===----------------------------------------------------------------------===//
2816 //                           Other Lowering Hooks
2817 //===----------------------------------------------------------------------===//
2818
2819 static bool MayFoldLoad(SDValue Op) {
2820   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2821 }
2822
2823 static bool MayFoldIntoStore(SDValue Op) {
2824   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2825 }
2826
2827 static bool isTargetShuffle(unsigned Opcode) {
2828   switch(Opcode) {
2829   default: return false;
2830   case X86ISD::PSHUFD:
2831   case X86ISD::PSHUFHW:
2832   case X86ISD::PSHUFLW:
2833   case X86ISD::SHUFPD:
2834   case X86ISD::PALIGN:
2835   case X86ISD::SHUFPS:
2836   case X86ISD::MOVLHPS:
2837   case X86ISD::MOVLHPD:
2838   case X86ISD::MOVHLPS:
2839   case X86ISD::MOVLPS:
2840   case X86ISD::MOVLPD:
2841   case X86ISD::MOVSHDUP:
2842   case X86ISD::MOVSLDUP:
2843   case X86ISD::MOVDDUP:
2844   case X86ISD::MOVSS:
2845   case X86ISD::MOVSD:
2846   case X86ISD::UNPCKLPS:
2847   case X86ISD::UNPCKLPD:
2848   case X86ISD::VUNPCKLPSY:
2849   case X86ISD::VUNPCKLPDY:
2850   case X86ISD::PUNPCKLWD:
2851   case X86ISD::PUNPCKLBW:
2852   case X86ISD::PUNPCKLDQ:
2853   case X86ISD::PUNPCKLQDQ:
2854   case X86ISD::VPUNPCKLWDY:
2855   case X86ISD::VPUNPCKLBWY:
2856   case X86ISD::VPUNPCKLDQY:
2857   case X86ISD::VPUNPCKLQDQY:
2858   case X86ISD::UNPCKHPS:
2859   case X86ISD::UNPCKHPD:
2860   case X86ISD::VUNPCKHPSY:
2861   case X86ISD::VUNPCKHPDY:
2862   case X86ISD::PUNPCKHWD:
2863   case X86ISD::PUNPCKHBW:
2864   case X86ISD::PUNPCKHDQ:
2865   case X86ISD::PUNPCKHQDQ:
2866   case X86ISD::VPUNPCKHWDY:
2867   case X86ISD::VPUNPCKHBWY:
2868   case X86ISD::VPUNPCKHDQY:
2869   case X86ISD::VPUNPCKHQDQY:
2870   case X86ISD::VPERMILPS:
2871   case X86ISD::VPERMILPSY:
2872   case X86ISD::VPERMILPD:
2873   case X86ISD::VPERMILPDY:
2874   case X86ISD::VPERM2F128:
2875     return true;
2876   }
2877   return false;
2878 }
2879
2880 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2881                                                SDValue V1, SelectionDAG &DAG) {
2882   switch(Opc) {
2883   default: llvm_unreachable("Unknown x86 shuffle node");
2884   case X86ISD::MOVSHDUP:
2885   case X86ISD::MOVSLDUP:
2886   case X86ISD::MOVDDUP:
2887     return DAG.getNode(Opc, dl, VT, V1);
2888   }
2889
2890   return SDValue();
2891 }
2892
2893 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2894                           SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2895   switch(Opc) {
2896   default: llvm_unreachable("Unknown x86 shuffle node");
2897   case X86ISD::PSHUFD:
2898   case X86ISD::PSHUFHW:
2899   case X86ISD::PSHUFLW:
2900   case X86ISD::VPERMILPS:
2901   case X86ISD::VPERMILPSY:
2902   case X86ISD::VPERMILPD:
2903   case X86ISD::VPERMILPDY:
2904     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2905   }
2906
2907   return SDValue();
2908 }
2909
2910 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2911                SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2912   switch(Opc) {
2913   default: llvm_unreachable("Unknown x86 shuffle node");
2914   case X86ISD::PALIGN:
2915   case X86ISD::SHUFPD:
2916   case X86ISD::SHUFPS:
2917   case X86ISD::VPERM2F128:
2918     return DAG.getNode(Opc, dl, VT, V1, V2,
2919                        DAG.getConstant(TargetMask, MVT::i8));
2920   }
2921   return SDValue();
2922 }
2923
2924 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2925                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
2926   switch(Opc) {
2927   default: llvm_unreachable("Unknown x86 shuffle node");
2928   case X86ISD::MOVLHPS:
2929   case X86ISD::MOVLHPD:
2930   case X86ISD::MOVHLPS:
2931   case X86ISD::MOVLPS:
2932   case X86ISD::MOVLPD:
2933   case X86ISD::MOVSS:
2934   case X86ISD::MOVSD:
2935   case X86ISD::UNPCKLPS:
2936   case X86ISD::UNPCKLPD:
2937   case X86ISD::VUNPCKLPSY:
2938   case X86ISD::VUNPCKLPDY:
2939   case X86ISD::PUNPCKLWD:
2940   case X86ISD::PUNPCKLBW:
2941   case X86ISD::PUNPCKLDQ:
2942   case X86ISD::PUNPCKLQDQ:
2943   case X86ISD::VPUNPCKLWDY:
2944   case X86ISD::VPUNPCKLBWY:
2945   case X86ISD::VPUNPCKLDQY:
2946   case X86ISD::VPUNPCKLQDQY:
2947   case X86ISD::UNPCKHPS:
2948   case X86ISD::UNPCKHPD:
2949   case X86ISD::VUNPCKHPSY:
2950   case X86ISD::VUNPCKHPDY:
2951   case X86ISD::PUNPCKHWD:
2952   case X86ISD::PUNPCKHBW:
2953   case X86ISD::PUNPCKHDQ:
2954   case X86ISD::PUNPCKHQDQ:
2955   case X86ISD::VPUNPCKHWDY:
2956   case X86ISD::VPUNPCKHBWY:
2957   case X86ISD::VPUNPCKHDQY:
2958   case X86ISD::VPUNPCKHQDQY:
2959     return DAG.getNode(Opc, dl, VT, V1, V2);
2960   }
2961   return SDValue();
2962 }
2963
2964 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2965   MachineFunction &MF = DAG.getMachineFunction();
2966   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2967   int ReturnAddrIndex = FuncInfo->getRAIndex();
2968
2969   if (ReturnAddrIndex == 0) {
2970     // Set up a frame object for the return address.
2971     uint64_t SlotSize = TD->getPointerSize();
2972     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2973                                                            false);
2974     FuncInfo->setRAIndex(ReturnAddrIndex);
2975   }
2976
2977   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2978 }
2979
2980
2981 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2982                                        bool hasSymbolicDisplacement) {
2983   // Offset should fit into 32 bit immediate field.
2984   if (!isInt<32>(Offset))
2985     return false;
2986
2987   // If we don't have a symbolic displacement - we don't have any extra
2988   // restrictions.
2989   if (!hasSymbolicDisplacement)
2990     return true;
2991
2992   // FIXME: Some tweaks might be needed for medium code model.
2993   if (M != CodeModel::Small && M != CodeModel::Kernel)
2994     return false;
2995
2996   // For small code model we assume that latest object is 16MB before end of 31
2997   // bits boundary. We may also accept pretty large negative constants knowing
2998   // that all objects are in the positive half of address space.
2999   if (M == CodeModel::Small && Offset < 16*1024*1024)
3000     return true;
3001
3002   // For kernel code model we know that all object resist in the negative half
3003   // of 32bits address space. We may not accept negative offsets, since they may
3004   // be just off and we may accept pretty large positive ones.
3005   if (M == CodeModel::Kernel && Offset > 0)
3006     return true;
3007
3008   return false;
3009 }
3010
3011 /// isCalleePop - Determines whether the callee is required to pop its
3012 /// own arguments. Callee pop is necessary to support tail calls.
3013 bool X86::isCalleePop(CallingConv::ID CallingConv,
3014                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3015   if (IsVarArg)
3016     return false;
3017
3018   switch (CallingConv) {
3019   default:
3020     return false;
3021   case CallingConv::X86_StdCall:
3022     return !is64Bit;
3023   case CallingConv::X86_FastCall:
3024     return !is64Bit;
3025   case CallingConv::X86_ThisCall:
3026     return !is64Bit;
3027   case CallingConv::Fast:
3028     return TailCallOpt;
3029   case CallingConv::GHC:
3030     return TailCallOpt;
3031   }
3032 }
3033
3034 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3035 /// specific condition code, returning the condition code and the LHS/RHS of the
3036 /// comparison to make.
3037 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3038                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3039   if (!isFP) {
3040     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3041       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3042         // X > -1   -> X == 0, jump !sign.
3043         RHS = DAG.getConstant(0, RHS.getValueType());
3044         return X86::COND_NS;
3045       } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3046         // X < 0   -> X == 0, jump on sign.
3047         return X86::COND_S;
3048       } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3049         // X < 1   -> X <= 0
3050         RHS = DAG.getConstant(0, RHS.getValueType());
3051         return X86::COND_LE;
3052       }
3053     }
3054
3055     switch (SetCCOpcode) {
3056     default: llvm_unreachable("Invalid integer condition!");
3057     case ISD::SETEQ:  return X86::COND_E;
3058     case ISD::SETGT:  return X86::COND_G;
3059     case ISD::SETGE:  return X86::COND_GE;
3060     case ISD::SETLT:  return X86::COND_L;
3061     case ISD::SETLE:  return X86::COND_LE;
3062     case ISD::SETNE:  return X86::COND_NE;
3063     case ISD::SETULT: return X86::COND_B;
3064     case ISD::SETUGT: return X86::COND_A;
3065     case ISD::SETULE: return X86::COND_BE;
3066     case ISD::SETUGE: return X86::COND_AE;
3067     }
3068   }
3069
3070   // First determine if it is required or is profitable to flip the operands.
3071
3072   // If LHS is a foldable load, but RHS is not, flip the condition.
3073   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3074       !ISD::isNON_EXTLoad(RHS.getNode())) {
3075     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3076     std::swap(LHS, RHS);
3077   }
3078
3079   switch (SetCCOpcode) {
3080   default: break;
3081   case ISD::SETOLT:
3082   case ISD::SETOLE:
3083   case ISD::SETUGT:
3084   case ISD::SETUGE:
3085     std::swap(LHS, RHS);
3086     break;
3087   }
3088
3089   // On a floating point condition, the flags are set as follows:
3090   // ZF  PF  CF   op
3091   //  0 | 0 | 0 | X > Y
3092   //  0 | 0 | 1 | X < Y
3093   //  1 | 0 | 0 | X == Y
3094   //  1 | 1 | 1 | unordered
3095   switch (SetCCOpcode) {
3096   default: llvm_unreachable("Condcode should be pre-legalized away");
3097   case ISD::SETUEQ:
3098   case ISD::SETEQ:   return X86::COND_E;
3099   case ISD::SETOLT:              // flipped
3100   case ISD::SETOGT:
3101   case ISD::SETGT:   return X86::COND_A;
3102   case ISD::SETOLE:              // flipped
3103   case ISD::SETOGE:
3104   case ISD::SETGE:   return X86::COND_AE;
3105   case ISD::SETUGT:              // flipped
3106   case ISD::SETULT:
3107   case ISD::SETLT:   return X86::COND_B;
3108   case ISD::SETUGE:              // flipped
3109   case ISD::SETULE:
3110   case ISD::SETLE:   return X86::COND_BE;
3111   case ISD::SETONE:
3112   case ISD::SETNE:   return X86::COND_NE;
3113   case ISD::SETUO:   return X86::COND_P;
3114   case ISD::SETO:    return X86::COND_NP;
3115   case ISD::SETOEQ:
3116   case ISD::SETUNE:  return X86::COND_INVALID;
3117   }
3118 }
3119
3120 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3121 /// code. Current x86 isa includes the following FP cmov instructions:
3122 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3123 static bool hasFPCMov(unsigned X86CC) {
3124   switch (X86CC) {
3125   default:
3126     return false;
3127   case X86::COND_B:
3128   case X86::COND_BE:
3129   case X86::COND_E:
3130   case X86::COND_P:
3131   case X86::COND_A:
3132   case X86::COND_AE:
3133   case X86::COND_NE:
3134   case X86::COND_NP:
3135     return true;
3136   }
3137 }
3138
3139 /// isFPImmLegal - Returns true if the target can instruction select the
3140 /// specified FP immediate natively. If false, the legalizer will
3141 /// materialize the FP immediate as a load from a constant pool.
3142 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3143   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3144     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3145       return true;
3146   }
3147   return false;
3148 }
3149
3150 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3151 /// the specified range (L, H].
3152 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3153   return (Val < 0) || (Val >= Low && Val < Hi);
3154 }
3155
3156 /// isUndefOrInRange - Return true if every element in Mask, begining
3157 /// from position Pos and ending in Pos+Size, falls within the specified
3158 /// range (L, L+Pos]. or is undef.
3159 static bool isUndefOrInRange(const SmallVectorImpl<int> &Mask,
3160                              int Pos, int Size, int Low, int Hi) {
3161   for (int i = Pos, e = Pos+Size; i != e; ++i)
3162     if (!isUndefOrInRange(Mask[i], Low, Hi))
3163       return false;
3164   return true;
3165 }
3166
3167 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3168 /// specified value.
3169 static bool isUndefOrEqual(int Val, int CmpVal) {
3170   if (Val < 0 || Val == CmpVal)
3171     return true;
3172   return false;
3173 }
3174
3175 /// isSequentialOrUndefInRange - Return true if every element in Mask, begining
3176 /// from position Pos and ending in Pos+Size, falls within the specified
3177 /// sequential range (L, L+Pos]. or is undef.
3178 static bool isSequentialOrUndefInRange(const SmallVectorImpl<int> &Mask,
3179                                        int Pos, int Size, int Low) {
3180   for (int i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3181     if (!isUndefOrEqual(Mask[i], Low))
3182       return false;
3183   return true;
3184 }
3185
3186 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3187 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3188 /// the second operand.
3189 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3190   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3191     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3192   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3193     return (Mask[0] < 2 && Mask[1] < 2);
3194   return false;
3195 }
3196
3197 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
3198   SmallVector<int, 8> M;
3199   N->getMask(M);
3200   return ::isPSHUFDMask(M, N->getValueType(0));
3201 }
3202
3203 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3204 /// is suitable for input to PSHUFHW.
3205 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3206   if (VT != MVT::v8i16)
3207     return false;
3208
3209   // Lower quadword copied in order or undef.
3210   for (int i = 0; i != 4; ++i)
3211     if (Mask[i] >= 0 && Mask[i] != i)
3212       return false;
3213
3214   // Upper quadword shuffled.
3215   for (int i = 4; i != 8; ++i)
3216     if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
3217       return false;
3218
3219   return true;
3220 }
3221
3222 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
3223   SmallVector<int, 8> M;
3224   N->getMask(M);
3225   return ::isPSHUFHWMask(M, N->getValueType(0));
3226 }
3227
3228 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3229 /// is suitable for input to PSHUFLW.
3230 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3231   if (VT != MVT::v8i16)
3232     return false;
3233
3234   // Upper quadword copied in order.
3235   for (int i = 4; i != 8; ++i)
3236     if (Mask[i] >= 0 && Mask[i] != i)
3237       return false;
3238
3239   // Lower quadword shuffled.
3240   for (int i = 0; i != 4; ++i)
3241     if (Mask[i] >= 4)
3242       return false;
3243
3244   return true;
3245 }
3246
3247 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
3248   SmallVector<int, 8> M;
3249   N->getMask(M);
3250   return ::isPSHUFLWMask(M, N->getValueType(0));
3251 }
3252
3253 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3254 /// is suitable for input to PALIGNR.
3255 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
3256                           bool hasSSSE3OrAVX) {
3257   int i, e = VT.getVectorNumElements();
3258   if (VT.getSizeInBits() != 128 && VT.getSizeInBits() != 64)
3259     return false;
3260
3261   // Do not handle v2i64 / v2f64 shuffles with palignr.
3262   if (e < 4 || !hasSSSE3OrAVX)
3263     return false;
3264
3265   for (i = 0; i != e; ++i)
3266     if (Mask[i] >= 0)
3267       break;
3268
3269   // All undef, not a palignr.
3270   if (i == e)
3271     return false;
3272
3273   // Make sure we're shifting in the right direction.
3274   if (Mask[i] <= i)
3275     return false;
3276
3277   int s = Mask[i] - i;
3278
3279   // Check the rest of the elements to see if they are consecutive.
3280   for (++i; i != e; ++i) {
3281     int m = Mask[i];
3282     if (m >= 0 && m != s+i)
3283       return false;
3284   }
3285   return true;
3286 }
3287
3288 /// isVSHUFPSYMask - Return true if the specified VECTOR_SHUFFLE operand
3289 /// specifies a shuffle of elements that is suitable for input to 256-bit
3290 /// VSHUFPSY.
3291 static bool isVSHUFPSYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3292                           const X86Subtarget *Subtarget) {
3293   int NumElems = VT.getVectorNumElements();
3294
3295   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3296     return false;
3297
3298   if (NumElems != 8)
3299     return false;
3300
3301   // VSHUFPSY divides the resulting vector into 4 chunks.
3302   // The sources are also splitted into 4 chunks, and each destination
3303   // chunk must come from a different source chunk.
3304   //
3305   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3306   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3307   //
3308   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3309   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3310   //
3311   int QuarterSize = NumElems/4;
3312   int HalfSize = QuarterSize*2;
3313   for (int i = 0; i < QuarterSize; ++i)
3314     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3315       return false;
3316   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3317     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3318       return false;
3319
3320   // The mask of the second half must be the same as the first but with
3321   // the appropriate offsets. This works in the same way as VPERMILPS
3322   // works with masks.
3323   for (int i = QuarterSize*2; i < QuarterSize*3; ++i) {
3324     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3325       return false;
3326     int FstHalfIdx = i-HalfSize;
3327     if (Mask[FstHalfIdx] < 0)
3328       continue;
3329     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3330       return false;
3331   }
3332   for (int i = QuarterSize*3; i < NumElems; ++i) {
3333     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3334       return false;
3335     int FstHalfIdx = i-HalfSize;
3336     if (Mask[FstHalfIdx] < 0)
3337       continue;
3338     if (!isUndefOrEqual(Mask[i], Mask[FstHalfIdx]+HalfSize))
3339       return false;
3340
3341   }
3342
3343   return true;
3344 }
3345
3346 /// getShuffleVSHUFPSYImmediate - Return the appropriate immediate to shuffle
3347 /// the specified VECTOR_MASK mask with VSHUFPSY instruction.
3348 static unsigned getShuffleVSHUFPSYImmediate(SDNode *N) {
3349   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3350   EVT VT = SVOp->getValueType(0);
3351   int NumElems = VT.getVectorNumElements();
3352
3353   assert(NumElems == 8 && VT.getSizeInBits() == 256 &&
3354          "Only supports v8i32 and v8f32 types");
3355
3356   int HalfSize = NumElems/2;
3357   unsigned Mask = 0;
3358   for (int i = 0; i != NumElems ; ++i) {
3359     if (SVOp->getMaskElt(i) < 0)
3360       continue;
3361     // The mask of the first half must be equal to the second one.
3362     unsigned Shamt = (i%HalfSize)*2;
3363     unsigned Elt = SVOp->getMaskElt(i) % HalfSize;
3364     Mask |= Elt << Shamt;
3365   }
3366
3367   return Mask;
3368 }
3369
3370 /// isVSHUFPDYMask - Return true if the specified VECTOR_SHUFFLE operand
3371 /// specifies a shuffle of elements that is suitable for input to 256-bit
3372 /// VSHUFPDY. This shuffle doesn't have the same restriction as the PS
3373 /// version and the mask of the second half isn't binded with the first
3374 /// one.
3375 static bool isVSHUFPDYMask(const SmallVectorImpl<int> &Mask, EVT VT,
3376                            const X86Subtarget *Subtarget) {
3377   int NumElems = VT.getVectorNumElements();
3378
3379   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3380     return false;
3381
3382   if (NumElems != 4)
3383     return false;
3384
3385   // VSHUFPSY divides the resulting vector into 4 chunks.
3386   // The sources are also splitted into 4 chunks, and each destination
3387   // chunk must come from a different source chunk.
3388   //
3389   //  SRC1 =>      X3       X2       X1       X0
3390   //  SRC2 =>      Y3       Y2       Y1       Y0
3391   //
3392   //  DST  =>  Y2..Y3,  X2..X3,  Y1..Y0,  X1..X0
3393   //
3394   int QuarterSize = NumElems/4;
3395   int HalfSize = QuarterSize*2;
3396   for (int i = 0; i < QuarterSize; ++i)
3397     if (!isUndefOrInRange(Mask[i], 0, HalfSize))
3398       return false;
3399   for (int i = QuarterSize; i < QuarterSize*2; ++i)
3400     if (!isUndefOrInRange(Mask[i], NumElems, NumElems+HalfSize))
3401       return false;
3402   for (int i = QuarterSize*2; i < QuarterSize*3; ++i)
3403     if (!isUndefOrInRange(Mask[i], HalfSize, NumElems))
3404       return false;
3405   for (int i = QuarterSize*3; i < NumElems; ++i)
3406     if (!isUndefOrInRange(Mask[i], NumElems+HalfSize, NumElems*2))
3407       return false;
3408
3409   return true;
3410 }
3411
3412 /// getShuffleVSHUFPDYImmediate - Return the appropriate immediate to shuffle
3413 /// the specified VECTOR_MASK mask with VSHUFPDY instruction.
3414 static unsigned getShuffleVSHUFPDYImmediate(SDNode *N) {
3415   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3416   EVT VT = SVOp->getValueType(0);
3417   int NumElems = VT.getVectorNumElements();
3418
3419   assert(NumElems == 4 && VT.getSizeInBits() == 256 &&
3420          "Only supports v4i64 and v4f64 types");
3421
3422   int HalfSize = NumElems/2;
3423   unsigned Mask = 0;
3424   for (int i = 0; i != NumElems ; ++i) {
3425     if (SVOp->getMaskElt(i) < 0)
3426       continue;
3427     int Elt = SVOp->getMaskElt(i) % HalfSize;
3428     Mask |= Elt << i;
3429   }
3430
3431   return Mask;
3432 }
3433
3434 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3435 /// specifies a shuffle of elements that is suitable for input to 128-bit
3436 /// SHUFPS and SHUFPD.
3437 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3438   int NumElems = VT.getVectorNumElements();
3439
3440   if (VT.getSizeInBits() != 128)
3441     return false;
3442
3443   if (NumElems != 2 && NumElems != 4)
3444     return false;
3445
3446   int Half = NumElems / 2;
3447   for (int i = 0; i < Half; ++i)
3448     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3449       return false;
3450   for (int i = Half; i < NumElems; ++i)
3451     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3452       return false;
3453
3454   return true;
3455 }
3456
3457 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3458   SmallVector<int, 8> M;
3459   N->getMask(M);
3460   return ::isSHUFPMask(M, N->getValueType(0));
3461 }
3462
3463 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3464 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3465 /// half elements to come from vector 1 (which would equal the dest.) and
3466 /// the upper half to come from vector 2.
3467 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3468   int NumElems = VT.getVectorNumElements();
3469
3470   if (NumElems != 2 && NumElems != 4)
3471     return false;
3472
3473   int Half = NumElems / 2;
3474   for (int i = 0; i < Half; ++i)
3475     if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3476       return false;
3477   for (int i = Half; i < NumElems; ++i)
3478     if (!isUndefOrInRange(Mask[i], 0, NumElems))
3479       return false;
3480   return true;
3481 }
3482
3483 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3484   SmallVector<int, 8> M;
3485   N->getMask(M);
3486   return isCommutedSHUFPMask(M, N->getValueType(0));
3487 }
3488
3489 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3490 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3491 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3492   EVT VT = N->getValueType(0);
3493   unsigned NumElems = VT.getVectorNumElements();
3494
3495   if (VT.getSizeInBits() != 128)
3496     return false;
3497
3498   if (NumElems != 4)
3499     return false;
3500
3501   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3502   return isUndefOrEqual(N->getMaskElt(0), 6) &&
3503          isUndefOrEqual(N->getMaskElt(1), 7) &&
3504          isUndefOrEqual(N->getMaskElt(2), 2) &&
3505          isUndefOrEqual(N->getMaskElt(3), 3);
3506 }
3507
3508 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3509 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3510 /// <2, 3, 2, 3>
3511 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3512   EVT VT = N->getValueType(0);
3513   unsigned NumElems = VT.getVectorNumElements();
3514
3515   if (VT.getSizeInBits() != 128)
3516     return false;
3517
3518   if (NumElems != 4)
3519     return false;
3520
3521   return isUndefOrEqual(N->getMaskElt(0), 2) &&
3522          isUndefOrEqual(N->getMaskElt(1), 3) &&
3523          isUndefOrEqual(N->getMaskElt(2), 2) &&
3524          isUndefOrEqual(N->getMaskElt(3), 3);
3525 }
3526
3527 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3528 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3529 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3530   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3531
3532   if (NumElems != 2 && NumElems != 4)
3533     return false;
3534
3535   for (unsigned i = 0; i < NumElems/2; ++i)
3536     if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3537       return false;
3538
3539   for (unsigned i = NumElems/2; i < NumElems; ++i)
3540     if (!isUndefOrEqual(N->getMaskElt(i), i))
3541       return false;
3542
3543   return true;
3544 }
3545
3546 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3547 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3548 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3549   unsigned NumElems = N->getValueType(0).getVectorNumElements();
3550
3551   if ((NumElems != 2 && NumElems != 4)
3552       || N->getValueType(0).getSizeInBits() > 128)
3553     return false;
3554
3555   for (unsigned i = 0; i < NumElems/2; ++i)
3556     if (!isUndefOrEqual(N->getMaskElt(i), i))
3557       return false;
3558
3559   for (unsigned i = 0; i < NumElems/2; ++i)
3560     if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3561       return false;
3562
3563   return true;
3564 }
3565
3566 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3567 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3568 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3569                          bool HasAVX2, bool V2IsSplat = false) {
3570   int NumElts = VT.getVectorNumElements();
3571
3572   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3573          "Unsupported vector type for unpckh");
3574
3575   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3576       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3577     return false;
3578
3579   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3580   // independently on 128-bit lanes.
3581   unsigned NumLanes = VT.getSizeInBits()/128;
3582   unsigned NumLaneElts = NumElts/NumLanes;
3583
3584   unsigned Start = 0;
3585   unsigned End = NumLaneElts;
3586   for (unsigned s = 0; s < NumLanes; ++s) {
3587     for (unsigned i = Start, j = s * NumLaneElts;
3588          i != End;
3589          i += 2, ++j) {
3590       int BitI  = Mask[i];
3591       int BitI1 = Mask[i+1];
3592       if (!isUndefOrEqual(BitI, j))
3593         return false;
3594       if (V2IsSplat) {
3595         if (!isUndefOrEqual(BitI1, NumElts))
3596           return false;
3597       } else {
3598         if (!isUndefOrEqual(BitI1, j + NumElts))
3599           return false;
3600       }
3601     }
3602     // Process the next 128 bits.
3603     Start += NumLaneElts;
3604     End += NumLaneElts;
3605   }
3606
3607   return true;
3608 }
3609
3610 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3611   SmallVector<int, 8> M;
3612   N->getMask(M);
3613   return ::isUNPCKLMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3614 }
3615
3616 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3617 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3618 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3619                          bool HasAVX2, bool V2IsSplat = false) {
3620   int NumElts = VT.getVectorNumElements();
3621
3622   assert((VT.is128BitVector() || VT.is256BitVector()) &&
3623          "Unsupported vector type for unpckh");
3624
3625   if (VT.getSizeInBits() == 256 && NumElts != 4 && NumElts != 8 &&
3626       (!HasAVX2 || (NumElts != 16 && NumElts != 32)))
3627     return false;
3628
3629   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3630   // independently on 128-bit lanes.
3631   unsigned NumLanes = VT.getSizeInBits()/128;
3632   unsigned NumLaneElts = NumElts/NumLanes;
3633
3634   unsigned Start = 0;
3635   unsigned End = NumLaneElts;
3636   for (unsigned l = 0; l != NumLanes; ++l) {
3637     for (unsigned i = Start, j = (l*NumLaneElts)+NumLaneElts/2;
3638                              i != End; i += 2, ++j) {
3639       int BitI  = Mask[i];
3640       int BitI1 = Mask[i+1];
3641       if (!isUndefOrEqual(BitI, j))
3642         return false;
3643       if (V2IsSplat) {
3644         if (isUndefOrEqual(BitI1, NumElts))
3645           return false;
3646       } else {
3647         if (!isUndefOrEqual(BitI1, j+NumElts))
3648           return false;
3649       }
3650     }
3651     // Process the next 128 bits.
3652     Start += NumLaneElts;
3653     End += NumLaneElts;
3654   }
3655   return true;
3656 }
3657
3658 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool HasAVX2, bool V2IsSplat) {
3659   SmallVector<int, 8> M;
3660   N->getMask(M);
3661   return ::isUNPCKHMask(M, N->getValueType(0), HasAVX2, V2IsSplat);
3662 }
3663
3664 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3665 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3666 /// <0, 0, 1, 1>
3667 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3668   int NumElems = VT.getVectorNumElements();
3669   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3670     return false;
3671
3672   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
3673   // FIXME: Need a better way to get rid of this, there's no latency difference
3674   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
3675   // the former later. We should also remove the "_undef" special mask.
3676   if (NumElems == 4 && VT.getSizeInBits() == 256)
3677     return false;
3678
3679   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
3680   // independently on 128-bit lanes.
3681   unsigned NumLanes = VT.getSizeInBits() / 128;
3682   unsigned NumLaneElts = NumElems / NumLanes;
3683
3684   for (unsigned s = 0; s < NumLanes; ++s) {
3685     for (unsigned i = s * NumLaneElts, j = s * NumLaneElts;
3686          i != NumLaneElts * (s + 1);
3687          i += 2, ++j) {
3688       int BitI  = Mask[i];
3689       int BitI1 = Mask[i+1];
3690
3691       if (!isUndefOrEqual(BitI, j))
3692         return false;
3693       if (!isUndefOrEqual(BitI1, j))
3694         return false;
3695     }
3696   }
3697
3698   return true;
3699 }
3700
3701 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3702   SmallVector<int, 8> M;
3703   N->getMask(M);
3704   return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3705 }
3706
3707 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3708 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3709 /// <2, 2, 3, 3>
3710 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3711   int NumElems = VT.getVectorNumElements();
3712   if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3713     return false;
3714
3715   for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3716     int BitI  = Mask[i];
3717     int BitI1 = Mask[i+1];
3718     if (!isUndefOrEqual(BitI, j))
3719       return false;
3720     if (!isUndefOrEqual(BitI1, j))
3721       return false;
3722   }
3723   return true;
3724 }
3725
3726 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3727   SmallVector<int, 8> M;
3728   N->getMask(M);
3729   return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3730 }
3731
3732 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3733 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3734 /// MOVSD, and MOVD, i.e. setting the lowest element.
3735 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3736   if (VT.getVectorElementType().getSizeInBits() < 32)
3737     return false;
3738
3739   int NumElts = VT.getVectorNumElements();
3740
3741   if (!isUndefOrEqual(Mask[0], NumElts))
3742     return false;
3743
3744   for (int i = 1; i < NumElts; ++i)
3745     if (!isUndefOrEqual(Mask[i], i))
3746       return false;
3747
3748   return true;
3749 }
3750
3751 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3752   SmallVector<int, 8> M;
3753   N->getMask(M);
3754   return ::isMOVLMask(M, N->getValueType(0));
3755 }
3756
3757 /// isVPERM2F128Mask - Match 256-bit shuffles where the elements are considered
3758 /// as permutations between 128-bit chunks or halves. As an example: this
3759 /// shuffle bellow:
3760 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
3761 /// The first half comes from the second half of V1 and the second half from the
3762 /// the second half of V2.
3763 static bool isVPERM2F128Mask(const SmallVectorImpl<int> &Mask, EVT VT,
3764                              const X86Subtarget *Subtarget) {
3765   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256)
3766     return false;
3767
3768   // The shuffle result is divided into half A and half B. In total the two
3769   // sources have 4 halves, namely: C, D, E, F. The final values of A and
3770   // B must come from C, D, E or F.
3771   int HalfSize = VT.getVectorNumElements()/2;
3772   bool MatchA = false, MatchB = false;
3773
3774   // Check if A comes from one of C, D, E, F.
3775   for (int Half = 0; Half < 4; ++Half) {
3776     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
3777       MatchA = true;
3778       break;
3779     }
3780   }
3781
3782   // Check if B comes from one of C, D, E, F.
3783   for (int Half = 0; Half < 4; ++Half) {
3784     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
3785       MatchB = true;
3786       break;
3787     }
3788   }
3789
3790   return MatchA && MatchB;
3791 }
3792
3793 /// getShuffleVPERM2F128Immediate - Return the appropriate immediate to shuffle
3794 /// the specified VECTOR_MASK mask with VPERM2F128 instructions.
3795 static unsigned getShuffleVPERM2F128Immediate(SDNode *N) {
3796   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3797   EVT VT = SVOp->getValueType(0);
3798
3799   int HalfSize = VT.getVectorNumElements()/2;
3800
3801   int FstHalf = 0, SndHalf = 0;
3802   for (int i = 0; i < HalfSize; ++i) {
3803     if (SVOp->getMaskElt(i) > 0) {
3804       FstHalf = SVOp->getMaskElt(i)/HalfSize;
3805       break;
3806     }
3807   }
3808   for (int i = HalfSize; i < HalfSize*2; ++i) {
3809     if (SVOp->getMaskElt(i) > 0) {
3810       SndHalf = SVOp->getMaskElt(i)/HalfSize;
3811       break;
3812     }
3813   }
3814
3815   return (FstHalf | (SndHalf << 4));
3816 }
3817
3818 /// isVPERMILPDMask - Return true if the specified VECTOR_SHUFFLE operand
3819 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
3820 /// Note that VPERMIL mask matching is different depending whether theunderlying
3821 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3822 /// to the same elements of the low, but to the higher half of the source.
3823 /// In VPERMILPD the two lanes could be shuffled independently of each other
3824 /// with the same restriction that lanes can't be crossed.
3825 static bool isVPERMILPDMask(const SmallVectorImpl<int> &Mask, EVT VT,
3826                             const X86Subtarget *Subtarget) {
3827   int NumElts = VT.getVectorNumElements();
3828   int NumLanes = VT.getSizeInBits()/128;
3829
3830   if (!Subtarget->hasAVX())
3831     return false;
3832
3833   // Only match 256-bit with 64-bit types
3834   if (VT.getSizeInBits() != 256 || NumElts != 4)
3835     return false;
3836
3837   // The mask on the high lane is independent of the low. Both can match
3838   // any element in inside its own lane, but can't cross.
3839   int LaneSize = NumElts/NumLanes;
3840   for (int l = 0; l < NumLanes; ++l)
3841     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3842       int LaneStart = l*LaneSize;
3843       if (!isUndefOrInRange(Mask[i], LaneStart, LaneStart+LaneSize))
3844         return false;
3845     }
3846
3847   return true;
3848 }
3849
3850 /// isVPERMILPSMask - Return true if the specified VECTOR_SHUFFLE operand
3851 /// specifies a shuffle of elements that is suitable for input to VPERMILPS*.
3852 /// Note that VPERMIL mask matching is different depending whether theunderlying
3853 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
3854 /// to the same elements of the low, but to the higher half of the source.
3855 /// In VPERMILPD the two lanes could be shuffled independently of each other
3856 /// with the same restriction that lanes can't be crossed.
3857 static bool isVPERMILPSMask(const SmallVectorImpl<int> &Mask, EVT VT,
3858                             const X86Subtarget *Subtarget) {
3859   unsigned NumElts = VT.getVectorNumElements();
3860   unsigned NumLanes = VT.getSizeInBits()/128;
3861
3862   if (!Subtarget->hasAVX())
3863     return false;
3864
3865   // Only match 256-bit with 32-bit types
3866   if (VT.getSizeInBits() != 256 || NumElts != 8)
3867     return false;
3868
3869   // The mask on the high lane should be the same as the low. Actually,
3870   // they can differ if any of the corresponding index in a lane is undef
3871   // and the other stays in range.
3872   int LaneSize = NumElts/NumLanes;
3873   for (int i = 0; i < LaneSize; ++i) {
3874     int HighElt = i+LaneSize;
3875     bool HighValid = isUndefOrInRange(Mask[HighElt], LaneSize, NumElts);
3876     bool LowValid = isUndefOrInRange(Mask[i], 0, LaneSize);
3877
3878     if (!HighValid || !LowValid)
3879       return false;
3880     if (Mask[i] < 0 || Mask[HighElt] < 0)
3881       continue;
3882     if (Mask[HighElt]-Mask[i] != LaneSize)
3883       return false;
3884   }
3885
3886   return true;
3887 }
3888
3889 /// getShuffleVPERMILPSImmediate - Return the appropriate immediate to shuffle
3890 /// the specified VECTOR_MASK mask with VPERMILPS* instructions.
3891 static unsigned getShuffleVPERMILPSImmediate(SDNode *N) {
3892   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3893   EVT VT = SVOp->getValueType(0);
3894
3895   int NumElts = VT.getVectorNumElements();
3896   int NumLanes = VT.getSizeInBits()/128;
3897   int LaneSize = NumElts/NumLanes;
3898
3899   // Although the mask is equal for both lanes do it twice to get the cases
3900   // where a mask will match because the same mask element is undef on the
3901   // first half but valid on the second. This would get pathological cases
3902   // such as: shuffle <u, 0, 1, 2, 4, 4, 5, 6>, which is completely valid.
3903   unsigned Mask = 0;
3904   for (int l = 0; l < NumLanes; ++l) {
3905     for (int i = 0; i < LaneSize; ++i) {
3906       int MaskElt = SVOp->getMaskElt(i+(l*LaneSize));
3907       if (MaskElt < 0)
3908         continue;
3909       if (MaskElt >= LaneSize)
3910         MaskElt -= LaneSize;
3911       Mask |= MaskElt << (i*2);
3912     }
3913   }
3914
3915   return Mask;
3916 }
3917
3918 /// getShuffleVPERMILPDImmediate - Return the appropriate immediate to shuffle
3919 /// the specified VECTOR_MASK mask with VPERMILPD* instructions.
3920 static unsigned getShuffleVPERMILPDImmediate(SDNode *N) {
3921   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3922   EVT VT = SVOp->getValueType(0);
3923
3924   int NumElts = VT.getVectorNumElements();
3925   int NumLanes = VT.getSizeInBits()/128;
3926
3927   unsigned Mask = 0;
3928   int LaneSize = NumElts/NumLanes;
3929   for (int l = 0; l < NumLanes; ++l)
3930     for (int i = l*LaneSize; i < LaneSize*(l+1); ++i) {
3931       int MaskElt = SVOp->getMaskElt(i);
3932       if (MaskElt < 0)
3933         continue;
3934       Mask |= (MaskElt-l*LaneSize) << i;
3935     }
3936
3937   return Mask;
3938 }
3939
3940 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3941 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
3942 /// element of vector 2 and the other elements to come from vector 1 in order.
3943 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3944                                bool V2IsSplat = false, bool V2IsUndef = false) {
3945   int NumOps = VT.getVectorNumElements();
3946   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3947     return false;
3948
3949   if (!isUndefOrEqual(Mask[0], 0))
3950     return false;
3951
3952   for (int i = 1; i < NumOps; ++i)
3953     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3954           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3955           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3956       return false;
3957
3958   return true;
3959 }
3960
3961 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3962                            bool V2IsUndef = false) {
3963   SmallVector<int, 8> M;
3964   N->getMask(M);
3965   return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3966 }
3967
3968 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3969 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3970 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
3971 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N,
3972                          const X86Subtarget *Subtarget) {
3973   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
3974     return false;
3975
3976   // The second vector must be undef
3977   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
3978     return false;
3979
3980   EVT VT = N->getValueType(0);
3981   unsigned NumElems = VT.getVectorNumElements();
3982
3983   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
3984       (VT.getSizeInBits() == 256 && NumElems != 8))
3985     return false;
3986
3987   // "i+1" is the value the indexed mask element must have
3988   for (unsigned i = 0; i < NumElems; i += 2)
3989     if (!isUndefOrEqual(N->getMaskElt(i), i+1) ||
3990         !isUndefOrEqual(N->getMaskElt(i+1), i+1))
3991       return false;
3992
3993   return true;
3994 }
3995
3996 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3997 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3998 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
3999 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N,
4000                          const X86Subtarget *Subtarget) {
4001   if (!Subtarget->hasSSE3() && !Subtarget->hasAVX())
4002     return false;
4003
4004   // The second vector must be undef
4005   if (N->getOperand(1).getOpcode() != ISD::UNDEF)
4006     return false;
4007
4008   EVT VT = N->getValueType(0);
4009   unsigned NumElems = VT.getVectorNumElements();
4010
4011   if ((VT.getSizeInBits() == 128 && NumElems != 4) ||
4012       (VT.getSizeInBits() == 256 && NumElems != 8))
4013     return false;
4014
4015   // "i" is the value the indexed mask element must have
4016   for (unsigned i = 0; i < NumElems; i += 2)
4017     if (!isUndefOrEqual(N->getMaskElt(i), i) ||
4018         !isUndefOrEqual(N->getMaskElt(i+1), i))
4019       return false;
4020
4021   return true;
4022 }
4023
4024 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4025 /// specifies a shuffle of elements that is suitable for input to 256-bit
4026 /// version of MOVDDUP.
4027 static bool isMOVDDUPYMask(ShuffleVectorSDNode *N,
4028                            const X86Subtarget *Subtarget) {
4029   EVT VT = N->getValueType(0);
4030   int NumElts = VT.getVectorNumElements();
4031   bool V2IsUndef = N->getOperand(1).getOpcode() == ISD::UNDEF;
4032
4033   if (!Subtarget->hasAVX() || VT.getSizeInBits() != 256 ||
4034       !V2IsUndef || NumElts != 4)
4035     return false;
4036
4037   for (int i = 0; i != NumElts/2; ++i)
4038     if (!isUndefOrEqual(N->getMaskElt(i), 0))
4039       return false;
4040   for (int i = NumElts/2; i != NumElts; ++i)
4041     if (!isUndefOrEqual(N->getMaskElt(i), NumElts/2))
4042       return false;
4043   return true;
4044 }
4045
4046 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4047 /// specifies a shuffle of elements that is suitable for input to 128-bit
4048 /// version of MOVDDUP.
4049 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
4050   EVT VT = N->getValueType(0);
4051
4052   if (VT.getSizeInBits() != 128)
4053     return false;
4054
4055   int e = VT.getVectorNumElements() / 2;
4056   for (int i = 0; i < e; ++i)
4057     if (!isUndefOrEqual(N->getMaskElt(i), i))
4058       return false;
4059   for (int i = 0; i < e; ++i)
4060     if (!isUndefOrEqual(N->getMaskElt(e+i), i))
4061       return false;
4062   return true;
4063 }
4064
4065 /// isVEXTRACTF128Index - Return true if the specified
4066 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4067 /// suitable for input to VEXTRACTF128.
4068 bool X86::isVEXTRACTF128Index(SDNode *N) {
4069   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4070     return false;
4071
4072   // The index should be aligned on a 128-bit boundary.
4073   uint64_t Index =
4074     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4075
4076   unsigned VL = N->getValueType(0).getVectorNumElements();
4077   unsigned VBits = N->getValueType(0).getSizeInBits();
4078   unsigned ElSize = VBits / VL;
4079   bool Result = (Index * ElSize) % 128 == 0;
4080
4081   return Result;
4082 }
4083
4084 /// isVINSERTF128Index - Return true if the specified INSERT_SUBVECTOR
4085 /// operand specifies a subvector insert that is suitable for input to
4086 /// VINSERTF128.
4087 bool X86::isVINSERTF128Index(SDNode *N) {
4088   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4089     return false;
4090
4091   // The index should be aligned on a 128-bit boundary.
4092   uint64_t Index =
4093     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4094
4095   unsigned VL = N->getValueType(0).getVectorNumElements();
4096   unsigned VBits = N->getValueType(0).getSizeInBits();
4097   unsigned ElSize = VBits / VL;
4098   bool Result = (Index * ElSize) % 128 == 0;
4099
4100   return Result;
4101 }
4102
4103 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4104 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4105 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
4106   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4107   int NumOperands = SVOp->getValueType(0).getVectorNumElements();
4108
4109   unsigned Shift = (NumOperands == 4) ? 2 : 1;
4110   unsigned Mask = 0;
4111   for (int i = 0; i < NumOperands; ++i) {
4112     int Val = SVOp->getMaskElt(NumOperands-i-1);
4113     if (Val < 0) Val = 0;
4114     if (Val >= NumOperands) Val -= NumOperands;
4115     Mask |= Val;
4116     if (i != NumOperands - 1)
4117       Mask <<= Shift;
4118   }
4119   return Mask;
4120 }
4121
4122 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4123 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4124 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
4125   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4126   unsigned Mask = 0;
4127   // 8 nodes, but we only care about the last 4.
4128   for (unsigned i = 7; i >= 4; --i) {
4129     int Val = SVOp->getMaskElt(i);
4130     if (Val >= 0)
4131       Mask |= (Val - 4);
4132     if (i != 4)
4133       Mask <<= 2;
4134   }
4135   return Mask;
4136 }
4137
4138 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4139 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4140 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
4141   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4142   unsigned Mask = 0;
4143   // 8 nodes, but we only care about the first 4.
4144   for (int i = 3; i >= 0; --i) {
4145     int Val = SVOp->getMaskElt(i);
4146     if (Val >= 0)
4147       Mask |= Val;
4148     if (i != 0)
4149       Mask <<= 2;
4150   }
4151   return Mask;
4152 }
4153
4154 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4155 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4156 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
4157   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
4158   EVT VVT = N->getValueType(0);
4159   unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
4160   int Val = 0;
4161
4162   unsigned i, e;
4163   for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
4164     Val = SVOp->getMaskElt(i);
4165     if (Val >= 0)
4166       break;
4167   }
4168   assert(Val - i > 0 && "PALIGNR imm should be positive");
4169   return (Val - i) * EltSize;
4170 }
4171
4172 /// getExtractVEXTRACTF128Immediate - Return the appropriate immediate
4173 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4174 /// instructions.
4175 unsigned X86::getExtractVEXTRACTF128Immediate(SDNode *N) {
4176   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4177     llvm_unreachable("Illegal extract subvector for VEXTRACTF128");
4178
4179   uint64_t Index =
4180     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4181
4182   EVT VecVT = N->getOperand(0).getValueType();
4183   EVT ElVT = VecVT.getVectorElementType();
4184
4185   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4186   return Index / NumElemsPerChunk;
4187 }
4188
4189 /// getInsertVINSERTF128Immediate - Return the appropriate immediate
4190 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4191 /// instructions.
4192 unsigned X86::getInsertVINSERTF128Immediate(SDNode *N) {
4193   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4194     llvm_unreachable("Illegal insert subvector for VINSERTF128");
4195
4196   uint64_t Index =
4197     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4198
4199   EVT VecVT = N->getValueType(0);
4200   EVT ElVT = VecVT.getVectorElementType();
4201
4202   unsigned NumElemsPerChunk = 128 / ElVT.getSizeInBits();
4203   return Index / NumElemsPerChunk;
4204 }
4205
4206 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4207 /// constant +0.0.
4208 bool X86::isZeroNode(SDValue Elt) {
4209   return ((isa<ConstantSDNode>(Elt) &&
4210            cast<ConstantSDNode>(Elt)->isNullValue()) ||
4211           (isa<ConstantFPSDNode>(Elt) &&
4212            cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
4213 }
4214
4215 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4216 /// their permute mask.
4217 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4218                                     SelectionDAG &DAG) {
4219   EVT VT = SVOp->getValueType(0);
4220   unsigned NumElems = VT.getVectorNumElements();
4221   SmallVector<int, 8> MaskVec;
4222
4223   for (unsigned i = 0; i != NumElems; ++i) {
4224     int idx = SVOp->getMaskElt(i);
4225     if (idx < 0)
4226       MaskVec.push_back(idx);
4227     else if (idx < (int)NumElems)
4228       MaskVec.push_back(idx + NumElems);
4229     else
4230       MaskVec.push_back(idx - NumElems);
4231   }
4232   return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
4233                               SVOp->getOperand(0), &MaskVec[0]);
4234 }
4235
4236 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4237 /// the two vector operands have swapped position.
4238 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
4239   unsigned NumElems = VT.getVectorNumElements();
4240   for (unsigned i = 0; i != NumElems; ++i) {
4241     int idx = Mask[i];
4242     if (idx < 0)
4243       continue;
4244     else if (idx < (int)NumElems)
4245       Mask[i] = idx + NumElems;
4246     else
4247       Mask[i] = idx - NumElems;
4248   }
4249 }
4250
4251 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4252 /// match movhlps. The lower half elements should come from upper half of
4253 /// V1 (and in order), and the upper half elements should come from the upper
4254 /// half of V2 (and in order).
4255 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
4256   EVT VT = Op->getValueType(0);
4257   if (VT.getSizeInBits() != 128)
4258     return false;
4259   if (VT.getVectorNumElements() != 4)
4260     return false;
4261   for (unsigned i = 0, e = 2; i != e; ++i)
4262     if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
4263       return false;
4264   for (unsigned i = 2; i != 4; ++i)
4265     if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
4266       return false;
4267   return true;
4268 }
4269
4270 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4271 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4272 /// required.
4273 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
4274   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4275     return false;
4276   N = N->getOperand(0).getNode();
4277   if (!ISD::isNON_EXTLoad(N))
4278     return false;
4279   if (LD)
4280     *LD = cast<LoadSDNode>(N);
4281   return true;
4282 }
4283
4284 // Test whether the given value is a vector value which will be legalized
4285 // into a load.
4286 static bool WillBeConstantPoolLoad(SDNode *N) {
4287   if (N->getOpcode() != ISD::BUILD_VECTOR)
4288     return false;
4289
4290   // Check for any non-constant elements.
4291   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4292     switch (N->getOperand(i).getNode()->getOpcode()) {
4293     case ISD::UNDEF:
4294     case ISD::ConstantFP:
4295     case ISD::Constant:
4296       break;
4297     default:
4298       return false;
4299     }
4300
4301   // Vectors of all-zeros and all-ones are materialized with special
4302   // instructions rather than being loaded.
4303   return !ISD::isBuildVectorAllZeros(N) &&
4304          !ISD::isBuildVectorAllOnes(N);
4305 }
4306
4307 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4308 /// match movlp{s|d}. The lower half elements should come from lower half of
4309 /// V1 (and in order), and the upper half elements should come from the upper
4310 /// half of V2 (and in order). And since V1 will become the source of the
4311 /// MOVLP, it must be either a vector load or a scalar load to vector.
4312 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4313                                ShuffleVectorSDNode *Op) {
4314   EVT VT = Op->getValueType(0);
4315   if (VT.getSizeInBits() != 128)
4316     return false;
4317
4318   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4319     return false;
4320   // Is V2 is a vector load, don't do this transformation. We will try to use
4321   // load folding shufps op.
4322   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4323     return false;
4324
4325   unsigned NumElems = VT.getVectorNumElements();
4326
4327   if (NumElems != 2 && NumElems != 4)
4328     return false;
4329   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4330     if (!isUndefOrEqual(Op->getMaskElt(i), i))
4331       return false;
4332   for (unsigned i = NumElems/2; i != NumElems; ++i)
4333     if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
4334       return false;
4335   return true;
4336 }
4337
4338 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4339 /// all the same.
4340 static bool isSplatVector(SDNode *N) {
4341   if (N->getOpcode() != ISD::BUILD_VECTOR)
4342     return false;
4343
4344   SDValue SplatValue = N->getOperand(0);
4345   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4346     if (N->getOperand(i) != SplatValue)
4347       return false;
4348   return true;
4349 }
4350
4351 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4352 /// to an zero vector.
4353 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4354 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4355   SDValue V1 = N->getOperand(0);
4356   SDValue V2 = N->getOperand(1);
4357   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4358   for (unsigned i = 0; i != NumElems; ++i) {
4359     int Idx = N->getMaskElt(i);
4360     if (Idx >= (int)NumElems) {
4361       unsigned Opc = V2.getOpcode();
4362       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4363         continue;
4364       if (Opc != ISD::BUILD_VECTOR ||
4365           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4366         return false;
4367     } else if (Idx >= 0) {
4368       unsigned Opc = V1.getOpcode();
4369       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4370         continue;
4371       if (Opc != ISD::BUILD_VECTOR ||
4372           !X86::isZeroNode(V1.getOperand(Idx)))
4373         return false;
4374     }
4375   }
4376   return true;
4377 }
4378
4379 /// getZeroVector - Returns a vector of specified type with all zero elements.
4380 ///
4381 static SDValue getZeroVector(EVT VT, bool HasXMMInt, SelectionDAG &DAG,
4382                              DebugLoc dl) {
4383   assert(VT.isVector() && "Expected a vector type");
4384
4385   // Always build SSE zero vectors as <4 x i32> bitcasted
4386   // to their dest type. This ensures they get CSE'd.
4387   SDValue Vec;
4388   if (VT.getSizeInBits() == 128) {  // SSE
4389     if (HasXMMInt) {  // SSE2
4390       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4391       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4392     } else { // SSE1
4393       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4394       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4395     }
4396   } else if (VT.getSizeInBits() == 256) { // AVX
4397     // 256-bit logic and arithmetic instructions in AVX are
4398     // all floating-point, no support for integer ops. Default
4399     // to emitting fp zeroed vectors then.
4400     SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4401     SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4402     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
4403   }
4404   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4405 }
4406
4407 /// getOnesVector - Returns a vector of specified type with all bits set.
4408 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4409 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4410 /// Then bitcast to their original type, ensuring they get CSE'd.
4411 static SDValue getOnesVector(EVT VT, bool HasAVX2, SelectionDAG &DAG,
4412                              DebugLoc dl) {
4413   assert(VT.isVector() && "Expected a vector type");
4414   assert((VT.is128BitVector() || VT.is256BitVector())
4415          && "Expected a 128-bit or 256-bit vector type");
4416
4417   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4418   SDValue Vec;
4419   if (VT.getSizeInBits() == 256) {
4420     if (HasAVX2) { // AVX2
4421       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4422       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops, 8);
4423     } else { // AVX
4424       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4425       SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, MVT::v8i32),
4426                                 Vec, DAG.getConstant(0, MVT::i32), DAG, dl);
4427       Vec = Insert128BitVector(InsV, Vec,
4428                     DAG.getConstant(4 /* NumElems/2 */, MVT::i32), DAG, dl);
4429     }
4430   } else {
4431     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4432   }
4433
4434   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4435 }
4436
4437 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4438 /// that point to V2 points to its first element.
4439 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4440   EVT VT = SVOp->getValueType(0);
4441   unsigned NumElems = VT.getVectorNumElements();
4442
4443   bool Changed = false;
4444   SmallVector<int, 8> MaskVec;
4445   SVOp->getMask(MaskVec);
4446
4447   for (unsigned i = 0; i != NumElems; ++i) {
4448     if (MaskVec[i] > (int)NumElems) {
4449       MaskVec[i] = NumElems;
4450       Changed = true;
4451     }
4452   }
4453   if (Changed)
4454     return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
4455                                 SVOp->getOperand(1), &MaskVec[0]);
4456   return SDValue(SVOp, 0);
4457 }
4458
4459 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4460 /// operation of specified width.
4461 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4462                        SDValue V2) {
4463   unsigned NumElems = VT.getVectorNumElements();
4464   SmallVector<int, 8> Mask;
4465   Mask.push_back(NumElems);
4466   for (unsigned i = 1; i != NumElems; ++i)
4467     Mask.push_back(i);
4468   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4469 }
4470
4471 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4472 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4473                           SDValue V2) {
4474   unsigned NumElems = VT.getVectorNumElements();
4475   SmallVector<int, 8> Mask;
4476   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4477     Mask.push_back(i);
4478     Mask.push_back(i + NumElems);
4479   }
4480   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4481 }
4482
4483 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4484 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
4485                           SDValue V2) {
4486   unsigned NumElems = VT.getVectorNumElements();
4487   unsigned Half = NumElems/2;
4488   SmallVector<int, 8> Mask;
4489   for (unsigned i = 0; i != Half; ++i) {
4490     Mask.push_back(i + Half);
4491     Mask.push_back(i + NumElems + Half);
4492   }
4493   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4494 }
4495
4496 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4497 // a generic shuffle instruction because the target has no such instructions.
4498 // Generate shuffles which repeat i16 and i8 several times until they can be
4499 // represented by v4f32 and then be manipulated by target suported shuffles.
4500 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4501   EVT VT = V.getValueType();
4502   int NumElems = VT.getVectorNumElements();
4503   DebugLoc dl = V.getDebugLoc();
4504
4505   while (NumElems > 4) {
4506     if (EltNo < NumElems/2) {
4507       V = getUnpackl(DAG, dl, VT, V, V);
4508     } else {
4509       V = getUnpackh(DAG, dl, VT, V, V);
4510       EltNo -= NumElems/2;
4511     }
4512     NumElems >>= 1;
4513   }
4514   return V;
4515 }
4516
4517 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
4518 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
4519   EVT VT = V.getValueType();
4520   DebugLoc dl = V.getDebugLoc();
4521   assert((VT.getSizeInBits() == 128 || VT.getSizeInBits() == 256)
4522          && "Vector size not supported");
4523
4524   if (VT.getSizeInBits() == 128) {
4525     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
4526     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
4527     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
4528                              &SplatMask[0]);
4529   } else {
4530     // To use VPERMILPS to splat scalars, the second half of indicies must
4531     // refer to the higher part, which is a duplication of the lower one,
4532     // because VPERMILPS can only handle in-lane permutations.
4533     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
4534                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
4535
4536     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
4537     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
4538                              &SplatMask[0]);
4539   }
4540
4541   return DAG.getNode(ISD::BITCAST, dl, VT, V);
4542 }
4543
4544 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
4545 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
4546   EVT SrcVT = SV->getValueType(0);
4547   SDValue V1 = SV->getOperand(0);
4548   DebugLoc dl = SV->getDebugLoc();
4549
4550   int EltNo = SV->getSplatIndex();
4551   int NumElems = SrcVT.getVectorNumElements();
4552   unsigned Size = SrcVT.getSizeInBits();
4553
4554   assert(((Size == 128 && NumElems > 4) || Size == 256) &&
4555           "Unknown how to promote splat for type");
4556
4557   // Extract the 128-bit part containing the splat element and update
4558   // the splat element index when it refers to the higher register.
4559   if (Size == 256) {
4560     unsigned Idx = (EltNo > NumElems/2) ? NumElems/2 : 0;
4561     V1 = Extract128BitVector(V1, DAG.getConstant(Idx, MVT::i32), DAG, dl);
4562     if (Idx > 0)
4563       EltNo -= NumElems/2;
4564   }
4565
4566   // All i16 and i8 vector types can't be used directly by a generic shuffle
4567   // instruction because the target has no such instruction. Generate shuffles
4568   // which repeat i16 and i8 several times until they fit in i32, and then can
4569   // be manipulated by target suported shuffles.
4570   EVT EltVT = SrcVT.getVectorElementType();
4571   if (EltVT == MVT::i8 || EltVT == MVT::i16)
4572     V1 = PromoteSplati8i16(V1, DAG, EltNo);
4573
4574   // Recreate the 256-bit vector and place the same 128-bit vector
4575   // into the low and high part. This is necessary because we want
4576   // to use VPERM* to shuffle the vectors
4577   if (Size == 256) {
4578     SDValue InsV = Insert128BitVector(DAG.getUNDEF(SrcVT), V1,
4579                          DAG.getConstant(0, MVT::i32), DAG, dl);
4580     V1 = Insert128BitVector(InsV, V1,
4581                DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
4582   }
4583
4584   return getLegalSplat(DAG, V1, EltNo);
4585 }
4586
4587 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4588 /// vector of zero or undef vector.  This produces a shuffle where the low
4589 /// element of V2 is swizzled into the zero/undef vector, landing at element
4590 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4591 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4592                                            bool isZero, bool HasXMMInt,
4593                                            SelectionDAG &DAG) {
4594   EVT VT = V2.getValueType();
4595   SDValue V1 = isZero
4596     ? getZeroVector(VT, HasXMMInt, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
4597   unsigned NumElems = VT.getVectorNumElements();
4598   SmallVector<int, 16> MaskVec;
4599   for (unsigned i = 0; i != NumElems; ++i)
4600     // If this is the insertion idx, put the low elt of V2 here.
4601     MaskVec.push_back(i == Idx ? NumElems : i);
4602   return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
4603 }
4604
4605 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4606 /// element of the result of the vector shuffle.
4607 static SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
4608                                    unsigned Depth) {
4609   if (Depth == 6)
4610     return SDValue();  // Limit search depth.
4611
4612   SDValue V = SDValue(N, 0);
4613   EVT VT = V.getValueType();
4614   unsigned Opcode = V.getOpcode();
4615
4616   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4617   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4618     Index = SV->getMaskElt(Index);
4619
4620     if (Index < 0)
4621       return DAG.getUNDEF(VT.getVectorElementType());
4622
4623     int NumElems = VT.getVectorNumElements();
4624     SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
4625     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
4626   }
4627
4628   // Recurse into target specific vector shuffles to find scalars.
4629   if (isTargetShuffle(Opcode)) {
4630     int NumElems = VT.getVectorNumElements();
4631     SmallVector<unsigned, 16> ShuffleMask;
4632     SDValue ImmN;
4633
4634     switch(Opcode) {
4635     case X86ISD::SHUFPS:
4636     case X86ISD::SHUFPD:
4637       ImmN = N->getOperand(N->getNumOperands()-1);
4638       DecodeSHUFPSMask(NumElems,
4639                        cast<ConstantSDNode>(ImmN)->getZExtValue(),
4640                        ShuffleMask);
4641       break;
4642     case X86ISD::PUNPCKHBW:
4643     case X86ISD::PUNPCKHWD:
4644     case X86ISD::PUNPCKHDQ:
4645     case X86ISD::PUNPCKHQDQ:
4646     case X86ISD::VPUNPCKHBWY:
4647     case X86ISD::VPUNPCKHWDY:
4648     case X86ISD::VPUNPCKHDQY:
4649     case X86ISD::VPUNPCKHQDQY:
4650       DecodePUNPCKHMask(NumElems, ShuffleMask);
4651       break;
4652     case X86ISD::UNPCKHPS:
4653     case X86ISD::UNPCKHPD:
4654     case X86ISD::VUNPCKHPSY:
4655     case X86ISD::VUNPCKHPDY:
4656       DecodeUNPCKHPMask(NumElems, ShuffleMask);
4657       break;
4658     case X86ISD::PUNPCKLBW:
4659     case X86ISD::PUNPCKLWD:
4660     case X86ISD::PUNPCKLDQ:
4661     case X86ISD::PUNPCKLQDQ:
4662     case X86ISD::VPUNPCKLBWY:
4663     case X86ISD::VPUNPCKLWDY:
4664     case X86ISD::VPUNPCKLDQY:
4665     case X86ISD::VPUNPCKLQDQY:
4666       DecodePUNPCKLMask(VT, ShuffleMask);
4667       break;
4668     case X86ISD::UNPCKLPS:
4669     case X86ISD::UNPCKLPD:
4670     case X86ISD::VUNPCKLPSY:
4671     case X86ISD::VUNPCKLPDY:
4672       DecodeUNPCKLPMask(VT, ShuffleMask);
4673       break;
4674     case X86ISD::MOVHLPS:
4675       DecodeMOVHLPSMask(NumElems, ShuffleMask);
4676       break;
4677     case X86ISD::MOVLHPS:
4678       DecodeMOVLHPSMask(NumElems, ShuffleMask);
4679       break;
4680     case X86ISD::PSHUFD:
4681       ImmN = N->getOperand(N->getNumOperands()-1);
4682       DecodePSHUFMask(NumElems,
4683                       cast<ConstantSDNode>(ImmN)->getZExtValue(),
4684                       ShuffleMask);
4685       break;
4686     case X86ISD::PSHUFHW:
4687       ImmN = N->getOperand(N->getNumOperands()-1);
4688       DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4689                         ShuffleMask);
4690       break;
4691     case X86ISD::PSHUFLW:
4692       ImmN = N->getOperand(N->getNumOperands()-1);
4693       DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
4694                         ShuffleMask);
4695       break;
4696     case X86ISD::MOVSS:
4697     case X86ISD::MOVSD: {
4698       // The index 0 always comes from the first element of the second source,
4699       // this is why MOVSS and MOVSD are used in the first place. The other
4700       // elements come from the other positions of the first source vector.
4701       unsigned OpNum = (Index == 0) ? 1 : 0;
4702       return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
4703                                  Depth+1);
4704     }
4705     case X86ISD::VPERMILPS:
4706       ImmN = N->getOperand(N->getNumOperands()-1);
4707       DecodeVPERMILPSMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4708                         ShuffleMask);
4709       break;
4710     case X86ISD::VPERMILPSY:
4711       ImmN = N->getOperand(N->getNumOperands()-1);
4712       DecodeVPERMILPSMask(8, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4713                         ShuffleMask);
4714       break;
4715     case X86ISD::VPERMILPD:
4716       ImmN = N->getOperand(N->getNumOperands()-1);
4717       DecodeVPERMILPDMask(2, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4718                         ShuffleMask);
4719       break;
4720     case X86ISD::VPERMILPDY:
4721       ImmN = N->getOperand(N->getNumOperands()-1);
4722       DecodeVPERMILPDMask(4, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4723                         ShuffleMask);
4724       break;
4725     case X86ISD::VPERM2F128:
4726       ImmN = N->getOperand(N->getNumOperands()-1);
4727       DecodeVPERM2F128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(),
4728                            ShuffleMask);
4729       break;
4730     case X86ISD::MOVDDUP:
4731     case X86ISD::MOVLHPD:
4732     case X86ISD::MOVLPD:
4733     case X86ISD::MOVLPS:
4734     case X86ISD::MOVSHDUP:
4735     case X86ISD::MOVSLDUP:
4736     case X86ISD::PALIGN:
4737       return SDValue(); // Not yet implemented.
4738     default:
4739       assert(0 && "unknown target shuffle node");
4740       return SDValue();
4741     }
4742
4743     Index = ShuffleMask[Index];
4744     if (Index < 0)
4745       return DAG.getUNDEF(VT.getVectorElementType());
4746
4747     SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
4748     return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
4749                                Depth+1);
4750   }
4751
4752   // Actual nodes that may contain scalar elements
4753   if (Opcode == ISD::BITCAST) {
4754     V = V.getOperand(0);
4755     EVT SrcVT = V.getValueType();
4756     unsigned NumElems = VT.getVectorNumElements();
4757
4758     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4759       return SDValue();
4760   }
4761
4762   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4763     return (Index == 0) ? V.getOperand(0)
4764                           : DAG.getUNDEF(VT.getVectorElementType());
4765
4766   if (V.getOpcode() == ISD::BUILD_VECTOR)
4767     return V.getOperand(Index);
4768
4769   return SDValue();
4770 }
4771
4772 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
4773 /// shuffle operation which come from a consecutively from a zero. The
4774 /// search can start in two different directions, from left or right.
4775 static
4776 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
4777                                   bool ZerosFromLeft, SelectionDAG &DAG) {
4778   int i = 0;
4779
4780   while (i < NumElems) {
4781     unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
4782     SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
4783     if (!(Elt.getNode() &&
4784          (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
4785       break;
4786     ++i;
4787   }
4788
4789   return i;
4790 }
4791
4792 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
4793 /// MaskE correspond consecutively to elements from one of the vector operands,
4794 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
4795 static
4796 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
4797                               int OpIdx, int NumElems, unsigned &OpNum) {
4798   bool SeenV1 = false;
4799   bool SeenV2 = false;
4800
4801   for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
4802     int Idx = SVOp->getMaskElt(i);
4803     // Ignore undef indicies
4804     if (Idx < 0)
4805       continue;
4806
4807     if (Idx < NumElems)
4808       SeenV1 = true;
4809     else
4810       SeenV2 = true;
4811
4812     // Only accept consecutive elements from the same vector
4813     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
4814       return false;
4815   }
4816
4817   OpNum = SeenV1 ? 0 : 1;
4818   return true;
4819 }
4820
4821 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
4822 /// logical left shift of a vector.
4823 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4824                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4825   unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
4826   unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
4827               false /* check zeros from right */, DAG);
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-1, // Mask End Index
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(SVOp, NumElems,
4860               true /* check zeros from left */, DAG);
4861   unsigned OpSrc;
4862
4863   if (!NumZeros)
4864     return false;
4865
4866   // Considering the elements in the mask that are not consecutive zeros,
4867   // check if they consecutively come from only one of the source vectors.
4868   //
4869   //                           0    { A, B, X, X } = V2
4870   //                          / \    /  /
4871   //   vector_shuffle V1, V2 <X, X, 4, 5>
4872   //
4873   if (!isShuffleMaskConsecutive(SVOp,
4874             NumZeros,     // Mask Start Index
4875             NumElems-1,   // Mask End Index
4876             0,            // Where to start looking in the src vector
4877             NumElems,     // Number of elements in vector
4878             OpSrc))       // Which source operand ?
4879     return false;
4880
4881   isLeft = true;
4882   ShAmt = NumZeros;
4883   ShVal = SVOp->getOperand(OpSrc);
4884   return true;
4885 }
4886
4887 /// isVectorShift - Returns true if the shuffle can be implemented as a
4888 /// logical left or right shift of a vector.
4889 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
4890                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
4891   // Although the logic below support any bitwidth size, there are no
4892   // shift instructions which handle more than 128-bit vectors.
4893   if (SVOp->getValueType(0).getSizeInBits() > 128)
4894     return false;
4895
4896   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
4897       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
4898     return true;
4899
4900   return false;
4901 }
4902
4903 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4904 ///
4905 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4906                                        unsigned NumNonZero, unsigned NumZero,
4907                                        SelectionDAG &DAG,
4908                                        const TargetLowering &TLI) {
4909   if (NumNonZero > 8)
4910     return SDValue();
4911
4912   DebugLoc dl = Op.getDebugLoc();
4913   SDValue V(0, 0);
4914   bool First = true;
4915   for (unsigned i = 0; i < 16; ++i) {
4916     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4917     if (ThisIsNonZero && First) {
4918       if (NumZero)
4919         V = getZeroVector(MVT::v8i16, true, DAG, dl);
4920       else
4921         V = DAG.getUNDEF(MVT::v8i16);
4922       First = false;
4923     }
4924
4925     if ((i & 1) != 0) {
4926       SDValue ThisElt(0, 0), LastElt(0, 0);
4927       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4928       if (LastIsNonZero) {
4929         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4930                               MVT::i16, Op.getOperand(i-1));
4931       }
4932       if (ThisIsNonZero) {
4933         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4934         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4935                               ThisElt, DAG.getConstant(8, MVT::i8));
4936         if (LastIsNonZero)
4937           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4938       } else
4939         ThisElt = LastElt;
4940
4941       if (ThisElt.getNode())
4942         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4943                         DAG.getIntPtrConstant(i/2));
4944     }
4945   }
4946
4947   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
4948 }
4949
4950 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4951 ///
4952 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4953                                      unsigned NumNonZero, unsigned NumZero,
4954                                      SelectionDAG &DAG,
4955                                      const TargetLowering &TLI) {
4956   if (NumNonZero > 4)
4957     return SDValue();
4958
4959   DebugLoc dl = Op.getDebugLoc();
4960   SDValue V(0, 0);
4961   bool First = true;
4962   for (unsigned i = 0; i < 8; ++i) {
4963     bool isNonZero = (NonZeros & (1 << i)) != 0;
4964     if (isNonZero) {
4965       if (First) {
4966         if (NumZero)
4967           V = getZeroVector(MVT::v8i16, true, DAG, dl);
4968         else
4969           V = DAG.getUNDEF(MVT::v8i16);
4970         First = false;
4971       }
4972       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4973                       MVT::v8i16, V, Op.getOperand(i),
4974                       DAG.getIntPtrConstant(i));
4975     }
4976   }
4977
4978   return V;
4979 }
4980
4981 /// getVShift - Return a vector logical shift node.
4982 ///
4983 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4984                          unsigned NumBits, SelectionDAG &DAG,
4985                          const TargetLowering &TLI, DebugLoc dl) {
4986   assert(VT.getSizeInBits() == 128 && "Unknown type for VShift");
4987   EVT ShVT = MVT::v2i64;
4988   unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4989   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
4990   return DAG.getNode(ISD::BITCAST, dl, VT,
4991                      DAG.getNode(Opc, dl, ShVT, SrcOp,
4992                              DAG.getConstant(NumBits,
4993                                   TLI.getShiftAmountTy(SrcOp.getValueType()))));
4994 }
4995
4996 SDValue
4997 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4998                                           SelectionDAG &DAG) const {
4999
5000   // Check if the scalar load can be widened into a vector load. And if
5001   // the address is "base + cst" see if the cst can be "absorbed" into
5002   // the shuffle mask.
5003   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5004     SDValue Ptr = LD->getBasePtr();
5005     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5006       return SDValue();
5007     EVT PVT = LD->getValueType(0);
5008     if (PVT != MVT::i32 && PVT != MVT::f32)
5009       return SDValue();
5010
5011     int FI = -1;
5012     int64_t Offset = 0;
5013     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5014       FI = FINode->getIndex();
5015       Offset = 0;
5016     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5017                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5018       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5019       Offset = Ptr.getConstantOperandVal(1);
5020       Ptr = Ptr.getOperand(0);
5021     } else {
5022       return SDValue();
5023     }
5024
5025     // FIXME: 256-bit vector instructions don't require a strict alignment,
5026     // improve this code to support it better.
5027     unsigned RequiredAlign = VT.getSizeInBits()/8;
5028     SDValue Chain = LD->getChain();
5029     // Make sure the stack object alignment is at least 16 or 32.
5030     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5031     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5032       if (MFI->isFixedObjectIndex(FI)) {
5033         // Can't change the alignment. FIXME: It's possible to compute
5034         // the exact stack offset and reference FI + adjust offset instead.
5035         // If someone *really* cares about this. That's the way to implement it.
5036         return SDValue();
5037       } else {
5038         MFI->setObjectAlignment(FI, RequiredAlign);
5039       }
5040     }
5041
5042     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5043     // Ptr + (Offset & ~15).
5044     if (Offset < 0)
5045       return SDValue();
5046     if ((Offset % RequiredAlign) & 3)
5047       return SDValue();
5048     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5049     if (StartOffset)
5050       Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
5051                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5052
5053     int EltNo = (Offset - StartOffset) >> 2;
5054     int NumElems = VT.getVectorNumElements();
5055
5056     EVT CanonVT = VT.getSizeInBits() == 128 ? MVT::v4i32 : MVT::v8i32;
5057     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5058     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5059                              LD->getPointerInfo().getWithOffset(StartOffset),
5060                              false, false, false, 0);
5061
5062     // Canonicalize it to a v4i32 or v8i32 shuffle.
5063     SmallVector<int, 8> Mask;
5064     for (int i = 0; i < NumElems; ++i)
5065       Mask.push_back(EltNo);
5066
5067     V1 = DAG.getNode(ISD::BITCAST, dl, CanonVT, V1);
5068     return DAG.getNode(ISD::BITCAST, dl, NVT,
5069                        DAG.getVectorShuffle(CanonVT, dl, V1,
5070                                             DAG.getUNDEF(CanonVT),&Mask[0]));
5071   }
5072
5073   return SDValue();
5074 }
5075
5076 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5077 /// vector of type 'VT', see if the elements can be replaced by a single large
5078 /// load which has the same value as a build_vector whose operands are 'elts'.
5079 ///
5080 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5081 ///
5082 /// FIXME: we'd also like to handle the case where the last elements are zero
5083 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5084 /// There's even a handy isZeroNode for that purpose.
5085 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5086                                         DebugLoc &DL, SelectionDAG &DAG) {
5087   EVT EltVT = VT.getVectorElementType();
5088   unsigned NumElems = Elts.size();
5089
5090   LoadSDNode *LDBase = NULL;
5091   unsigned LastLoadedElt = -1U;
5092
5093   // For each element in the initializer, see if we've found a load or an undef.
5094   // If we don't find an initial load element, or later load elements are
5095   // non-consecutive, bail out.
5096   for (unsigned i = 0; i < NumElems; ++i) {
5097     SDValue Elt = Elts[i];
5098
5099     if (!Elt.getNode() ||
5100         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5101       return SDValue();
5102     if (!LDBase) {
5103       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5104         return SDValue();
5105       LDBase = cast<LoadSDNode>(Elt.getNode());
5106       LastLoadedElt = i;
5107       continue;
5108     }
5109     if (Elt.getOpcode() == ISD::UNDEF)
5110       continue;
5111
5112     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5113     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5114       return SDValue();
5115     LastLoadedElt = i;
5116   }
5117
5118   // If we have found an entire vector of loads and undefs, then return a large
5119   // load of the entire vector width starting at the base pointer.  If we found
5120   // consecutive loads for the low half, generate a vzext_load node.
5121   if (LastLoadedElt == NumElems - 1) {
5122     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5123       return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5124                          LDBase->getPointerInfo(),
5125                          LDBase->isVolatile(), LDBase->isNonTemporal(),
5126                          LDBase->isInvariant(), 0);
5127     return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5128                        LDBase->getPointerInfo(),
5129                        LDBase->isVolatile(), LDBase->isNonTemporal(),
5130                        LDBase->isInvariant(), LDBase->getAlignment());
5131   } else if (NumElems == 4 && LastLoadedElt == 1 &&
5132              DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5133     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5134     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5135     SDValue ResNode =
5136         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, 2, MVT::i64,
5137                                 LDBase->getPointerInfo(),
5138                                 LDBase->getAlignment(),
5139                                 false/*isVolatile*/, true/*ReadMem*/,
5140                                 false/*WriteMem*/);
5141     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5142   }
5143   return SDValue();
5144 }
5145
5146 /// isVectorBroadcast - Check if the node chain is suitable to be xformed to
5147 /// a vbroadcast node. We support two patterns:
5148 /// 1. A splat BUILD_VECTOR which uses a single scalar load.
5149 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5150 /// a scalar load.
5151 /// The scalar load node is returned when a pattern is found,
5152 /// or SDValue() otherwise.
5153 static SDValue isVectorBroadcast(SDValue &Op, bool hasAVX2) {
5154   EVT VT = Op.getValueType();
5155   SDValue V = Op;
5156
5157   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5158     V = V.getOperand(0);
5159
5160   //A suspected load to be broadcasted.
5161   SDValue Ld;
5162
5163   switch (V.getOpcode()) {
5164     default:
5165       // Unknown pattern found.
5166       return SDValue();
5167
5168     case ISD::BUILD_VECTOR: {
5169       // The BUILD_VECTOR node must be a splat.
5170       if (!isSplatVector(V.getNode()))
5171         return SDValue();
5172
5173       Ld = V.getOperand(0);
5174
5175       // The suspected load node has several users. Make sure that all
5176       // of its users are from the BUILD_VECTOR node.
5177       if (!Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5178         return SDValue();
5179       break;
5180     }
5181
5182     case ISD::VECTOR_SHUFFLE: {
5183       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5184
5185       // Shuffles must have a splat mask where the first element is
5186       // broadcasted.
5187       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5188         return SDValue();
5189
5190       SDValue Sc = Op.getOperand(0);
5191       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR)
5192         return SDValue();
5193
5194       Ld = Sc.getOperand(0);
5195
5196       // The scalar_to_vector node and the suspected
5197       // load node must have exactly one user.
5198       if (!Sc.hasOneUse() || !Ld.hasOneUse())
5199         return SDValue();
5200       break;
5201     }
5202   }
5203
5204   // The scalar source must be a normal load.
5205   if (!ISD::isNormalLoad(Ld.getNode()))
5206     return SDValue();
5207
5208   bool Is256 = VT.getSizeInBits() == 256;
5209   bool Is128 = VT.getSizeInBits() == 128;
5210   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5211
5212   if (hasAVX2) {
5213     // VBroadcast to YMM
5214     if (Is256 && (ScalarSize == 8  || ScalarSize == 16 ||
5215                   ScalarSize == 32 || ScalarSize == 64 ))
5216       return Ld;
5217
5218     // VBroadcast to XMM
5219     if (Is128 && (ScalarSize ==  8 || ScalarSize == 32 ||
5220                   ScalarSize == 16 || ScalarSize == 64 ))
5221       return Ld;
5222   }
5223
5224   // VBroadcast to YMM
5225   if (Is256 && (ScalarSize == 32 || ScalarSize == 64))
5226     return Ld;
5227
5228   // VBroadcast to XMM
5229   if (Is128 && (ScalarSize == 32))
5230     return Ld;
5231
5232
5233   // Unsupported broadcast.
5234   return SDValue();
5235 }
5236
5237 SDValue
5238 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5239   DebugLoc dl = Op.getDebugLoc();
5240
5241   EVT VT = Op.getValueType();
5242   EVT ExtVT = VT.getVectorElementType();
5243   unsigned NumElems = Op.getNumOperands();
5244
5245   // Vectors containing all zeros can be matched by pxor and xorps later
5246   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5247     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5248     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5249     if (Op.getValueType() == MVT::v4i32 ||
5250         Op.getValueType() == MVT::v8i32)
5251       return Op;
5252
5253     return getZeroVector(Op.getValueType(), Subtarget->hasXMMInt(), DAG, dl);
5254   }
5255
5256   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5257   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5258   // vpcmpeqd on 256-bit vectors.
5259   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5260     if (Op.getValueType() == MVT::v4i32 ||
5261         (Op.getValueType() == MVT::v8i32 && Subtarget->hasAVX2()))
5262       return Op;
5263
5264     return getOnesVector(Op.getValueType(), Subtarget->hasAVX2(), DAG, dl);
5265   }
5266
5267   SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
5268   if (Subtarget->hasAVX() && LD.getNode())
5269       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
5270
5271   unsigned EVTBits = ExtVT.getSizeInBits();
5272
5273   unsigned NumZero  = 0;
5274   unsigned NumNonZero = 0;
5275   unsigned NonZeros = 0;
5276   bool IsAllConstants = true;
5277   SmallSet<SDValue, 8> Values;
5278   for (unsigned i = 0; i < NumElems; ++i) {
5279     SDValue Elt = Op.getOperand(i);
5280     if (Elt.getOpcode() == ISD::UNDEF)
5281       continue;
5282     Values.insert(Elt);
5283     if (Elt.getOpcode() != ISD::Constant &&
5284         Elt.getOpcode() != ISD::ConstantFP)
5285       IsAllConstants = false;
5286     if (X86::isZeroNode(Elt))
5287       NumZero++;
5288     else {
5289       NonZeros |= (1 << i);
5290       NumNonZero++;
5291     }
5292   }
5293
5294   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5295   if (NumNonZero == 0)
5296     return DAG.getUNDEF(VT);
5297
5298   // Special case for single non-zero, non-undef, element.
5299   if (NumNonZero == 1) {
5300     unsigned Idx = CountTrailingZeros_32(NonZeros);
5301     SDValue Item = Op.getOperand(Idx);
5302
5303     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5304     // the value are obviously zero, truncate the value to i32 and do the
5305     // insertion that way.  Only do this if the value is non-constant or if the
5306     // value is a constant being inserted into element 0.  It is cheaper to do
5307     // a constant pool load than it is to do a movd + shuffle.
5308     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5309         (!IsAllConstants || Idx == 0)) {
5310       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5311         // Handle SSE only.
5312         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5313         EVT VecVT = MVT::v4i32;
5314         unsigned VecElts = 4;
5315
5316         // Truncate the value (which may itself be a constant) to i32, and
5317         // convert it to a vector with movd (S2V+shuffle to zero extend).
5318         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5319         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5320         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5321                                            Subtarget->hasXMMInt(), DAG);
5322
5323         // Now we have our 32-bit value zero extended in the low element of
5324         // a vector.  If Idx != 0, swizzle it into place.
5325         if (Idx != 0) {
5326           SmallVector<int, 4> Mask;
5327           Mask.push_back(Idx);
5328           for (unsigned i = 1; i != VecElts; ++i)
5329             Mask.push_back(i);
5330           Item = DAG.getVectorShuffle(VecVT, dl, Item,
5331                                       DAG.getUNDEF(Item.getValueType()),
5332                                       &Mask[0]);
5333         }
5334         return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
5335       }
5336     }
5337
5338     // If we have a constant or non-constant insertion into the low element of
5339     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5340     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5341     // depending on what the source datatype is.
5342     if (Idx == 0) {
5343       if (NumZero == 0) {
5344         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5345       } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5346           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5347         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5348         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5349         return getShuffleVectorZeroOrUndef(Item, 0, true,Subtarget->hasXMMInt(),
5350                                            DAG);
5351       } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5352         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5353         assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
5354         EVT MiddleVT = MVT::v4i32;
5355         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
5356         Item = getShuffleVectorZeroOrUndef(Item, 0, true,
5357                                            Subtarget->hasXMMInt(), DAG);
5358         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
5359       }
5360     }
5361
5362     // Is it a vector logical left shift?
5363     if (NumElems == 2 && Idx == 1 &&
5364         X86::isZeroNode(Op.getOperand(0)) &&
5365         !X86::isZeroNode(Op.getOperand(1))) {
5366       unsigned NumBits = VT.getSizeInBits();
5367       return getVShift(true, VT,
5368                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5369                                    VT, Op.getOperand(1)),
5370                        NumBits/2, DAG, *this, dl);
5371     }
5372
5373     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5374       return SDValue();
5375
5376     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5377     // is a non-constant being inserted into an element other than the low one,
5378     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5379     // movd/movss) to move this into the low element, then shuffle it into
5380     // place.
5381     if (EVTBits == 32) {
5382       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5383
5384       // Turn it into a shuffle of zero and zero-extended scalar to vector.
5385       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
5386                                          Subtarget->hasXMMInt(), DAG);
5387       SmallVector<int, 8> MaskVec;
5388       for (unsigned i = 0; i < NumElems; i++)
5389         MaskVec.push_back(i == Idx ? 0 : 1);
5390       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
5391     }
5392   }
5393
5394   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5395   if (Values.size() == 1) {
5396     if (EVTBits == 32) {
5397       // Instead of a shuffle like this:
5398       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5399       // Check if it's possible to issue this instead.
5400       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5401       unsigned Idx = CountTrailingZeros_32(NonZeros);
5402       SDValue Item = Op.getOperand(Idx);
5403       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5404         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5405     }
5406     return SDValue();
5407   }
5408
5409   // A vector full of immediates; various special cases are already
5410   // handled, so this is best done with a single constant-pool load.
5411   if (IsAllConstants)
5412     return SDValue();
5413
5414   // For AVX-length vectors, build the individual 128-bit pieces and use
5415   // shuffles to put them in place.
5416   if (VT.getSizeInBits() == 256 && !ISD::isBuildVectorAllZeros(Op.getNode())) {
5417     SmallVector<SDValue, 32> V;
5418     for (unsigned i = 0; i < NumElems; ++i)
5419       V.push_back(Op.getOperand(i));
5420
5421     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5422
5423     // Build both the lower and upper subvector.
5424     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[0], NumElems/2);
5425     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT, &V[NumElems / 2],
5426                                 NumElems/2);
5427
5428     // Recreate the wider vector with the lower and upper part.
5429     SDValue Vec = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), Lower,
5430                                 DAG.getConstant(0, MVT::i32), DAG, dl);
5431     return Insert128BitVector(Vec, Upper, DAG.getConstant(NumElems/2, MVT::i32),
5432                               DAG, dl);
5433   }
5434
5435   // Let legalizer expand 2-wide build_vectors.
5436   if (EVTBits == 64) {
5437     if (NumNonZero == 1) {
5438       // One half is zero or undef.
5439       unsigned Idx = CountTrailingZeros_32(NonZeros);
5440       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
5441                                  Op.getOperand(Idx));
5442       return getShuffleVectorZeroOrUndef(V2, Idx, true,
5443                                          Subtarget->hasXMMInt(), DAG);
5444     }
5445     return SDValue();
5446   }
5447
5448   // If element VT is < 32 bits, convert it to inserts into a zero vector.
5449   if (EVTBits == 8 && NumElems == 16) {
5450     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
5451                                         *this);
5452     if (V.getNode()) return V;
5453   }
5454
5455   if (EVTBits == 16 && NumElems == 8) {
5456     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
5457                                       *this);
5458     if (V.getNode()) return V;
5459   }
5460
5461   // If element VT is == 32 bits, turn it into a number of shuffles.
5462   SmallVector<SDValue, 8> V;
5463   V.resize(NumElems);
5464   if (NumElems == 4 && NumZero > 0) {
5465     for (unsigned i = 0; i < 4; ++i) {
5466       bool isZero = !(NonZeros & (1 << i));
5467       if (isZero)
5468         V[i] = getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
5469       else
5470         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5471     }
5472
5473     for (unsigned i = 0; i < 2; ++i) {
5474       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
5475         default: break;
5476         case 0:
5477           V[i] = V[i*2];  // Must be a zero vector.
5478           break;
5479         case 1:
5480           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
5481           break;
5482         case 2:
5483           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
5484           break;
5485         case 3:
5486           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
5487           break;
5488       }
5489     }
5490
5491     SmallVector<int, 8> MaskVec;
5492     bool Reverse = (NonZeros & 0x3) == 2;
5493     for (unsigned i = 0; i < 2; ++i)
5494       MaskVec.push_back(Reverse ? 1-i : i);
5495     Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
5496     for (unsigned i = 0; i < 2; ++i)
5497       MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
5498     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
5499   }
5500
5501   if (Values.size() > 1 && VT.getSizeInBits() == 128) {
5502     // Check for a build vector of consecutive loads.
5503     for (unsigned i = 0; i < NumElems; ++i)
5504       V[i] = Op.getOperand(i);
5505
5506     // Check for elements which are consecutive loads.
5507     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
5508     if (LD.getNode())
5509       return LD;
5510
5511     // For SSE 4.1, use insertps to put the high elements into the low element.
5512     if (getSubtarget()->hasSSE41() || getSubtarget()->hasAVX()) {
5513       SDValue Result;
5514       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
5515         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
5516       else
5517         Result = DAG.getUNDEF(VT);
5518
5519       for (unsigned i = 1; i < NumElems; ++i) {
5520         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
5521         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
5522                              Op.getOperand(i), DAG.getIntPtrConstant(i));
5523       }
5524       return Result;
5525     }
5526
5527     // Otherwise, expand into a number of unpckl*, start by extending each of
5528     // our (non-undef) elements to the full vector width with the element in the
5529     // bottom slot of the vector (which generates no code for SSE).
5530     for (unsigned i = 0; i < NumElems; ++i) {
5531       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
5532         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
5533       else
5534         V[i] = DAG.getUNDEF(VT);
5535     }
5536
5537     // Next, we iteratively mix elements, e.g. for v4f32:
5538     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
5539     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
5540     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
5541     unsigned EltStride = NumElems >> 1;
5542     while (EltStride != 0) {
5543       for (unsigned i = 0; i < EltStride; ++i) {
5544         // If V[i+EltStride] is undef and this is the first round of mixing,
5545         // then it is safe to just drop this shuffle: V[i] is already in the
5546         // right place, the one element (since it's the first round) being
5547         // inserted as undef can be dropped.  This isn't safe for successive
5548         // rounds because they will permute elements within both vectors.
5549         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
5550             EltStride == NumElems/2)
5551           continue;
5552
5553         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
5554       }
5555       EltStride >>= 1;
5556     }
5557     return V[0];
5558   }
5559   return SDValue();
5560 }
5561
5562 // LowerMMXCONCAT_VECTORS - We support concatenate two MMX registers and place
5563 // them in a MMX register.  This is better than doing a stack convert.
5564 static SDValue LowerMMXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5565   DebugLoc dl = Op.getDebugLoc();
5566   EVT ResVT = Op.getValueType();
5567
5568   assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
5569          ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
5570   int Mask[2];
5571   SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
5572   SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5573   InVec = Op.getOperand(1);
5574   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5575     unsigned NumElts = ResVT.getVectorNumElements();
5576     VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5577     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
5578                        InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
5579   } else {
5580     InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
5581     SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
5582     Mask[0] = 0; Mask[1] = 2;
5583     VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
5584   }
5585   return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
5586 }
5587
5588 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
5589 // to create 256-bit vectors from two other 128-bit ones.
5590 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5591   DebugLoc dl = Op.getDebugLoc();
5592   EVT ResVT = Op.getValueType();
5593
5594   assert(ResVT.getSizeInBits() == 256 && "Value type must be 256-bit wide");
5595
5596   SDValue V1 = Op.getOperand(0);
5597   SDValue V2 = Op.getOperand(1);
5598   unsigned NumElems = ResVT.getVectorNumElements();
5599
5600   SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, ResVT), V1,
5601                                  DAG.getConstant(0, MVT::i32), DAG, dl);
5602   return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
5603                             DAG, dl);
5604 }
5605
5606 SDValue
5607 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
5608   EVT ResVT = Op.getValueType();
5609
5610   assert(Op.getNumOperands() == 2);
5611   assert((ResVT.getSizeInBits() == 128 || ResVT.getSizeInBits() == 256) &&
5612          "Unsupported CONCAT_VECTORS for value type");
5613
5614   // We support concatenate two MMX registers and place them in a MMX register.
5615   // This is better than doing a stack convert.
5616   if (ResVT.is128BitVector())
5617     return LowerMMXCONCAT_VECTORS(Op, DAG);
5618
5619   // 256-bit AVX can use the vinsertf128 instruction to create 256-bit vectors
5620   // from two other 128-bit ones.
5621   return LowerAVXCONCAT_VECTORS(Op, DAG);
5622 }
5623
5624 // v8i16 shuffles - Prefer shuffles in the following order:
5625 // 1. [all]   pshuflw, pshufhw, optional move
5626 // 2. [ssse3] 1 x pshufb
5627 // 3. [ssse3] 2 x pshufb + 1 x por
5628 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
5629 SDValue
5630 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
5631                                             SelectionDAG &DAG) const {
5632   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5633   SDValue V1 = SVOp->getOperand(0);
5634   SDValue V2 = SVOp->getOperand(1);
5635   DebugLoc dl = SVOp->getDebugLoc();
5636   SmallVector<int, 8> MaskVals;
5637
5638   // Determine if more than 1 of the words in each of the low and high quadwords
5639   // of the result come from the same quadword of one of the two inputs.  Undef
5640   // mask values count as coming from any quadword, for better codegen.
5641   unsigned LoQuad[] = { 0, 0, 0, 0 };
5642   unsigned HiQuad[] = { 0, 0, 0, 0 };
5643   BitVector InputQuads(4);
5644   for (unsigned i = 0; i < 8; ++i) {
5645     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
5646     int EltIdx = SVOp->getMaskElt(i);
5647     MaskVals.push_back(EltIdx);
5648     if (EltIdx < 0) {
5649       ++Quad[0];
5650       ++Quad[1];
5651       ++Quad[2];
5652       ++Quad[3];
5653       continue;
5654     }
5655     ++Quad[EltIdx / 4];
5656     InputQuads.set(EltIdx / 4);
5657   }
5658
5659   int BestLoQuad = -1;
5660   unsigned MaxQuad = 1;
5661   for (unsigned i = 0; i < 4; ++i) {
5662     if (LoQuad[i] > MaxQuad) {
5663       BestLoQuad = i;
5664       MaxQuad = LoQuad[i];
5665     }
5666   }
5667
5668   int BestHiQuad = -1;
5669   MaxQuad = 1;
5670   for (unsigned i = 0; i < 4; ++i) {
5671     if (HiQuad[i] > MaxQuad) {
5672       BestHiQuad = i;
5673       MaxQuad = HiQuad[i];
5674     }
5675   }
5676
5677   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
5678   // of the two input vectors, shuffle them into one input vector so only a
5679   // single pshufb instruction is necessary. If There are more than 2 input
5680   // quads, disable the next transformation since it does not help SSSE3.
5681   bool V1Used = InputQuads[0] || InputQuads[1];
5682   bool V2Used = InputQuads[2] || InputQuads[3];
5683   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5684     if (InputQuads.count() == 2 && V1Used && V2Used) {
5685       BestLoQuad = InputQuads.find_first();
5686       BestHiQuad = InputQuads.find_next(BestLoQuad);
5687     }
5688     if (InputQuads.count() > 2) {
5689       BestLoQuad = -1;
5690       BestHiQuad = -1;
5691     }
5692   }
5693
5694   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
5695   // the shuffle mask.  If a quad is scored as -1, that means that it contains
5696   // words from all 4 input quadwords.
5697   SDValue NewV;
5698   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
5699     SmallVector<int, 8> MaskV;
5700     MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
5701     MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
5702     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
5703                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
5704                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
5705     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
5706
5707     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
5708     // source words for the shuffle, to aid later transformations.
5709     bool AllWordsInNewV = true;
5710     bool InOrder[2] = { true, true };
5711     for (unsigned i = 0; i != 8; ++i) {
5712       int idx = MaskVals[i];
5713       if (idx != (int)i)
5714         InOrder[i/4] = false;
5715       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
5716         continue;
5717       AllWordsInNewV = false;
5718       break;
5719     }
5720
5721     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
5722     if (AllWordsInNewV) {
5723       for (int i = 0; i != 8; ++i) {
5724         int idx = MaskVals[i];
5725         if (idx < 0)
5726           continue;
5727         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
5728         if ((idx != i) && idx < 4)
5729           pshufhw = false;
5730         if ((idx != i) && idx > 3)
5731           pshuflw = false;
5732       }
5733       V1 = NewV;
5734       V2Used = false;
5735       BestLoQuad = 0;
5736       BestHiQuad = 1;
5737     }
5738
5739     // If we've eliminated the use of V2, and the new mask is a pshuflw or
5740     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
5741     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
5742       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
5743       unsigned TargetMask = 0;
5744       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
5745                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
5746       TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
5747                              X86::getShufflePSHUFLWImmediate(NewV.getNode());
5748       V1 = NewV.getOperand(0);
5749       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
5750     }
5751   }
5752
5753   // If we have SSSE3, and all words of the result are from 1 input vector,
5754   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
5755   // is present, fall back to case 4.
5756   if (Subtarget->hasSSSE3() || Subtarget->hasAVX()) {
5757     SmallVector<SDValue,16> pshufbMask;
5758
5759     // If we have elements from both input vectors, set the high bit of the
5760     // shuffle mask element to zero out elements that come from V2 in the V1
5761     // mask, and elements that come from V1 in the V2 mask, so that the two
5762     // results can be OR'd together.
5763     bool TwoInputs = V1Used && V2Used;
5764     for (unsigned i = 0; i != 8; ++i) {
5765       int EltIdx = MaskVals[i] * 2;
5766       if (TwoInputs && (EltIdx >= 16)) {
5767         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5768         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5769         continue;
5770       }
5771       pshufbMask.push_back(DAG.getConstant(EltIdx,   MVT::i8));
5772       pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
5773     }
5774     V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
5775     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
5776                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5777                                  MVT::v16i8, &pshufbMask[0], 16));
5778     if (!TwoInputs)
5779       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5780
5781     // Calculate the shuffle mask for the second input, shuffle it, and
5782     // OR it with the first shuffled input.
5783     pshufbMask.clear();
5784     for (unsigned i = 0; i != 8; ++i) {
5785       int EltIdx = MaskVals[i] * 2;
5786       if (EltIdx < 16) {
5787         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5788         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5789         continue;
5790       }
5791       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5792       pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
5793     }
5794     V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
5795     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5796                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5797                                  MVT::v16i8, &pshufbMask[0], 16));
5798     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5799     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5800   }
5801
5802   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
5803   // and update MaskVals with new element order.
5804   BitVector InOrder(8);
5805   if (BestLoQuad >= 0) {
5806     SmallVector<int, 8> MaskV;
5807     for (int i = 0; i != 4; ++i) {
5808       int idx = MaskVals[i];
5809       if (idx < 0) {
5810         MaskV.push_back(-1);
5811         InOrder.set(i);
5812       } else if ((idx / 4) == BestLoQuad) {
5813         MaskV.push_back(idx & 3);
5814         InOrder.set(i);
5815       } else {
5816         MaskV.push_back(-1);
5817       }
5818     }
5819     for (unsigned i = 4; i != 8; ++i)
5820       MaskV.push_back(i);
5821     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5822                                 &MaskV[0]);
5823
5824     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5825         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5826       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
5827                                NewV.getOperand(0),
5828                                X86::getShufflePSHUFLWImmediate(NewV.getNode()),
5829                                DAG);
5830   }
5831
5832   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
5833   // and update MaskVals with the new element order.
5834   if (BestHiQuad >= 0) {
5835     SmallVector<int, 8> MaskV;
5836     for (unsigned i = 0; i != 4; ++i)
5837       MaskV.push_back(i);
5838     for (unsigned i = 4; i != 8; ++i) {
5839       int idx = MaskVals[i];
5840       if (idx < 0) {
5841         MaskV.push_back(-1);
5842         InOrder.set(i);
5843       } else if ((idx / 4) == BestHiQuad) {
5844         MaskV.push_back((idx & 3) + 4);
5845         InOrder.set(i);
5846       } else {
5847         MaskV.push_back(-1);
5848       }
5849     }
5850     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
5851                                 &MaskV[0]);
5852
5853     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE &&
5854         (Subtarget->hasSSSE3() || Subtarget->hasAVX()))
5855       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
5856                               NewV.getOperand(0),
5857                               X86::getShufflePSHUFHWImmediate(NewV.getNode()),
5858                               DAG);
5859   }
5860
5861   // In case BestHi & BestLo were both -1, which means each quadword has a word
5862   // from each of the four input quadwords, calculate the InOrder bitvector now
5863   // before falling through to the insert/extract cleanup.
5864   if (BestLoQuad == -1 && BestHiQuad == -1) {
5865     NewV = V1;
5866     for (int i = 0; i != 8; ++i)
5867       if (MaskVals[i] < 0 || MaskVals[i] == i)
5868         InOrder.set(i);
5869   }
5870
5871   // The other elements are put in the right place using pextrw and pinsrw.
5872   for (unsigned i = 0; i != 8; ++i) {
5873     if (InOrder[i])
5874       continue;
5875     int EltIdx = MaskVals[i];
5876     if (EltIdx < 0)
5877       continue;
5878     SDValue ExtOp = (EltIdx < 8)
5879     ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
5880                   DAG.getIntPtrConstant(EltIdx))
5881     : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
5882                   DAG.getIntPtrConstant(EltIdx - 8));
5883     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
5884                        DAG.getIntPtrConstant(i));
5885   }
5886   return NewV;
5887 }
5888
5889 // v16i8 shuffles - Prefer shuffles in the following order:
5890 // 1. [ssse3] 1 x pshufb
5891 // 2. [ssse3] 2 x pshufb + 1 x por
5892 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
5893 static
5894 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
5895                                  SelectionDAG &DAG,
5896                                  const X86TargetLowering &TLI) {
5897   SDValue V1 = SVOp->getOperand(0);
5898   SDValue V2 = SVOp->getOperand(1);
5899   DebugLoc dl = SVOp->getDebugLoc();
5900   SmallVector<int, 16> MaskVals;
5901   SVOp->getMask(MaskVals);
5902
5903   // If we have SSSE3, case 1 is generated when all result bytes come from
5904   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
5905   // present, fall back to case 3.
5906   // FIXME: kill V2Only once shuffles are canonizalized by getNode.
5907   bool V1Only = true;
5908   bool V2Only = true;
5909   for (unsigned i = 0; i < 16; ++i) {
5910     int EltIdx = MaskVals[i];
5911     if (EltIdx < 0)
5912       continue;
5913     if (EltIdx < 16)
5914       V2Only = false;
5915     else
5916       V1Only = false;
5917   }
5918
5919   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
5920   if (TLI.getSubtarget()->hasSSSE3() || TLI.getSubtarget()->hasAVX()) {
5921     SmallVector<SDValue,16> pshufbMask;
5922
5923     // If all result elements are from one input vector, then only translate
5924     // undef mask values to 0x80 (zero out result) in the pshufb mask.
5925     //
5926     // Otherwise, we have elements from both input vectors, and must zero out
5927     // elements that come from V2 in the first mask, and V1 in the second mask
5928     // so that we can OR them together.
5929     bool TwoInputs = !(V1Only || V2Only);
5930     for (unsigned i = 0; i != 16; ++i) {
5931       int EltIdx = MaskVals[i];
5932       if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
5933         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5934         continue;
5935       }
5936       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
5937     }
5938     // If all the elements are from V2, assign it to V1 and return after
5939     // building the first pshufb.
5940     if (V2Only)
5941       V1 = V2;
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 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 != 16; ++i) {
5952       int EltIdx = MaskVals[i];
5953       if (EltIdx < 16) {
5954         pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
5955         continue;
5956       }
5957       pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
5958     }
5959     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
5960                      DAG.getNode(ISD::BUILD_VECTOR, dl,
5961                                  MVT::v16i8, &pshufbMask[0], 16));
5962     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
5963   }
5964
5965   // No SSSE3 - Calculate in place words and then fix all out of place words
5966   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
5967   // the 16 different words that comprise the two doublequadword input vectors.
5968   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
5969   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
5970   SDValue NewV = V2Only ? V2 : V1;
5971   for (int i = 0; i != 8; ++i) {
5972     int Elt0 = MaskVals[i*2];
5973     int Elt1 = MaskVals[i*2+1];
5974
5975     // This word of the result is all undef, skip it.
5976     if (Elt0 < 0 && Elt1 < 0)
5977       continue;
5978
5979     // This word of the result is already in the correct place, skip it.
5980     if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
5981       continue;
5982     if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
5983       continue;
5984
5985     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
5986     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
5987     SDValue InsElt;
5988
5989     // If Elt0 and Elt1 are defined, are consecutive, and can be load
5990     // using a single extract together, load it and store it.
5991     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
5992       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
5993                            DAG.getIntPtrConstant(Elt1 / 2));
5994       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
5995                         DAG.getIntPtrConstant(i));
5996       continue;
5997     }
5998
5999     // If Elt1 is defined, extract it from the appropriate source.  If the
6000     // source byte is not also odd, shift the extracted word left 8 bits
6001     // otherwise clear the bottom 8 bits if we need to do an or.
6002     if (Elt1 >= 0) {
6003       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6004                            DAG.getIntPtrConstant(Elt1 / 2));
6005       if ((Elt1 & 1) == 0)
6006         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6007                              DAG.getConstant(8,
6008                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6009       else if (Elt0 >= 0)
6010         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6011                              DAG.getConstant(0xFF00, MVT::i16));
6012     }
6013     // If Elt0 is defined, extract it from the appropriate source.  If the
6014     // source byte is not also even, shift the extracted word right 8 bits. If
6015     // Elt1 was also defined, OR the extracted values together before
6016     // inserting them in the result.
6017     if (Elt0 >= 0) {
6018       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6019                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6020       if ((Elt0 & 1) != 0)
6021         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6022                               DAG.getConstant(8,
6023                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6024       else if (Elt1 >= 0)
6025         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6026                              DAG.getConstant(0x00FF, MVT::i16));
6027       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6028                          : InsElt0;
6029     }
6030     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6031                        DAG.getIntPtrConstant(i));
6032   }
6033   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6034 }
6035
6036 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6037 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6038 /// done when every pair / quad of shuffle mask elements point to elements in
6039 /// the right sequence. e.g.
6040 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6041 static
6042 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6043                                  SelectionDAG &DAG, DebugLoc dl) {
6044   EVT VT = SVOp->getValueType(0);
6045   SDValue V1 = SVOp->getOperand(0);
6046   SDValue V2 = SVOp->getOperand(1);
6047   unsigned NumElems = VT.getVectorNumElements();
6048   unsigned NewWidth = (NumElems == 4) ? 2 : 4;
6049   EVT NewVT;
6050   switch (VT.getSimpleVT().SimpleTy) {
6051   default: assert(false && "Unexpected!");
6052   case MVT::v4f32: NewVT = MVT::v2f64; break;
6053   case MVT::v4i32: NewVT = MVT::v2i64; break;
6054   case MVT::v8i16: NewVT = MVT::v4i32; break;
6055   case MVT::v16i8: NewVT = MVT::v4i32; break;
6056   }
6057
6058   int Scale = NumElems / NewWidth;
6059   SmallVector<int, 8> MaskVec;
6060   for (unsigned i = 0; i < NumElems; i += Scale) {
6061     int StartIdx = -1;
6062     for (int j = 0; j < Scale; ++j) {
6063       int EltIdx = SVOp->getMaskElt(i+j);
6064       if (EltIdx < 0)
6065         continue;
6066       if (StartIdx == -1)
6067         StartIdx = EltIdx - (EltIdx % Scale);
6068       if (EltIdx != StartIdx + j)
6069         return SDValue();
6070     }
6071     if (StartIdx == -1)
6072       MaskVec.push_back(-1);
6073     else
6074       MaskVec.push_back(StartIdx / Scale);
6075   }
6076
6077   V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
6078   V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
6079   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
6080 }
6081
6082 /// getVZextMovL - Return a zero-extending vector move low node.
6083 ///
6084 static SDValue getVZextMovL(EVT VT, EVT OpVT,
6085                             SDValue SrcOp, SelectionDAG &DAG,
6086                             const X86Subtarget *Subtarget, DebugLoc dl) {
6087   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
6088     LoadSDNode *LD = NULL;
6089     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
6090       LD = dyn_cast<LoadSDNode>(SrcOp);
6091     if (!LD) {
6092       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
6093       // instead.
6094       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
6095       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
6096           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6097           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
6098           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
6099         // PR2108
6100         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
6101         return DAG.getNode(ISD::BITCAST, dl, VT,
6102                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6103                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6104                                                    OpVT,
6105                                                    SrcOp.getOperand(0)
6106                                                           .getOperand(0))));
6107       }
6108     }
6109   }
6110
6111   return DAG.getNode(ISD::BITCAST, dl, VT,
6112                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
6113                                  DAG.getNode(ISD::BITCAST, dl,
6114                                              OpVT, SrcOp)));
6115 }
6116
6117 /// areShuffleHalvesWithinDisjointLanes - Check whether each half of a vector
6118 /// shuffle node referes to only one lane in the sources.
6119 static bool areShuffleHalvesWithinDisjointLanes(ShuffleVectorSDNode *SVOp) {
6120   EVT VT = SVOp->getValueType(0);
6121   int NumElems = VT.getVectorNumElements();
6122   int HalfSize = NumElems/2;
6123   SmallVector<int, 16> M;
6124   SVOp->getMask(M);
6125   bool MatchA = false, MatchB = false;
6126
6127   for (int l = 0; l < NumElems*2; l += HalfSize) {
6128     if (isUndefOrInRange(M, 0, HalfSize, l, l+HalfSize)) {
6129       MatchA = true;
6130       break;
6131     }
6132   }
6133
6134   for (int l = 0; l < NumElems*2; l += HalfSize) {
6135     if (isUndefOrInRange(M, HalfSize, HalfSize, l, l+HalfSize)) {
6136       MatchB = true;
6137       break;
6138     }
6139   }
6140
6141   return MatchA && MatchB;
6142 }
6143
6144 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
6145 /// which could not be matched by any known target speficic shuffle
6146 static SDValue
6147 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6148   if (areShuffleHalvesWithinDisjointLanes(SVOp)) {
6149     // If each half of a vector shuffle node referes to only one lane in the
6150     // source vectors, extract each used 128-bit lane and shuffle them using
6151     // 128-bit shuffles. Then, concatenate the results. Otherwise leave
6152     // the work to the legalizer.
6153     DebugLoc dl = SVOp->getDebugLoc();
6154     EVT VT = SVOp->getValueType(0);
6155     int NumElems = VT.getVectorNumElements();
6156     int HalfSize = NumElems/2;
6157
6158     // Extract the reference for each half
6159     int FstVecExtractIdx = 0, SndVecExtractIdx = 0;
6160     int FstVecOpNum = 0, SndVecOpNum = 0;
6161     for (int i = 0; i < HalfSize; ++i) {
6162       int Elt = SVOp->getMaskElt(i);
6163       if (SVOp->getMaskElt(i) < 0)
6164         continue;
6165       FstVecOpNum = Elt/NumElems;
6166       FstVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6167       break;
6168     }
6169     for (int i = HalfSize; i < NumElems; ++i) {
6170       int Elt = SVOp->getMaskElt(i);
6171       if (SVOp->getMaskElt(i) < 0)
6172         continue;
6173       SndVecOpNum = Elt/NumElems;
6174       SndVecExtractIdx = Elt % NumElems < HalfSize ? 0 : HalfSize;
6175       break;
6176     }
6177
6178     // Extract the subvectors
6179     SDValue V1 = Extract128BitVector(SVOp->getOperand(FstVecOpNum),
6180                       DAG.getConstant(FstVecExtractIdx, MVT::i32), DAG, dl);
6181     SDValue V2 = Extract128BitVector(SVOp->getOperand(SndVecOpNum),
6182                       DAG.getConstant(SndVecExtractIdx, MVT::i32), DAG, dl);
6183
6184     // Generate 128-bit shuffles
6185     SmallVector<int, 16> MaskV1, MaskV2;
6186     for (int i = 0; i < HalfSize; ++i) {
6187       int Elt = SVOp->getMaskElt(i);
6188       MaskV1.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6189     }
6190     for (int i = HalfSize; i < NumElems; ++i) {
6191       int Elt = SVOp->getMaskElt(i);
6192       MaskV2.push_back(Elt < 0 ? Elt : Elt % HalfSize);
6193     }
6194
6195     EVT NVT = V1.getValueType();
6196     V1 = DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &MaskV1[0]);
6197     V2 = DAG.getVectorShuffle(NVT, dl, V2, DAG.getUNDEF(NVT), &MaskV2[0]);
6198
6199     // Concatenate the result back
6200     SDValue V = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT), V1,
6201                                    DAG.getConstant(0, MVT::i32), DAG, dl);
6202     return Insert128BitVector(V, V2, DAG.getConstant(NumElems/2, MVT::i32),
6203                               DAG, dl);
6204   }
6205
6206   return SDValue();
6207 }
6208
6209 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
6210 /// 4 elements, and match them with several different shuffle types.
6211 static SDValue
6212 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
6213   SDValue V1 = SVOp->getOperand(0);
6214   SDValue V2 = SVOp->getOperand(1);
6215   DebugLoc dl = SVOp->getDebugLoc();
6216   EVT VT = SVOp->getValueType(0);
6217
6218   assert(VT.getSizeInBits() == 128 && "Unsupported vector size");
6219
6220   SmallVector<std::pair<int, int>, 8> Locs;
6221   Locs.resize(4);
6222   SmallVector<int, 8> Mask1(4U, -1);
6223   SmallVector<int, 8> PermMask;
6224   SVOp->getMask(PermMask);
6225
6226   unsigned NumHi = 0;
6227   unsigned NumLo = 0;
6228   for (unsigned i = 0; i != 4; ++i) {
6229     int Idx = PermMask[i];
6230     if (Idx < 0) {
6231       Locs[i] = std::make_pair(-1, -1);
6232     } else {
6233       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
6234       if (Idx < 4) {
6235         Locs[i] = std::make_pair(0, NumLo);
6236         Mask1[NumLo] = Idx;
6237         NumLo++;
6238       } else {
6239         Locs[i] = std::make_pair(1, NumHi);
6240         if (2+NumHi < 4)
6241           Mask1[2+NumHi] = Idx;
6242         NumHi++;
6243       }
6244     }
6245   }
6246
6247   if (NumLo <= 2 && NumHi <= 2) {
6248     // If no more than two elements come from either vector. This can be
6249     // implemented with two shuffles. First shuffle gather the elements.
6250     // The second shuffle, which takes the first shuffle as both of its
6251     // vector operands, put the elements into the right order.
6252     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6253
6254     SmallVector<int, 8> Mask2(4U, -1);
6255
6256     for (unsigned i = 0; i != 4; ++i) {
6257       if (Locs[i].first == -1)
6258         continue;
6259       else {
6260         unsigned Idx = (i < 2) ? 0 : 4;
6261         Idx += Locs[i].first * 2 + Locs[i].second;
6262         Mask2[i] = Idx;
6263       }
6264     }
6265
6266     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
6267   } else if (NumLo == 3 || NumHi == 3) {
6268     // Otherwise, we must have three elements from one vector, call it X, and
6269     // one element from the other, call it Y.  First, use a shufps to build an
6270     // intermediate vector with the one element from Y and the element from X
6271     // that will be in the same half in the final destination (the indexes don't
6272     // matter). Then, use a shufps to build the final vector, taking the half
6273     // containing the element from Y from the intermediate, and the other half
6274     // from X.
6275     if (NumHi == 3) {
6276       // Normalize it so the 3 elements come from V1.
6277       CommuteVectorShuffleMask(PermMask, VT);
6278       std::swap(V1, V2);
6279     }
6280
6281     // Find the element from V2.
6282     unsigned HiIndex;
6283     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
6284       int Val = PermMask[HiIndex];
6285       if (Val < 0)
6286         continue;
6287       if (Val >= 4)
6288         break;
6289     }
6290
6291     Mask1[0] = PermMask[HiIndex];
6292     Mask1[1] = -1;
6293     Mask1[2] = PermMask[HiIndex^1];
6294     Mask1[3] = -1;
6295     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6296
6297     if (HiIndex >= 2) {
6298       Mask1[0] = PermMask[0];
6299       Mask1[1] = PermMask[1];
6300       Mask1[2] = HiIndex & 1 ? 6 : 4;
6301       Mask1[3] = HiIndex & 1 ? 4 : 6;
6302       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
6303     } else {
6304       Mask1[0] = HiIndex & 1 ? 2 : 0;
6305       Mask1[1] = HiIndex & 1 ? 0 : 2;
6306       Mask1[2] = PermMask[2];
6307       Mask1[3] = PermMask[3];
6308       if (Mask1[2] >= 0)
6309         Mask1[2] += 4;
6310       if (Mask1[3] >= 0)
6311         Mask1[3] += 4;
6312       return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
6313     }
6314   }
6315
6316   // Break it into (shuffle shuffle_hi, shuffle_lo).
6317   Locs.clear();
6318   Locs.resize(4);
6319   SmallVector<int,8> LoMask(4U, -1);
6320   SmallVector<int,8> HiMask(4U, -1);
6321
6322   SmallVector<int,8> *MaskPtr = &LoMask;
6323   unsigned MaskIdx = 0;
6324   unsigned LoIdx = 0;
6325   unsigned HiIdx = 2;
6326   for (unsigned i = 0; i != 4; ++i) {
6327     if (i == 2) {
6328       MaskPtr = &HiMask;
6329       MaskIdx = 1;
6330       LoIdx = 0;
6331       HiIdx = 2;
6332     }
6333     int Idx = PermMask[i];
6334     if (Idx < 0) {
6335       Locs[i] = std::make_pair(-1, -1);
6336     } else if (Idx < 4) {
6337       Locs[i] = std::make_pair(MaskIdx, LoIdx);
6338       (*MaskPtr)[LoIdx] = Idx;
6339       LoIdx++;
6340     } else {
6341       Locs[i] = std::make_pair(MaskIdx, HiIdx);
6342       (*MaskPtr)[HiIdx] = Idx;
6343       HiIdx++;
6344     }
6345   }
6346
6347   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
6348   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
6349   SmallVector<int, 8> MaskOps;
6350   for (unsigned i = 0; i != 4; ++i) {
6351     if (Locs[i].first == -1) {
6352       MaskOps.push_back(-1);
6353     } else {
6354       unsigned Idx = Locs[i].first * 4 + Locs[i].second;
6355       MaskOps.push_back(Idx);
6356     }
6357   }
6358   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
6359 }
6360
6361 static bool MayFoldVectorLoad(SDValue V) {
6362   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6363     V = V.getOperand(0);
6364   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6365     V = V.getOperand(0);
6366   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
6367       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
6368     // BUILD_VECTOR (load), undef
6369     V = V.getOperand(0);
6370   if (MayFoldLoad(V))
6371     return true;
6372   return false;
6373 }
6374
6375 // FIXME: the version above should always be used. Since there's
6376 // a bug where several vector shuffles can't be folded because the
6377 // DAG is not updated during lowering and a node claims to have two
6378 // uses while it only has one, use this version, and let isel match
6379 // another instruction if the load really happens to have more than
6380 // one use. Remove this version after this bug get fixed.
6381 // rdar://8434668, PR8156
6382 static bool RelaxedMayFoldVectorLoad(SDValue V) {
6383   if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
6384     V = V.getOperand(0);
6385   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
6386     V = V.getOperand(0);
6387   if (ISD::isNormalLoad(V.getNode()))
6388     return true;
6389   return false;
6390 }
6391
6392 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
6393 /// a vector extract, and if both can be later optimized into a single load.
6394 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
6395 /// here because otherwise a target specific shuffle node is going to be
6396 /// emitted for this shuffle, and the optimization not done.
6397 /// FIXME: This is probably not the best approach, but fix the problem
6398 /// until the right path is decided.
6399 static
6400 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
6401                                          const TargetLowering &TLI) {
6402   EVT VT = V.getValueType();
6403   ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
6404
6405   // Be sure that the vector shuffle is present in a pattern like this:
6406   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
6407   if (!V.hasOneUse())
6408     return false;
6409
6410   SDNode *N = *V.getNode()->use_begin();
6411   if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6412     return false;
6413
6414   SDValue EltNo = N->getOperand(1);
6415   if (!isa<ConstantSDNode>(EltNo))
6416     return false;
6417
6418   // If the bit convert changed the number of elements, it is unsafe
6419   // to examine the mask.
6420   bool HasShuffleIntoBitcast = false;
6421   if (V.getOpcode() == ISD::BITCAST) {
6422     EVT SrcVT = V.getOperand(0).getValueType();
6423     if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
6424       return false;
6425     V = V.getOperand(0);
6426     HasShuffleIntoBitcast = true;
6427   }
6428
6429   // Select the input vector, guarding against out of range extract vector.
6430   unsigned NumElems = VT.getVectorNumElements();
6431   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6432   int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
6433   V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
6434
6435   // Skip one more bit_convert if necessary
6436   if (V.getOpcode() == ISD::BITCAST)
6437     V = V.getOperand(0);
6438
6439   if (ISD::isNormalLoad(V.getNode())) {
6440     // Is the original load suitable?
6441     LoadSDNode *LN0 = cast<LoadSDNode>(V);
6442
6443     // FIXME: avoid the multi-use bug that is preventing lots of
6444     // of foldings to be detected, this is still wrong of course, but
6445     // give the temporary desired behavior, and if it happens that
6446     // the load has real more uses, during isel it will not fold, and
6447     // will generate poor code.
6448     if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
6449       return false;
6450
6451     if (!HasShuffleIntoBitcast)
6452       return true;
6453
6454     // If there's a bitcast before the shuffle, check if the load type and
6455     // alignment is valid.
6456     unsigned Align = LN0->getAlignment();
6457     unsigned NewAlign =
6458       TLI.getTargetData()->getABITypeAlignment(
6459                                     VT.getTypeForEVT(*DAG.getContext()));
6460
6461     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
6462       return false;
6463   }
6464
6465   return true;
6466 }
6467
6468 static
6469 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
6470   EVT VT = Op.getValueType();
6471
6472   // Canonizalize to v2f64.
6473   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
6474   return DAG.getNode(ISD::BITCAST, dl, VT,
6475                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
6476                                           V1, DAG));
6477 }
6478
6479 static
6480 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
6481                         bool HasXMMInt) {
6482   SDValue V1 = Op.getOperand(0);
6483   SDValue V2 = Op.getOperand(1);
6484   EVT VT = Op.getValueType();
6485
6486   assert(VT != MVT::v2i64 && "unsupported shuffle type");
6487
6488   if (HasXMMInt && VT == MVT::v2f64)
6489     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
6490
6491   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
6492   return DAG.getNode(ISD::BITCAST, dl, VT,
6493                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
6494                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
6495                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
6496 }
6497
6498 static
6499 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
6500   SDValue V1 = Op.getOperand(0);
6501   SDValue V2 = Op.getOperand(1);
6502   EVT VT = Op.getValueType();
6503
6504   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
6505          "unsupported shuffle type");
6506
6507   if (V2.getOpcode() == ISD::UNDEF)
6508     V2 = V1;
6509
6510   // v4i32 or v4f32
6511   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
6512 }
6513
6514 static inline unsigned getSHUFPOpcode(EVT VT) {
6515   switch(VT.getSimpleVT().SimpleTy) {
6516   case MVT::v8i32: // Use fp unit for int unpack.
6517   case MVT::v8f32:
6518   case MVT::v4i32: // Use fp unit for int unpack.
6519   case MVT::v4f32: return X86ISD::SHUFPS;
6520   case MVT::v4i64: // Use fp unit for int unpack.
6521   case MVT::v4f64:
6522   case MVT::v2i64: // Use fp unit for int unpack.
6523   case MVT::v2f64: return X86ISD::SHUFPD;
6524   default:
6525     llvm_unreachable("Unknown type for shufp*");
6526   }
6527   return 0;
6528 }
6529
6530 static
6531 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasXMMInt) {
6532   SDValue V1 = Op.getOperand(0);
6533   SDValue V2 = Op.getOperand(1);
6534   EVT VT = Op.getValueType();
6535   unsigned NumElems = VT.getVectorNumElements();
6536
6537   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
6538   // operand of these instructions is only memory, so check if there's a
6539   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
6540   // same masks.
6541   bool CanFoldLoad = false;
6542
6543   // Trivial case, when V2 comes from a load.
6544   if (MayFoldVectorLoad(V2))
6545     CanFoldLoad = true;
6546
6547   // When V1 is a load, it can be folded later into a store in isel, example:
6548   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
6549   //    turns into:
6550   //  (MOVLPSmr addr:$src1, VR128:$src2)
6551   // So, recognize this potential and also use MOVLPS or MOVLPD
6552   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
6553     CanFoldLoad = true;
6554
6555   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6556   if (CanFoldLoad) {
6557     if (HasXMMInt && NumElems == 2)
6558       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
6559
6560     if (NumElems == 4)
6561       // If we don't care about the second element, procede to use movss.
6562       if (SVOp->getMaskElt(1) != -1)
6563         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
6564   }
6565
6566   // movl and movlp will both match v2i64, but v2i64 is never matched by
6567   // movl earlier because we make it strict to avoid messing with the movlp load
6568   // folding logic (see the code above getMOVLP call). Match it here then,
6569   // this is horrible, but will stay like this until we move all shuffle
6570   // matching to x86 specific nodes. Note that for the 1st condition all
6571   // types are matched with movsd.
6572   if (HasXMMInt) {
6573     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
6574     // as to remove this logic from here, as much as possible
6575     if (NumElems == 2 || !X86::isMOVLMask(SVOp))
6576       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6577     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6578   }
6579
6580   assert(VT != MVT::v4i32 && "unsupported shuffle type");
6581
6582   // Invert the operand order and use SHUFPS to match it.
6583   return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V2, V1,
6584                               X86::getShuffleSHUFImmediate(SVOp), DAG);
6585 }
6586
6587 static inline unsigned getUNPCKLOpcode(EVT VT, bool HasAVX2) {
6588   switch(VT.getSimpleVT().SimpleTy) {
6589   case MVT::v4i32: return X86ISD::PUNPCKLDQ;
6590   case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
6591   case MVT::v4f32: return X86ISD::UNPCKLPS;
6592   case MVT::v2f64: return X86ISD::UNPCKLPD;
6593   case MVT::v8i32:
6594     if (HasAVX2)   return X86ISD::VPUNPCKLDQY;
6595     // else use fp unit for int unpack.
6596   case MVT::v8f32: return X86ISD::VUNPCKLPSY;
6597   case MVT::v4i64:
6598     if (HasAVX2)   return X86ISD::VPUNPCKLQDQY;
6599     // else use fp unit for int unpack.
6600   case MVT::v4f64: return X86ISD::VUNPCKLPDY;
6601   case MVT::v16i8: return X86ISD::PUNPCKLBW;
6602   case MVT::v8i16: return X86ISD::PUNPCKLWD;
6603   case MVT::v16i16: return X86ISD::VPUNPCKLWDY;
6604   case MVT::v32i8: return X86ISD::VPUNPCKLBWY;
6605   default:
6606     llvm_unreachable("Unknown type for unpckl");
6607   }
6608   return 0;
6609 }
6610
6611 static inline unsigned getUNPCKHOpcode(EVT VT, bool HasAVX2) {
6612   switch(VT.getSimpleVT().SimpleTy) {
6613   case MVT::v4i32: return X86ISD::PUNPCKHDQ;
6614   case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
6615   case MVT::v4f32: return X86ISD::UNPCKHPS;
6616   case MVT::v2f64: return X86ISD::UNPCKHPD;
6617   case MVT::v8i32:
6618     if (HasAVX2)   return X86ISD::VPUNPCKHDQY;
6619     // else use fp unit for int unpack.
6620   case MVT::v8f32: return X86ISD::VUNPCKHPSY;
6621   case MVT::v4i64:
6622     if (HasAVX2)   return X86ISD::VPUNPCKHQDQY;
6623     // else use fp unit for int unpack.
6624   case MVT::v4f64: return X86ISD::VUNPCKHPDY;
6625   case MVT::v16i8: return X86ISD::PUNPCKHBW;
6626   case MVT::v8i16: return X86ISD::PUNPCKHWD;
6627   case MVT::v16i16: return X86ISD::VPUNPCKHWDY;
6628   case MVT::v32i8: return X86ISD::VPUNPCKHBWY;
6629   default:
6630     llvm_unreachable("Unknown type for unpckh");
6631   }
6632   return 0;
6633 }
6634
6635 static inline unsigned getVPERMILOpcode(EVT VT) {
6636   switch(VT.getSimpleVT().SimpleTy) {
6637   case MVT::v4i32:
6638   case MVT::v4f32: return X86ISD::VPERMILPS;
6639   case MVT::v2i64:
6640   case MVT::v2f64: return X86ISD::VPERMILPD;
6641   case MVT::v8i32:
6642   case MVT::v8f32: return X86ISD::VPERMILPSY;
6643   case MVT::v4i64:
6644   case MVT::v4f64: return X86ISD::VPERMILPDY;
6645   default:
6646     llvm_unreachable("Unknown type for vpermil");
6647   }
6648   return 0;
6649 }
6650
6651 static
6652 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
6653                                const TargetLowering &TLI,
6654                                const X86Subtarget *Subtarget) {
6655   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6656   EVT VT = Op.getValueType();
6657   DebugLoc dl = Op.getDebugLoc();
6658   SDValue V1 = Op.getOperand(0);
6659   SDValue V2 = Op.getOperand(1);
6660
6661   if (isZeroShuffle(SVOp))
6662     return getZeroVector(VT, Subtarget->hasXMMInt(), DAG, dl);
6663
6664   // Handle splat operations
6665   if (SVOp->isSplat()) {
6666     unsigned NumElem = VT.getVectorNumElements();
6667     int Size = VT.getSizeInBits();
6668     // Special case, this is the only place now where it's allowed to return
6669     // a vector_shuffle operation without using a target specific node, because
6670     // *hopefully* it will be optimized away by the dag combiner. FIXME: should
6671     // this be moved to DAGCombine instead?
6672     if (NumElem <= 4 && CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
6673       return Op;
6674
6675     // Use vbroadcast whenever the splat comes from a foldable load
6676     SDValue LD = isVectorBroadcast(Op, Subtarget->hasAVX2());
6677     if (Subtarget->hasAVX() && LD.getNode())
6678       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, LD);
6679
6680     // Handle splats by matching through known shuffle masks
6681     if ((Size == 128 && NumElem <= 4) ||
6682         (Size == 256 && NumElem < 8))
6683       return SDValue();
6684
6685     // All remaning splats are promoted to target supported vector shuffles.
6686     return PromoteSplat(SVOp, DAG);
6687   }
6688
6689   // If the shuffle can be profitably rewritten as a narrower shuffle, then
6690   // do it!
6691   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
6692     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6693     if (NewOp.getNode())
6694       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
6695   } else if ((VT == MVT::v4i32 ||
6696              (VT == MVT::v4f32 && Subtarget->hasXMMInt()))) {
6697     // FIXME: Figure out a cleaner way to do this.
6698     // Try to make use of movq to zero out the top part.
6699     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
6700       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6701       if (NewOp.getNode()) {
6702         if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
6703           return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
6704                               DAG, Subtarget, dl);
6705       }
6706     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
6707       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
6708       if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
6709         return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
6710                             DAG, Subtarget, dl);
6711     }
6712   }
6713   return SDValue();
6714 }
6715
6716 SDValue
6717 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
6718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6719   SDValue V1 = Op.getOperand(0);
6720   SDValue V2 = Op.getOperand(1);
6721   EVT VT = Op.getValueType();
6722   DebugLoc dl = Op.getDebugLoc();
6723   unsigned NumElems = VT.getVectorNumElements();
6724   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
6725   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6726   bool V1IsSplat = false;
6727   bool V2IsSplat = false;
6728   bool HasXMMInt = Subtarget->hasXMMInt();
6729   bool HasAVX2   = Subtarget->hasAVX2();
6730   MachineFunction &MF = DAG.getMachineFunction();
6731   bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
6732
6733   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
6734
6735   // Vector shuffle lowering takes 3 steps:
6736   //
6737   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
6738   //    narrowing and commutation of operands should be handled.
6739   // 2) Matching of shuffles with known shuffle masks to x86 target specific
6740   //    shuffle nodes.
6741   // 3) Rewriting of unmatched masks into new generic shuffle operations,
6742   //    so the shuffle can be broken into other shuffles and the legalizer can
6743   //    try the lowering again.
6744   //
6745   // The general idea is that no vector_shuffle operation should be left to
6746   // be matched during isel, all of them must be converted to a target specific
6747   // node here.
6748
6749   // Normalize the input vectors. Here splats, zeroed vectors, profitable
6750   // narrowing and commutation of operands should be handled. The actual code
6751   // doesn't include all of those, work in progress...
6752   SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
6753   if (NewOp.getNode())
6754     return NewOp;
6755
6756   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
6757   // unpckh_undef). Only use pshufd if speed is more important than size.
6758   if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
6759     return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6760                                 DAG);
6761   if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
6762     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6763                                 DAG);
6764
6765   if (X86::isMOVDDUPMask(SVOp) &&
6766       (Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
6767       V2IsUndef && RelaxedMayFoldVectorLoad(V1))
6768     return getMOVDDup(Op, dl, V1, DAG);
6769
6770   if (X86::isMOVHLPS_v_undef_Mask(SVOp))
6771     return getMOVHighToLow(Op, dl, DAG);
6772
6773   // Use to match splats
6774   if (HasXMMInt && X86::isUNPCKHMask(SVOp, Subtarget->hasAVX2()) && V2IsUndef &&
6775       (VT == MVT::v2f64 || VT == MVT::v2i64))
6776     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6777                                 DAG);
6778
6779   if (X86::isPSHUFDMask(SVOp)) {
6780     // The actual implementation will match the mask in the if above and then
6781     // during isel it can match several different instructions, not only pshufd
6782     // as its name says, sad but true, emulate the behavior for now...
6783     if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
6784         return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
6785
6786     unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
6787
6788     if (HasXMMInt && (VT == MVT::v4f32 || VT == MVT::v4i32))
6789       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
6790
6791     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V1,
6792                                 TargetMask, DAG);
6793   }
6794
6795   // Check if this can be converted into a logical shift.
6796   bool isLeft = false;
6797   unsigned ShAmt = 0;
6798   SDValue ShVal;
6799   bool isShift = getSubtarget()->hasXMMInt() &&
6800                  isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
6801   if (isShift && ShVal.hasOneUse()) {
6802     // If the shifted value has multiple uses, it may be cheaper to use
6803     // v_set0 + movlhps or movhlps, etc.
6804     EVT EltVT = VT.getVectorElementType();
6805     ShAmt *= EltVT.getSizeInBits();
6806     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6807   }
6808
6809   if (X86::isMOVLMask(SVOp)) {
6810     if (V1IsUndef)
6811       return V2;
6812     if (ISD::isBuildVectorAllZeros(V1.getNode()))
6813       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
6814     if (!X86::isMOVLPMask(SVOp)) {
6815       if (HasXMMInt && (VT == MVT::v2i64 || VT == MVT::v2f64))
6816         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
6817
6818       if (VT == MVT::v4i32 || VT == MVT::v4f32)
6819         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
6820     }
6821   }
6822
6823   // FIXME: fold these into legal mask.
6824   if (X86::isMOVLHPSMask(SVOp) &&
6825       !X86::isUNPCKLMask(SVOp, Subtarget->hasAVX2()))
6826     return getMOVLowToHigh(Op, dl, DAG, HasXMMInt);
6827
6828   if (X86::isMOVHLPSMask(SVOp))
6829     return getMOVHighToLow(Op, dl, DAG);
6830
6831   if (X86::isMOVSHDUPMask(SVOp, Subtarget))
6832     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
6833
6834   if (X86::isMOVSLDUPMask(SVOp, Subtarget))
6835     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
6836
6837   if (X86::isMOVLPMask(SVOp))
6838     return getMOVLP(Op, dl, DAG, HasXMMInt);
6839
6840   if (ShouldXformToMOVHLPS(SVOp) ||
6841       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
6842     return CommuteVectorShuffle(SVOp, DAG);
6843
6844   if (isShift) {
6845     // No better options. Use a vshl / vsrl.
6846     EVT EltVT = VT.getVectorElementType();
6847     ShAmt *= EltVT.getSizeInBits();
6848     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
6849   }
6850
6851   bool Commuted = false;
6852   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
6853   // 1,1,1,1 -> v8i16 though.
6854   V1IsSplat = isSplatVector(V1.getNode());
6855   V2IsSplat = isSplatVector(V2.getNode());
6856
6857   // Canonicalize the splat or undef, if present, to be on the RHS.
6858   if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
6859     Op = CommuteVectorShuffle(SVOp, DAG);
6860     SVOp = cast<ShuffleVectorSDNode>(Op);
6861     V1 = SVOp->getOperand(0);
6862     V2 = SVOp->getOperand(1);
6863     std::swap(V1IsSplat, V2IsSplat);
6864     std::swap(V1IsUndef, V2IsUndef);
6865     Commuted = true;
6866   }
6867
6868   if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
6869     // Shuffling low element of v1 into undef, just return v1.
6870     if (V2IsUndef)
6871       return V1;
6872     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
6873     // the instruction selector will not match, so get a canonical MOVL with
6874     // swapped operands to undo the commute.
6875     return getMOVL(DAG, dl, VT, V2, V1);
6876   }
6877
6878   if (X86::isUNPCKLMask(SVOp, Subtarget->hasAVX2()))
6879     return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V2,
6880                                 DAG);
6881
6882   if (X86::isUNPCKHMask(SVOp, Subtarget->hasAVX2()))
6883     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V2,
6884                                 DAG);
6885
6886   if (V2IsSplat) {
6887     // Normalize mask so all entries that point to V2 points to its first
6888     // element then try to match unpck{h|l} again. If match, return a
6889     // new vector_shuffle with the corrected mask.
6890     SDValue NewMask = NormalizeMask(SVOp, DAG);
6891     ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
6892     if (NSVOp != SVOp) {
6893       if (X86::isUNPCKLMask(NSVOp, Subtarget->hasAVX2(), true)) {
6894         return NewMask;
6895       } else if (X86::isUNPCKHMask(NSVOp, Subtarget->hasAVX2(), true)) {
6896         return NewMask;
6897       }
6898     }
6899   }
6900
6901   if (Commuted) {
6902     // Commute is back and try unpck* again.
6903     // FIXME: this seems wrong.
6904     SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
6905     ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
6906
6907     if (X86::isUNPCKLMask(NewSVOp, Subtarget->hasAVX2()))
6908       return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V2, V1,
6909                                   DAG);
6910
6911     if (X86::isUNPCKHMask(NewSVOp, Subtarget->hasAVX2()))
6912       return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V2, V1,
6913                                   DAG);
6914   }
6915
6916   // Normalize the node to match x86 shuffle ops if needed
6917   if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
6918     return CommuteVectorShuffle(SVOp, DAG);
6919
6920   // The checks below are all present in isShuffleMaskLegal, but they are
6921   // inlined here right now to enable us to directly emit target specific
6922   // nodes, and remove one by one until they don't return Op anymore.
6923   SmallVector<int, 16> M;
6924   SVOp->getMask(M);
6925
6926   if (isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()))
6927     return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
6928                                 X86::getShufflePALIGNRImmediate(SVOp),
6929                                 DAG);
6930
6931   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
6932       SVOp->getSplatIndex() == 0 && V2IsUndef) {
6933     if (VT == MVT::v2f64)
6934       return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
6935     if (VT == MVT::v2i64)
6936       return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
6937   }
6938
6939   if (isPSHUFHWMask(M, VT))
6940     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
6941                                 X86::getShufflePSHUFHWImmediate(SVOp),
6942                                 DAG);
6943
6944   if (isPSHUFLWMask(M, VT))
6945     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
6946                                 X86::getShufflePSHUFLWImmediate(SVOp),
6947                                 DAG);
6948
6949   if (isSHUFPMask(M, VT))
6950     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6951                                 X86::getShuffleSHUFImmediate(SVOp), DAG);
6952
6953   if (X86::isUNPCKL_v_undef_Mask(SVOp))
6954     return getTargetShuffleNode(getUNPCKLOpcode(VT, HasAVX2), dl, VT, V1, V1,
6955                                 DAG);
6956   if (X86::isUNPCKH_v_undef_Mask(SVOp))
6957     return getTargetShuffleNode(getUNPCKHOpcode(VT, HasAVX2), dl, VT, V1, V1,
6958                                 DAG);
6959
6960   //===--------------------------------------------------------------------===//
6961   // Generate target specific nodes for 128 or 256-bit shuffles only
6962   // supported in the AVX instruction set.
6963   //
6964
6965   // Handle VMOVDDUPY permutations
6966   if (isMOVDDUPYMask(SVOp, Subtarget))
6967     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
6968
6969   // Handle VPERMILPS* permutations
6970   if (isVPERMILPSMask(M, VT, Subtarget))
6971     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6972                                 getShuffleVPERMILPSImmediate(SVOp), DAG);
6973
6974   // Handle VPERMILPD* permutations
6975   if (isVPERMILPDMask(M, VT, Subtarget))
6976     return getTargetShuffleNode(getVPERMILOpcode(VT), dl, VT, V1,
6977                                 getShuffleVPERMILPDImmediate(SVOp), DAG);
6978
6979   // Handle VPERM2F128 permutations
6980   if (isVPERM2F128Mask(M, VT, Subtarget))
6981     return getTargetShuffleNode(X86ISD::VPERM2F128, dl, VT, V1, V2,
6982                                 getShuffleVPERM2F128Immediate(SVOp), DAG);
6983
6984   // Handle VSHUFPSY permutations
6985   if (isVSHUFPSYMask(M, VT, Subtarget))
6986     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6987                                 getShuffleVSHUFPSYImmediate(SVOp), DAG);
6988
6989   // Handle VSHUFPDY permutations
6990   if (isVSHUFPDYMask(M, VT, Subtarget))
6991     return getTargetShuffleNode(getSHUFPOpcode(VT), dl, VT, V1, V2,
6992                                 getShuffleVSHUFPDYImmediate(SVOp), DAG);
6993
6994   //===--------------------------------------------------------------------===//
6995   // Since no target specific shuffle was selected for this generic one,
6996   // lower it into other known shuffles. FIXME: this isn't true yet, but
6997   // this is the plan.
6998   //
6999
7000   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7001   if (VT == MVT::v8i16) {
7002     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
7003     if (NewOp.getNode())
7004       return NewOp;
7005   }
7006
7007   if (VT == MVT::v16i8) {
7008     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
7009     if (NewOp.getNode())
7010       return NewOp;
7011   }
7012
7013   // Handle all 128-bit wide vectors with 4 elements, and match them with
7014   // several different shuffle types.
7015   if (NumElems == 4 && VT.getSizeInBits() == 128)
7016     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7017
7018   // Handle general 256-bit shuffles
7019   if (VT.is256BitVector())
7020     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7021
7022   return SDValue();
7023 }
7024
7025 SDValue
7026 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
7027                                                 SelectionDAG &DAG) const {
7028   EVT VT = Op.getValueType();
7029   DebugLoc dl = Op.getDebugLoc();
7030
7031   if (Op.getOperand(0).getValueType().getSizeInBits() != 128)
7032     return SDValue();
7033
7034   if (VT.getSizeInBits() == 8) {
7035     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
7036                                     Op.getOperand(0), Op.getOperand(1));
7037     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7038                                     DAG.getValueType(VT));
7039     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7040   } else if (VT.getSizeInBits() == 16) {
7041     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7042     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
7043     if (Idx == 0)
7044       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7045                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7046                                      DAG.getNode(ISD::BITCAST, dl,
7047                                                  MVT::v4i32,
7048                                                  Op.getOperand(0)),
7049                                      Op.getOperand(1)));
7050     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
7051                                     Op.getOperand(0), Op.getOperand(1));
7052     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
7053                                     DAG.getValueType(VT));
7054     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7055   } else if (VT == MVT::f32) {
7056     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
7057     // the result back to FR32 register. It's only worth matching if the
7058     // result has a single use which is a store or a bitcast to i32.  And in
7059     // the case of a store, it's not worth it if the index is a constant 0,
7060     // because a MOVSSmr can be used instead, which is smaller and faster.
7061     if (!Op.hasOneUse())
7062       return SDValue();
7063     SDNode *User = *Op.getNode()->use_begin();
7064     if ((User->getOpcode() != ISD::STORE ||
7065          (isa<ConstantSDNode>(Op.getOperand(1)) &&
7066           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
7067         (User->getOpcode() != ISD::BITCAST ||
7068          User->getValueType(0) != MVT::i32))
7069       return SDValue();
7070     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7071                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
7072                                               Op.getOperand(0)),
7073                                               Op.getOperand(1));
7074     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
7075   } else if (VT == MVT::i32 || VT == MVT::i64) {
7076     // ExtractPS/pextrq works with constant index.
7077     if (isa<ConstantSDNode>(Op.getOperand(1)))
7078       return Op;
7079   }
7080   return SDValue();
7081 }
7082
7083
7084 SDValue
7085 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7086                                            SelectionDAG &DAG) const {
7087   if (!isa<ConstantSDNode>(Op.getOperand(1)))
7088     return SDValue();
7089
7090   SDValue Vec = Op.getOperand(0);
7091   EVT VecVT = Vec.getValueType();
7092
7093   // If this is a 256-bit vector result, first extract the 128-bit vector and
7094   // then extract the element from the 128-bit vector.
7095   if (VecVT.getSizeInBits() == 256) {
7096     DebugLoc dl = Op.getNode()->getDebugLoc();
7097     unsigned NumElems = VecVT.getVectorNumElements();
7098     SDValue Idx = Op.getOperand(1);
7099     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
7100
7101     // Get the 128-bit vector.
7102     bool Upper = IdxVal >= NumElems/2;
7103     Vec = Extract128BitVector(Vec,
7104                     DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32), DAG, dl);
7105
7106     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
7107                     Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : Idx);
7108   }
7109
7110   assert(Vec.getValueSizeInBits() <= 128 && "Unexpected vector length");
7111
7112   if (Subtarget->hasSSE41() || Subtarget->hasAVX()) {
7113     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
7114     if (Res.getNode())
7115       return Res;
7116   }
7117
7118   EVT VT = Op.getValueType();
7119   DebugLoc dl = Op.getDebugLoc();
7120   // TODO: handle v16i8.
7121   if (VT.getSizeInBits() == 16) {
7122     SDValue Vec = Op.getOperand(0);
7123     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7124     if (Idx == 0)
7125       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
7126                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7127                                      DAG.getNode(ISD::BITCAST, dl,
7128                                                  MVT::v4i32, Vec),
7129                                      Op.getOperand(1)));
7130     // Transform it so it match pextrw which produces a 32-bit result.
7131     EVT EltVT = MVT::i32;
7132     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
7133                                     Op.getOperand(0), Op.getOperand(1));
7134     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
7135                                     DAG.getValueType(VT));
7136     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
7137   } else if (VT.getSizeInBits() == 32) {
7138     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7139     if (Idx == 0)
7140       return Op;
7141
7142     // SHUFPS the element to the lowest double word, then movss.
7143     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
7144     EVT VVT = Op.getOperand(0).getValueType();
7145     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7146                                        DAG.getUNDEF(VVT), Mask);
7147     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7148                        DAG.getIntPtrConstant(0));
7149   } else if (VT.getSizeInBits() == 64) {
7150     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
7151     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
7152     //        to match extract_elt for f64.
7153     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7154     if (Idx == 0)
7155       return Op;
7156
7157     // UNPCKHPD the element to the lowest double word, then movsd.
7158     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
7159     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
7160     int Mask[2] = { 1, -1 };
7161     EVT VVT = Op.getOperand(0).getValueType();
7162     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
7163                                        DAG.getUNDEF(VVT), Mask);
7164     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
7165                        DAG.getIntPtrConstant(0));
7166   }
7167
7168   return SDValue();
7169 }
7170
7171 SDValue
7172 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
7173                                                SelectionDAG &DAG) const {
7174   EVT VT = Op.getValueType();
7175   EVT EltVT = VT.getVectorElementType();
7176   DebugLoc dl = Op.getDebugLoc();
7177
7178   SDValue N0 = Op.getOperand(0);
7179   SDValue N1 = Op.getOperand(1);
7180   SDValue N2 = Op.getOperand(2);
7181
7182   if (VT.getSizeInBits() == 256)
7183     return SDValue();
7184
7185   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
7186       isa<ConstantSDNode>(N2)) {
7187     unsigned Opc;
7188     if (VT == MVT::v8i16)
7189       Opc = X86ISD::PINSRW;
7190     else if (VT == MVT::v16i8)
7191       Opc = X86ISD::PINSRB;
7192     else
7193       Opc = X86ISD::PINSRB;
7194
7195     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
7196     // argument.
7197     if (N1.getValueType() != MVT::i32)
7198       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7199     if (N2.getValueType() != MVT::i32)
7200       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7201     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
7202   } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
7203     // Bits [7:6] of the constant are the source select.  This will always be
7204     //  zero here.  The DAG Combiner may combine an extract_elt index into these
7205     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
7206     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
7207     // Bits [5:4] of the constant are the destination select.  This is the
7208     //  value of the incoming immediate.
7209     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
7210     //   combine either bitwise AND or insert of float 0.0 to set these bits.
7211     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
7212     // Create this as a scalar to vector..
7213     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
7214     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
7215   } else if ((EltVT == MVT::i32 || EltVT == MVT::i64) && 
7216              isa<ConstantSDNode>(N2)) {
7217     // PINSR* works with constant index.
7218     return Op;
7219   }
7220   return SDValue();
7221 }
7222
7223 SDValue
7224 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
7225   EVT VT = Op.getValueType();
7226   EVT EltVT = VT.getVectorElementType();
7227
7228   DebugLoc dl = Op.getDebugLoc();
7229   SDValue N0 = Op.getOperand(0);
7230   SDValue N1 = Op.getOperand(1);
7231   SDValue N2 = Op.getOperand(2);
7232
7233   // If this is a 256-bit vector result, first extract the 128-bit vector,
7234   // insert the element into the extracted half and then place it back.
7235   if (VT.getSizeInBits() == 256) {
7236     if (!isa<ConstantSDNode>(N2))
7237       return SDValue();
7238
7239     // Get the desired 128-bit vector half.
7240     unsigned NumElems = VT.getVectorNumElements();
7241     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
7242     bool Upper = IdxVal >= NumElems/2;
7243     SDValue Ins128Idx = DAG.getConstant(Upper ? NumElems/2 : 0, MVT::i32);
7244     SDValue V = Extract128BitVector(N0, Ins128Idx, DAG, dl);
7245
7246     // Insert the element into the desired half.
7247     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V,
7248                  N1, Upper ? DAG.getConstant(IdxVal-NumElems/2, MVT::i32) : N2);
7249
7250     // Insert the changed part back to the 256-bit vector
7251     return Insert128BitVector(N0, V, Ins128Idx, DAG, dl);
7252   }
7253
7254   if (Subtarget->hasSSE41() || Subtarget->hasAVX())
7255     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
7256
7257   if (EltVT == MVT::i8)
7258     return SDValue();
7259
7260   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
7261     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
7262     // as its second argument.
7263     if (N1.getValueType() != MVT::i32)
7264       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
7265     if (N2.getValueType() != MVT::i32)
7266       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
7267     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
7268   }
7269   return SDValue();
7270 }
7271
7272 SDValue
7273 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
7274   LLVMContext *Context = DAG.getContext();
7275   DebugLoc dl = Op.getDebugLoc();
7276   EVT OpVT = Op.getValueType();
7277
7278   // If this is a 256-bit vector result, first insert into a 128-bit
7279   // vector and then insert into the 256-bit vector.
7280   if (OpVT.getSizeInBits() > 128) {
7281     // Insert into a 128-bit vector.
7282     EVT VT128 = EVT::getVectorVT(*Context,
7283                                  OpVT.getVectorElementType(),
7284                                  OpVT.getVectorNumElements() / 2);
7285
7286     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
7287
7288     // Insert the 128-bit vector.
7289     return Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, OpVT), Op,
7290                               DAG.getConstant(0, MVT::i32),
7291                               DAG, dl);
7292   }
7293
7294   if (Op.getValueType() == MVT::v1i64 &&
7295       Op.getOperand(0).getValueType() == MVT::i64)
7296     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
7297
7298   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
7299   assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
7300          "Expected an SSE type!");
7301   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
7302                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
7303 }
7304
7305 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
7306 // a simple subregister reference or explicit instructions to grab
7307 // upper bits of a vector.
7308 SDValue
7309 X86TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7310   if (Subtarget->hasAVX()) {
7311     DebugLoc dl = Op.getNode()->getDebugLoc();
7312     SDValue Vec = Op.getNode()->getOperand(0);
7313     SDValue Idx = Op.getNode()->getOperand(1);
7314
7315     if (Op.getNode()->getValueType(0).getSizeInBits() == 128
7316         && Vec.getNode()->getValueType(0).getSizeInBits() == 256) {
7317         return Extract128BitVector(Vec, Idx, DAG, dl);
7318     }
7319   }
7320   return SDValue();
7321 }
7322
7323 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
7324 // simple superregister reference or explicit instructions to insert
7325 // the upper bits of a vector.
7326 SDValue
7327 X86TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op, SelectionDAG &DAG) const {
7328   if (Subtarget->hasAVX()) {
7329     DebugLoc dl = Op.getNode()->getDebugLoc();
7330     SDValue Vec = Op.getNode()->getOperand(0);
7331     SDValue SubVec = Op.getNode()->getOperand(1);
7332     SDValue Idx = Op.getNode()->getOperand(2);
7333
7334     if (Op.getNode()->getValueType(0).getSizeInBits() == 256
7335         && SubVec.getNode()->getValueType(0).getSizeInBits() == 128) {
7336       return Insert128BitVector(Vec, SubVec, Idx, DAG, dl);
7337     }
7338   }
7339   return SDValue();
7340 }
7341
7342 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
7343 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
7344 // one of the above mentioned nodes. It has to be wrapped because otherwise
7345 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
7346 // be used to form addressing mode. These wrapped nodes will be selected
7347 // into MOV32ri.
7348 SDValue
7349 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
7350   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
7351
7352   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7353   // global base reg.
7354   unsigned char OpFlag = 0;
7355   unsigned WrapperKind = X86ISD::Wrapper;
7356   CodeModel::Model M = getTargetMachine().getCodeModel();
7357
7358   if (Subtarget->isPICStyleRIPRel() &&
7359       (M == CodeModel::Small || M == CodeModel::Kernel))
7360     WrapperKind = X86ISD::WrapperRIP;
7361   else if (Subtarget->isPICStyleGOT())
7362     OpFlag = X86II::MO_GOTOFF;
7363   else if (Subtarget->isPICStyleStubPIC())
7364     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7365
7366   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
7367                                              CP->getAlignment(),
7368                                              CP->getOffset(), OpFlag);
7369   DebugLoc DL = CP->getDebugLoc();
7370   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7371   // With PIC, the address is actually $g + Offset.
7372   if (OpFlag) {
7373     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7374                          DAG.getNode(X86ISD::GlobalBaseReg,
7375                                      DebugLoc(), getPointerTy()),
7376                          Result);
7377   }
7378
7379   return Result;
7380 }
7381
7382 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
7383   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
7384
7385   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7386   // global base reg.
7387   unsigned char OpFlag = 0;
7388   unsigned WrapperKind = X86ISD::Wrapper;
7389   CodeModel::Model M = getTargetMachine().getCodeModel();
7390
7391   if (Subtarget->isPICStyleRIPRel() &&
7392       (M == CodeModel::Small || M == CodeModel::Kernel))
7393     WrapperKind = X86ISD::WrapperRIP;
7394   else if (Subtarget->isPICStyleGOT())
7395     OpFlag = X86II::MO_GOTOFF;
7396   else if (Subtarget->isPICStyleStubPIC())
7397     OpFlag = X86II::MO_PIC_BASE_OFFSET;
7398
7399   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
7400                                           OpFlag);
7401   DebugLoc DL = JT->getDebugLoc();
7402   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7403
7404   // With PIC, the address is actually $g + Offset.
7405   if (OpFlag)
7406     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7407                          DAG.getNode(X86ISD::GlobalBaseReg,
7408                                      DebugLoc(), getPointerTy()),
7409                          Result);
7410
7411   return Result;
7412 }
7413
7414 SDValue
7415 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
7416   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
7417
7418   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7419   // global base reg.
7420   unsigned char OpFlag = 0;
7421   unsigned WrapperKind = X86ISD::Wrapper;
7422   CodeModel::Model M = getTargetMachine().getCodeModel();
7423
7424   if (Subtarget->isPICStyleRIPRel() &&
7425       (M == CodeModel::Small || M == CodeModel::Kernel)) {
7426     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
7427       OpFlag = X86II::MO_GOTPCREL;
7428     WrapperKind = X86ISD::WrapperRIP;
7429   } else if (Subtarget->isPICStyleGOT()) {
7430     OpFlag = X86II::MO_GOT;
7431   } else if (Subtarget->isPICStyleStubPIC()) {
7432     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
7433   } else if (Subtarget->isPICStyleStubNoDynamic()) {
7434     OpFlag = X86II::MO_DARWIN_NONLAZY;
7435   }
7436
7437   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
7438
7439   DebugLoc DL = Op.getDebugLoc();
7440   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7441
7442
7443   // With PIC, the address is actually $g + Offset.
7444   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
7445       !Subtarget->is64Bit()) {
7446     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7447                          DAG.getNode(X86ISD::GlobalBaseReg,
7448                                      DebugLoc(), getPointerTy()),
7449                          Result);
7450   }
7451
7452   // For symbols that require a load from a stub to get the address, emit the
7453   // load.
7454   if (isGlobalStubReference(OpFlag))
7455     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
7456                          MachinePointerInfo::getGOT(), false, false, false, 0);
7457
7458   return Result;
7459 }
7460
7461 SDValue
7462 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
7463   // Create the TargetBlockAddressAddress node.
7464   unsigned char OpFlags =
7465     Subtarget->ClassifyBlockAddressReference();
7466   CodeModel::Model M = getTargetMachine().getCodeModel();
7467   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
7468   DebugLoc dl = Op.getDebugLoc();
7469   SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
7470                                        /*isTarget=*/true, OpFlags);
7471
7472   if (Subtarget->isPICStyleRIPRel() &&
7473       (M == CodeModel::Small || M == CodeModel::Kernel))
7474     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7475   else
7476     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7477
7478   // With PIC, the address is actually $g + Offset.
7479   if (isGlobalRelativeToPICBase(OpFlags)) {
7480     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7481                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7482                          Result);
7483   }
7484
7485   return Result;
7486 }
7487
7488 SDValue
7489 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
7490                                       int64_t Offset,
7491                                       SelectionDAG &DAG) const {
7492   // Create the TargetGlobalAddress node, folding in the constant
7493   // offset if it is legal.
7494   unsigned char OpFlags =
7495     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
7496   CodeModel::Model M = getTargetMachine().getCodeModel();
7497   SDValue Result;
7498   if (OpFlags == X86II::MO_NO_FLAG &&
7499       X86::isOffsetSuitableForCodeModel(Offset, M)) {
7500     // A direct static reference to a global.
7501     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
7502     Offset = 0;
7503   } else {
7504     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
7505   }
7506
7507   if (Subtarget->isPICStyleRIPRel() &&
7508       (M == CodeModel::Small || M == CodeModel::Kernel))
7509     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
7510   else
7511     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
7512
7513   // With PIC, the address is actually $g + Offset.
7514   if (isGlobalRelativeToPICBase(OpFlags)) {
7515     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7516                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
7517                          Result);
7518   }
7519
7520   // For globals that require a load from a stub to get the address, emit the
7521   // load.
7522   if (isGlobalStubReference(OpFlags))
7523     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
7524                          MachinePointerInfo::getGOT(), false, false, false, 0);
7525
7526   // If there was a non-zero offset that we didn't fold, create an explicit
7527   // addition for it.
7528   if (Offset != 0)
7529     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
7530                          DAG.getConstant(Offset, getPointerTy()));
7531
7532   return Result;
7533 }
7534
7535 SDValue
7536 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
7537   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
7538   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
7539   return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
7540 }
7541
7542 static SDValue
7543 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
7544            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
7545            unsigned char OperandFlags) {
7546   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7547   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7548   DebugLoc dl = GA->getDebugLoc();
7549   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7550                                            GA->getValueType(0),
7551                                            GA->getOffset(),
7552                                            OperandFlags);
7553   if (InFlag) {
7554     SDValue Ops[] = { Chain,  TGA, *InFlag };
7555     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
7556   } else {
7557     SDValue Ops[]  = { Chain, TGA };
7558     Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
7559   }
7560
7561   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7562   MFI->setAdjustsStack(true);
7563
7564   SDValue Flag = Chain.getValue(1);
7565   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
7566 }
7567
7568 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
7569 static SDValue
7570 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7571                                 const EVT PtrVT) {
7572   SDValue InFlag;
7573   DebugLoc dl = GA->getDebugLoc();  // ? function entry point might be better
7574   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
7575                                      DAG.getNode(X86ISD::GlobalBaseReg,
7576                                                  DebugLoc(), PtrVT), InFlag);
7577   InFlag = Chain.getValue(1);
7578
7579   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
7580 }
7581
7582 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
7583 static SDValue
7584 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7585                                 const EVT PtrVT) {
7586   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
7587                     X86::RAX, X86II::MO_TLSGD);
7588 }
7589
7590 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
7591 // "local exec" model.
7592 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
7593                                    const EVT PtrVT, TLSModel::Model model,
7594                                    bool is64Bit) {
7595   DebugLoc dl = GA->getDebugLoc();
7596
7597   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
7598   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
7599                                                          is64Bit ? 257 : 256));
7600
7601   SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
7602                                       DAG.getIntPtrConstant(0),
7603                                       MachinePointerInfo(Ptr),
7604                                       false, false, false, 0);
7605
7606   unsigned char OperandFlags = 0;
7607   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
7608   // initialexec.
7609   unsigned WrapperKind = X86ISD::Wrapper;
7610   if (model == TLSModel::LocalExec) {
7611     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
7612   } else if (is64Bit) {
7613     assert(model == TLSModel::InitialExec);
7614     OperandFlags = X86II::MO_GOTTPOFF;
7615     WrapperKind = X86ISD::WrapperRIP;
7616   } else {
7617     assert(model == TLSModel::InitialExec);
7618     OperandFlags = X86II::MO_INDNTPOFF;
7619   }
7620
7621   // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
7622   // exec)
7623   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
7624                                            GA->getValueType(0),
7625                                            GA->getOffset(), OperandFlags);
7626   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
7627
7628   if (model == TLSModel::InitialExec)
7629     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
7630                          MachinePointerInfo::getGOT(), false, false, false, 0);
7631
7632   // The address of the thread local variable is the add of the thread
7633   // pointer with the offset of the variable.
7634   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
7635 }
7636
7637 SDValue
7638 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
7639
7640   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
7641   const GlobalValue *GV = GA->getGlobal();
7642
7643   if (Subtarget->isTargetELF()) {
7644     // TODO: implement the "local dynamic" model
7645     // TODO: implement the "initial exec"model for pic executables
7646
7647     // If GV is an alias then use the aliasee for determining
7648     // thread-localness.
7649     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
7650       GV = GA->resolveAliasedGlobal(false);
7651
7652     TLSModel::Model model
7653       = getTLSModel(GV, getTargetMachine().getRelocationModel());
7654
7655     switch (model) {
7656       case TLSModel::GeneralDynamic:
7657       case TLSModel::LocalDynamic: // not implemented
7658         if (Subtarget->is64Bit())
7659           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
7660         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
7661
7662       case TLSModel::InitialExec:
7663       case TLSModel::LocalExec:
7664         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
7665                                    Subtarget->is64Bit());
7666     }
7667   } else if (Subtarget->isTargetDarwin()) {
7668     // Darwin only has one model of TLS.  Lower to that.
7669     unsigned char OpFlag = 0;
7670     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
7671                            X86ISD::WrapperRIP : X86ISD::Wrapper;
7672
7673     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
7674     // global base reg.
7675     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
7676                   !Subtarget->is64Bit();
7677     if (PIC32)
7678       OpFlag = X86II::MO_TLVP_PIC_BASE;
7679     else
7680       OpFlag = X86II::MO_TLVP;
7681     DebugLoc DL = Op.getDebugLoc();
7682     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
7683                                                 GA->getValueType(0),
7684                                                 GA->getOffset(), OpFlag);
7685     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
7686
7687     // With PIC32, the address is actually $g + Offset.
7688     if (PIC32)
7689       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7690                            DAG.getNode(X86ISD::GlobalBaseReg,
7691                                        DebugLoc(), getPointerTy()),
7692                            Offset);
7693
7694     // Lowering the machine isd will make sure everything is in the right
7695     // location.
7696     SDValue Chain = DAG.getEntryNode();
7697     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7698     SDValue Args[] = { Chain, Offset };
7699     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
7700
7701     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
7702     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7703     MFI->setAdjustsStack(true);
7704
7705     // And our return value (tls address) is in the standard call return value
7706     // location.
7707     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
7708     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
7709                               Chain.getValue(1));
7710   }
7711
7712   assert(false &&
7713          "TLS not implemented for this target.");
7714
7715   llvm_unreachable("Unreachable");
7716   return SDValue();
7717 }
7718
7719
7720 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values and
7721 /// take a 2 x i32 value to shift plus a shift amount.
7722 SDValue X86TargetLowering::LowerShiftParts(SDValue Op, SelectionDAG &DAG) const {
7723   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
7724   EVT VT = Op.getValueType();
7725   unsigned VTBits = VT.getSizeInBits();
7726   DebugLoc dl = Op.getDebugLoc();
7727   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
7728   SDValue ShOpLo = Op.getOperand(0);
7729   SDValue ShOpHi = Op.getOperand(1);
7730   SDValue ShAmt  = Op.getOperand(2);
7731   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7732                                      DAG.getConstant(VTBits - 1, MVT::i8))
7733                        : DAG.getConstant(0, VT);
7734
7735   SDValue Tmp2, Tmp3;
7736   if (Op.getOpcode() == ISD::SHL_PARTS) {
7737     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
7738     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
7739   } else {
7740     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
7741     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
7742   }
7743
7744   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
7745                                 DAG.getConstant(VTBits, MVT::i8));
7746   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7747                              AndNode, DAG.getConstant(0, MVT::i8));
7748
7749   SDValue Hi, Lo;
7750   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7751   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
7752   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
7753
7754   if (Op.getOpcode() == ISD::SHL_PARTS) {
7755     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7756     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7757   } else {
7758     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
7759     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
7760   }
7761
7762   SDValue Ops[2] = { Lo, Hi };
7763   return DAG.getMergeValues(Ops, 2, dl);
7764 }
7765
7766 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
7767                                            SelectionDAG &DAG) const {
7768   EVT SrcVT = Op.getOperand(0).getValueType();
7769
7770   if (SrcVT.isVector())
7771     return SDValue();
7772
7773   assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
7774          "Unknown SINT_TO_FP to lower!");
7775
7776   // These are really Legal; return the operand so the caller accepts it as
7777   // Legal.
7778   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
7779     return Op;
7780   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
7781       Subtarget->is64Bit()) {
7782     return Op;
7783   }
7784
7785   DebugLoc dl = Op.getDebugLoc();
7786   unsigned Size = SrcVT.getSizeInBits()/8;
7787   MachineFunction &MF = DAG.getMachineFunction();
7788   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
7789   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7790   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
7791                                StackSlot,
7792                                MachinePointerInfo::getFixedStack(SSFI),
7793                                false, false, 0);
7794   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
7795 }
7796
7797 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
7798                                      SDValue StackSlot,
7799                                      SelectionDAG &DAG) const {
7800   // Build the FILD
7801   DebugLoc DL = Op.getDebugLoc();
7802   SDVTList Tys;
7803   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
7804   if (useSSE)
7805     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
7806   else
7807     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
7808
7809   unsigned ByteSize = SrcVT.getSizeInBits()/8;
7810
7811   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
7812   MachineMemOperand *MMO;
7813   if (FI) {
7814     int SSFI = FI->getIndex();
7815     MMO =
7816       DAG.getMachineFunction()
7817       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7818                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
7819   } else {
7820     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
7821     StackSlot = StackSlot.getOperand(1);
7822   }
7823   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
7824   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
7825                                            X86ISD::FILD, DL,
7826                                            Tys, Ops, array_lengthof(Ops),
7827                                            SrcVT, MMO);
7828
7829   if (useSSE) {
7830     Chain = Result.getValue(1);
7831     SDValue InFlag = Result.getValue(2);
7832
7833     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
7834     // shouldn't be necessary except that RFP cannot be live across
7835     // multiple blocks. When stackifier is fixed, they can be uncoupled.
7836     MachineFunction &MF = DAG.getMachineFunction();
7837     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
7838     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
7839     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7840     Tys = DAG.getVTList(MVT::Other);
7841     SDValue Ops[] = {
7842       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
7843     };
7844     MachineMemOperand *MMO =
7845       DAG.getMachineFunction()
7846       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
7847                             MachineMemOperand::MOStore, SSFISize, SSFISize);
7848
7849     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
7850                                     Ops, array_lengthof(Ops),
7851                                     Op.getValueType(), MMO);
7852     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
7853                          MachinePointerInfo::getFixedStack(SSFI),
7854                          false, false, false, 0);
7855   }
7856
7857   return Result;
7858 }
7859
7860 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
7861 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
7862                                                SelectionDAG &DAG) const {
7863   // This algorithm is not obvious. Here it is in C code, more or less:
7864   /*
7865     double uint64_to_double( uint32_t hi, uint32_t lo ) {
7866       static const __m128i exp = { 0x4330000045300000ULL, 0 };
7867       static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
7868
7869       // Copy ints to xmm registers.
7870       __m128i xh = _mm_cvtsi32_si128( hi );
7871       __m128i xl = _mm_cvtsi32_si128( lo );
7872
7873       // Combine into low half of a single xmm register.
7874       __m128i x = _mm_unpacklo_epi32( xh, xl );
7875       __m128d d;
7876       double sd;
7877
7878       // Merge in appropriate exponents to give the integer bits the right
7879       // magnitude.
7880       x = _mm_unpacklo_epi32( x, exp );
7881
7882       // Subtract away the biases to deal with the IEEE-754 double precision
7883       // implicit 1.
7884       d = _mm_sub_pd( (__m128d) x, bias );
7885
7886       // All conversions up to here are exact. The correctly rounded result is
7887       // calculated using the current rounding mode using the following
7888       // horizontal add.
7889       d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
7890       _mm_store_sd( &sd, d );   // Because we are returning doubles in XMM, this
7891                                 // store doesn't really need to be here (except
7892                                 // maybe to zero the other double)
7893       return sd;
7894     }
7895   */
7896
7897   DebugLoc dl = Op.getDebugLoc();
7898   LLVMContext *Context = DAG.getContext();
7899
7900   // Build some magic constants.
7901   std::vector<Constant*> CV0;
7902   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
7903   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
7904   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7905   CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
7906   Constant *C0 = ConstantVector::get(CV0);
7907   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
7908
7909   std::vector<Constant*> CV1;
7910   CV1.push_back(
7911     ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
7912   CV1.push_back(
7913     ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
7914   Constant *C1 = ConstantVector::get(CV1);
7915   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
7916
7917   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7918                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7919                                         Op.getOperand(0),
7920                                         DAG.getIntPtrConstant(1)));
7921   SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7922                             DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7923                                         Op.getOperand(0),
7924                                         DAG.getIntPtrConstant(0)));
7925   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
7926   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
7927                               MachinePointerInfo::getConstantPool(),
7928                               false, false, false, 16);
7929   SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
7930   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
7931   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
7932                               MachinePointerInfo::getConstantPool(),
7933                               false, false, false, 16);
7934   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
7935
7936   // Add the halves; easiest way is to swap them into another reg first.
7937   int ShufMask[2] = { 1, -1 };
7938   SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
7939                                       DAG.getUNDEF(MVT::v2f64), ShufMask);
7940   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
7941   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
7942                      DAG.getIntPtrConstant(0));
7943 }
7944
7945 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
7946 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
7947                                                SelectionDAG &DAG) const {
7948   DebugLoc dl = Op.getDebugLoc();
7949   // FP constant to bias correct the final result.
7950   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
7951                                    MVT::f64);
7952
7953   // Load the 32-bit value into an XMM register.
7954   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
7955                              Op.getOperand(0));
7956
7957   // Zero out the upper parts of the register.
7958   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget->hasXMMInt(),
7959                                      DAG);
7960
7961   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7962                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
7963                      DAG.getIntPtrConstant(0));
7964
7965   // Or the load with the bias.
7966   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
7967                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7968                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7969                                                    MVT::v2f64, Load)),
7970                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
7971                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7972                                                    MVT::v2f64, Bias)));
7973   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7974                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
7975                    DAG.getIntPtrConstant(0));
7976
7977   // Subtract the bias.
7978   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
7979
7980   // Handle final rounding.
7981   EVT DestVT = Op.getValueType();
7982
7983   if (DestVT.bitsLT(MVT::f64)) {
7984     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
7985                        DAG.getIntPtrConstant(0));
7986   } else if (DestVT.bitsGT(MVT::f64)) {
7987     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
7988   }
7989
7990   // Handle final rounding.
7991   return Sub;
7992 }
7993
7994 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
7995                                            SelectionDAG &DAG) const {
7996   SDValue N0 = Op.getOperand(0);
7997   DebugLoc dl = Op.getDebugLoc();
7998
7999   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
8000   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
8001   // the optimization here.
8002   if (DAG.SignBitIsZero(N0))
8003     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
8004
8005   EVT SrcVT = N0.getValueType();
8006   EVT DstVT = Op.getValueType();
8007   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
8008     return LowerUINT_TO_FP_i64(Op, DAG);
8009   else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
8010     return LowerUINT_TO_FP_i32(Op, DAG);
8011
8012   // Make a 64-bit buffer, and use it to build an FILD.
8013   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
8014   if (SrcVT == MVT::i32) {
8015     SDValue WordOff = DAG.getConstant(4, getPointerTy());
8016     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
8017                                      getPointerTy(), StackSlot, WordOff);
8018     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8019                                   StackSlot, MachinePointerInfo(),
8020                                   false, false, 0);
8021     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
8022                                   OffsetSlot, MachinePointerInfo(),
8023                                   false, false, 0);
8024     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
8025     return Fild;
8026   }
8027
8028   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
8029   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
8030                                 StackSlot, MachinePointerInfo(),
8031                                false, false, 0);
8032   // For i64 source, we need to add the appropriate power of 2 if the input
8033   // was negative.  This is the same as the optimization in
8034   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
8035   // we must be careful to do the computation in x87 extended precision, not
8036   // in SSE. (The generic code can't know it's OK to do this, or how to.)
8037   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
8038   MachineMemOperand *MMO =
8039     DAG.getMachineFunction()
8040     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8041                           MachineMemOperand::MOLoad, 8, 8);
8042
8043   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
8044   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
8045   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
8046                                          MVT::i64, MMO);
8047
8048   APInt FF(32, 0x5F800000ULL);
8049
8050   // Check whether the sign bit is set.
8051   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
8052                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
8053                                  ISD::SETLT);
8054
8055   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
8056   SDValue FudgePtr = DAG.getConstantPool(
8057                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
8058                                          getPointerTy());
8059
8060   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
8061   SDValue Zero = DAG.getIntPtrConstant(0);
8062   SDValue Four = DAG.getIntPtrConstant(4);
8063   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
8064                                Zero, Four);
8065   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
8066
8067   // Load the value out, extending it from f32 to f80.
8068   // FIXME: Avoid the extend by constructing the right constant pool?
8069   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
8070                                  FudgePtr, MachinePointerInfo::getConstantPool(),
8071                                  MVT::f32, false, false, 4);
8072   // Extend everything to 80 bits to force it to be done on x87.
8073   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
8074   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
8075 }
8076
8077 std::pair<SDValue,SDValue> X86TargetLowering::
8078 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
8079   DebugLoc DL = Op.getDebugLoc();
8080
8081   EVT DstTy = Op.getValueType();
8082
8083   if (!IsSigned) {
8084     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
8085     DstTy = MVT::i64;
8086   }
8087
8088   assert(DstTy.getSimpleVT() <= MVT::i64 &&
8089          DstTy.getSimpleVT() >= MVT::i16 &&
8090          "Unknown FP_TO_SINT to lower!");
8091
8092   // These are really Legal.
8093   if (DstTy == MVT::i32 &&
8094       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8095     return std::make_pair(SDValue(), SDValue());
8096   if (Subtarget->is64Bit() &&
8097       DstTy == MVT::i64 &&
8098       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
8099     return std::make_pair(SDValue(), SDValue());
8100
8101   // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
8102   // stack slot.
8103   MachineFunction &MF = DAG.getMachineFunction();
8104   unsigned MemSize = DstTy.getSizeInBits()/8;
8105   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8106   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8107
8108
8109
8110   unsigned Opc;
8111   switch (DstTy.getSimpleVT().SimpleTy) {
8112   default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
8113   case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
8114   case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
8115   case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
8116   }
8117
8118   SDValue Chain = DAG.getEntryNode();
8119   SDValue Value = Op.getOperand(0);
8120   EVT TheVT = Op.getOperand(0).getValueType();
8121   if (isScalarFPTypeInSSEReg(TheVT)) {
8122     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
8123     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
8124                          MachinePointerInfo::getFixedStack(SSFI),
8125                          false, false, 0);
8126     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
8127     SDValue Ops[] = {
8128       Chain, StackSlot, DAG.getValueType(TheVT)
8129     };
8130
8131     MachineMemOperand *MMO =
8132       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8133                               MachineMemOperand::MOLoad, MemSize, MemSize);
8134     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
8135                                     DstTy, MMO);
8136     Chain = Value.getValue(1);
8137     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
8138     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8139   }
8140
8141   MachineMemOperand *MMO =
8142     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8143                             MachineMemOperand::MOStore, MemSize, MemSize);
8144
8145   // Build the FP_TO_INT*_IN_MEM
8146   SDValue Ops[] = { Chain, Value, StackSlot };
8147   SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
8148                                          Ops, 3, DstTy, MMO);
8149
8150   return std::make_pair(FIST, StackSlot);
8151 }
8152
8153 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
8154                                            SelectionDAG &DAG) const {
8155   if (Op.getValueType().isVector())
8156     return SDValue();
8157
8158   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
8159   SDValue FIST = Vals.first, StackSlot = Vals.second;
8160   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
8161   if (FIST.getNode() == 0) return Op;
8162
8163   // Load the result.
8164   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8165                      FIST, StackSlot, MachinePointerInfo(),
8166                      false, false, false, 0);
8167 }
8168
8169 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
8170                                            SelectionDAG &DAG) const {
8171   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
8172   SDValue FIST = Vals.first, StackSlot = Vals.second;
8173   assert(FIST.getNode() && "Unexpected failure");
8174
8175   // Load the result.
8176   return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
8177                      FIST, StackSlot, MachinePointerInfo(),
8178                      false, false, false, 0);
8179 }
8180
8181 SDValue X86TargetLowering::LowerFABS(SDValue Op,
8182                                      SelectionDAG &DAG) const {
8183   LLVMContext *Context = DAG.getContext();
8184   DebugLoc dl = Op.getDebugLoc();
8185   EVT VT = Op.getValueType();
8186   EVT EltVT = VT;
8187   if (VT.isVector())
8188     EltVT = VT.getVectorElementType();
8189   std::vector<Constant*> CV;
8190   if (EltVT == MVT::f64) {
8191     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
8192     CV.push_back(C);
8193     CV.push_back(C);
8194   } else {
8195     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
8196     CV.push_back(C);
8197     CV.push_back(C);
8198     CV.push_back(C);
8199     CV.push_back(C);
8200   }
8201   Constant *C = ConstantVector::get(CV);
8202   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8203   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8204                              MachinePointerInfo::getConstantPool(),
8205                              false, false, false, 16);
8206   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
8207 }
8208
8209 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
8210   LLVMContext *Context = DAG.getContext();
8211   DebugLoc dl = Op.getDebugLoc();
8212   EVT VT = Op.getValueType();
8213   EVT EltVT = VT;
8214   if (VT.isVector())
8215     EltVT = VT.getVectorElementType();
8216   std::vector<Constant*> CV;
8217   if (EltVT == MVT::f64) {
8218     Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
8219     CV.push_back(C);
8220     CV.push_back(C);
8221   } else {
8222     Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
8223     CV.push_back(C);
8224     CV.push_back(C);
8225     CV.push_back(C);
8226     CV.push_back(C);
8227   }
8228   Constant *C = ConstantVector::get(CV);
8229   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8230   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8231                              MachinePointerInfo::getConstantPool(),
8232                              false, false, false, 16);
8233   if (VT.isVector()) {
8234     return DAG.getNode(ISD::BITCAST, dl, VT,
8235                        DAG.getNode(ISD::XOR, dl, MVT::v2i64,
8236                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
8237                                 Op.getOperand(0)),
8238                     DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
8239   } else {
8240     return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
8241   }
8242 }
8243
8244 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
8245   LLVMContext *Context = DAG.getContext();
8246   SDValue Op0 = Op.getOperand(0);
8247   SDValue Op1 = Op.getOperand(1);
8248   DebugLoc dl = Op.getDebugLoc();
8249   EVT VT = Op.getValueType();
8250   EVT SrcVT = Op1.getValueType();
8251
8252   // If second operand is smaller, extend it first.
8253   if (SrcVT.bitsLT(VT)) {
8254     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
8255     SrcVT = VT;
8256   }
8257   // And if it is bigger, shrink it first.
8258   if (SrcVT.bitsGT(VT)) {
8259     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
8260     SrcVT = VT;
8261   }
8262
8263   // At this point the operands and the result should have the same
8264   // type, and that won't be f80 since that is not custom lowered.
8265
8266   // First get the sign bit of second operand.
8267   std::vector<Constant*> CV;
8268   if (SrcVT == MVT::f64) {
8269     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
8270     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8271   } else {
8272     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
8273     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8274     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8275     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8276   }
8277   Constant *C = ConstantVector::get(CV);
8278   SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8279   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
8280                               MachinePointerInfo::getConstantPool(),
8281                               false, false, false, 16);
8282   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
8283
8284   // Shift sign bit right or left if the two operands have different types.
8285   if (SrcVT.bitsGT(VT)) {
8286     // Op0 is MVT::f32, Op1 is MVT::f64.
8287     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
8288     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
8289                           DAG.getConstant(32, MVT::i32));
8290     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
8291     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
8292                           DAG.getIntPtrConstant(0));
8293   }
8294
8295   // Clear first operand sign bit.
8296   CV.clear();
8297   if (VT == MVT::f64) {
8298     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
8299     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
8300   } else {
8301     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
8302     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8303     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8304     CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
8305   }
8306   C = ConstantVector::get(CV);
8307   CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8308   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8309                               MachinePointerInfo::getConstantPool(),
8310                               false, false, false, 16);
8311   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
8312
8313   // Or the value with the sign bit.
8314   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
8315 }
8316
8317 SDValue X86TargetLowering::LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) const {
8318   SDValue N0 = Op.getOperand(0);
8319   DebugLoc dl = Op.getDebugLoc();
8320   EVT VT = Op.getValueType();
8321
8322   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
8323   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
8324                                   DAG.getConstant(1, VT));
8325   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
8326 }
8327
8328 /// Emit nodes that will be selected as "test Op0,Op0", or something
8329 /// equivalent.
8330 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
8331                                     SelectionDAG &DAG) const {
8332   DebugLoc dl = Op.getDebugLoc();
8333
8334   // CF and OF aren't always set the way we want. Determine which
8335   // of these we need.
8336   bool NeedCF = false;
8337   bool NeedOF = false;
8338   switch (X86CC) {
8339   default: break;
8340   case X86::COND_A: case X86::COND_AE:
8341   case X86::COND_B: case X86::COND_BE:
8342     NeedCF = true;
8343     break;
8344   case X86::COND_G: case X86::COND_GE:
8345   case X86::COND_L: case X86::COND_LE:
8346   case X86::COND_O: case X86::COND_NO:
8347     NeedOF = true;
8348     break;
8349   }
8350
8351   // See if we can use the EFLAGS value from the operand instead of
8352   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
8353   // we prove that the arithmetic won't overflow, we can't use OF or CF.
8354   if (Op.getResNo() != 0 || NeedOF || NeedCF)
8355     // Emit a CMP with 0, which is the TEST pattern.
8356     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8357                        DAG.getConstant(0, Op.getValueType()));
8358
8359   unsigned Opcode = 0;
8360   unsigned NumOperands = 0;
8361   switch (Op.getNode()->getOpcode()) {
8362   case ISD::ADD:
8363     // Due to an isel shortcoming, be conservative if this add is likely to be
8364     // selected as part of a load-modify-store instruction. When the root node
8365     // in a match is a store, isel doesn't know how to remap non-chain non-flag
8366     // uses of other nodes in the match, such as the ADD in this case. This
8367     // leads to the ADD being left around and reselected, with the result being
8368     // two adds in the output.  Alas, even if none our users are stores, that
8369     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
8370     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
8371     // climbing the DAG back to the root, and it doesn't seem to be worth the
8372     // effort.
8373     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8374          UE = Op.getNode()->use_end(); UI != UE; ++UI)
8375       if (UI->getOpcode() != ISD::CopyToReg &&
8376           UI->getOpcode() != ISD::SETCC &&
8377           UI->getOpcode() != ISD::STORE)
8378         goto default_case;
8379
8380     if (ConstantSDNode *C =
8381         dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
8382       // An add of one will be selected as an INC.
8383       if (C->getAPIntValue() == 1) {
8384         Opcode = X86ISD::INC;
8385         NumOperands = 1;
8386         break;
8387       }
8388
8389       // An add of negative one (subtract of one) will be selected as a DEC.
8390       if (C->getAPIntValue().isAllOnesValue()) {
8391         Opcode = X86ISD::DEC;
8392         NumOperands = 1;
8393         break;
8394       }
8395     }
8396
8397     // Otherwise use a regular EFLAGS-setting add.
8398     Opcode = X86ISD::ADD;
8399     NumOperands = 2;
8400     break;
8401   case ISD::AND: {
8402     // If the primary and result isn't used, don't bother using X86ISD::AND,
8403     // because a TEST instruction will be better.
8404     bool NonFlagUse = false;
8405     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8406            UE = Op.getNode()->use_end(); UI != UE; ++UI) {
8407       SDNode *User = *UI;
8408       unsigned UOpNo = UI.getOperandNo();
8409       if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
8410         // Look pass truncate.
8411         UOpNo = User->use_begin().getOperandNo();
8412         User = *User->use_begin();
8413       }
8414
8415       if (User->getOpcode() != ISD::BRCOND &&
8416           User->getOpcode() != ISD::SETCC &&
8417           (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
8418         NonFlagUse = true;
8419         break;
8420       }
8421     }
8422
8423     if (!NonFlagUse)
8424       break;
8425   }
8426     // FALL THROUGH
8427   case ISD::SUB:
8428   case ISD::OR:
8429   case ISD::XOR:
8430     // Due to the ISEL shortcoming noted above, be conservative if this op is
8431     // likely to be selected as part of a load-modify-store instruction.
8432     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
8433            UE = Op.getNode()->use_end(); UI != UE; ++UI)
8434       if (UI->getOpcode() == ISD::STORE)
8435         goto default_case;
8436
8437     // Otherwise use a regular EFLAGS-setting instruction.
8438     switch (Op.getNode()->getOpcode()) {
8439     default: llvm_unreachable("unexpected operator!");
8440     case ISD::SUB: Opcode = X86ISD::SUB; break;
8441     case ISD::OR:  Opcode = X86ISD::OR;  break;
8442     case ISD::XOR: Opcode = X86ISD::XOR; break;
8443     case ISD::AND: Opcode = X86ISD::AND; break;
8444     }
8445
8446     NumOperands = 2;
8447     break;
8448   case X86ISD::ADD:
8449   case X86ISD::SUB:
8450   case X86ISD::INC:
8451   case X86ISD::DEC:
8452   case X86ISD::OR:
8453   case X86ISD::XOR:
8454   case X86ISD::AND:
8455     return SDValue(Op.getNode(), 1);
8456   default:
8457   default_case:
8458     break;
8459   }
8460
8461   if (Opcode == 0)
8462     // Emit a CMP with 0, which is the TEST pattern.
8463     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
8464                        DAG.getConstant(0, Op.getValueType()));
8465
8466   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
8467   SmallVector<SDValue, 4> Ops;
8468   for (unsigned i = 0; i != NumOperands; ++i)
8469     Ops.push_back(Op.getOperand(i));
8470
8471   SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
8472   DAG.ReplaceAllUsesWith(Op, New);
8473   return SDValue(New.getNode(), 1);
8474 }
8475
8476 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
8477 /// equivalent.
8478 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
8479                                    SelectionDAG &DAG) const {
8480   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
8481     if (C->getAPIntValue() == 0)
8482       return EmitTest(Op0, X86CC, DAG);
8483
8484   DebugLoc dl = Op0.getDebugLoc();
8485   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
8486 }
8487
8488 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
8489 /// if it's possible.
8490 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
8491                                      DebugLoc dl, SelectionDAG &DAG) const {
8492   SDValue Op0 = And.getOperand(0);
8493   SDValue Op1 = And.getOperand(1);
8494   if (Op0.getOpcode() == ISD::TRUNCATE)
8495     Op0 = Op0.getOperand(0);
8496   if (Op1.getOpcode() == ISD::TRUNCATE)
8497     Op1 = Op1.getOperand(0);
8498
8499   SDValue LHS, RHS;
8500   if (Op1.getOpcode() == ISD::SHL)
8501     std::swap(Op0, Op1);
8502   if (Op0.getOpcode() == ISD::SHL) {
8503     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
8504       if (And00C->getZExtValue() == 1) {
8505         // If we looked past a truncate, check that it's only truncating away
8506         // known zeros.
8507         unsigned BitWidth = Op0.getValueSizeInBits();
8508         unsigned AndBitWidth = And.getValueSizeInBits();
8509         if (BitWidth > AndBitWidth) {
8510           APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
8511           DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
8512           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
8513             return SDValue();
8514         }
8515         LHS = Op1;
8516         RHS = Op0.getOperand(1);
8517       }
8518   } else if (Op1.getOpcode() == ISD::Constant) {
8519     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
8520     SDValue AndLHS = Op0;
8521     if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
8522       LHS = AndLHS.getOperand(0);
8523       RHS = AndLHS.getOperand(1);
8524     }
8525   }
8526
8527   if (LHS.getNode()) {
8528     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
8529     // instruction.  Since the shift amount is in-range-or-undefined, we know
8530     // that doing a bittest on the i32 value is ok.  We extend to i32 because
8531     // the encoding for the i16 version is larger than the i32 version.
8532     // Also promote i16 to i32 for performance / code size reason.
8533     if (LHS.getValueType() == MVT::i8 ||
8534         LHS.getValueType() == MVT::i16)
8535       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
8536
8537     // If the operand types disagree, extend the shift amount to match.  Since
8538     // BT ignores high bits (like shifts) we can use anyextend.
8539     if (LHS.getValueType() != RHS.getValueType())
8540       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
8541
8542     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
8543     unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
8544     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8545                        DAG.getConstant(Cond, MVT::i8), BT);
8546   }
8547
8548   return SDValue();
8549 }
8550
8551 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
8552
8553   if (Op.getValueType().isVector()) return LowerVSETCC(Op, DAG);
8554
8555   assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
8556   SDValue Op0 = Op.getOperand(0);
8557   SDValue Op1 = Op.getOperand(1);
8558   DebugLoc dl = Op.getDebugLoc();
8559   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8560
8561   // Optimize to BT if possible.
8562   // Lower (X & (1 << N)) == 0 to BT(X, N).
8563   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
8564   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
8565   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
8566       Op1.getOpcode() == ISD::Constant &&
8567       cast<ConstantSDNode>(Op1)->isNullValue() &&
8568       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8569     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
8570     if (NewSetCC.getNode())
8571       return NewSetCC;
8572   }
8573
8574   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
8575   // these.
8576   if (Op1.getOpcode() == ISD::Constant &&
8577       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
8578        cast<ConstantSDNode>(Op1)->isNullValue()) &&
8579       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
8580
8581     // If the input is a setcc, then reuse the input setcc or use a new one with
8582     // the inverted condition.
8583     if (Op0.getOpcode() == X86ISD::SETCC) {
8584       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
8585       bool Invert = (CC == ISD::SETNE) ^
8586         cast<ConstantSDNode>(Op1)->isNullValue();
8587       if (!Invert) return Op0;
8588
8589       CCode = X86::GetOppositeBranchCondition(CCode);
8590       return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8591                          DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
8592     }
8593   }
8594
8595   bool isFP = Op1.getValueType().isFloatingPoint();
8596   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
8597   if (X86CC == X86::COND_INVALID)
8598     return SDValue();
8599
8600   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
8601   return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
8602                      DAG.getConstant(X86CC, MVT::i8), EFLAGS);
8603 }
8604
8605 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
8606 // ones, and then concatenate the result back.
8607 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
8608   EVT VT = Op.getValueType();
8609
8610   assert(VT.getSizeInBits() == 256 && Op.getOpcode() == ISD::SETCC &&
8611          "Unsupported value type for operation");
8612
8613   int NumElems = VT.getVectorNumElements();
8614   DebugLoc dl = Op.getDebugLoc();
8615   SDValue CC = Op.getOperand(2);
8616   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
8617   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
8618
8619   // Extract the LHS vectors
8620   SDValue LHS = Op.getOperand(0);
8621   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
8622   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
8623
8624   // Extract the RHS vectors
8625   SDValue RHS = Op.getOperand(1);
8626   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
8627   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
8628
8629   // Issue the operation on the smaller types and concatenate the result back
8630   MVT EltVT = VT.getVectorElementType().getSimpleVT();
8631   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
8632   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
8633                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
8634                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
8635 }
8636
8637
8638 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
8639   SDValue Cond;
8640   SDValue Op0 = Op.getOperand(0);
8641   SDValue Op1 = Op.getOperand(1);
8642   SDValue CC = Op.getOperand(2);
8643   EVT VT = Op.getValueType();
8644   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
8645   bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
8646   DebugLoc dl = Op.getDebugLoc();
8647
8648   if (isFP) {
8649     unsigned SSECC = 8;
8650     EVT EltVT = Op0.getValueType().getVectorElementType();
8651     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
8652
8653     unsigned Opc = EltVT == MVT::f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
8654     bool Swap = false;
8655
8656     // SSE Condition code mapping:
8657     //  0 - EQ
8658     //  1 - LT
8659     //  2 - LE
8660     //  3 - UNORD
8661     //  4 - NEQ
8662     //  5 - NLT
8663     //  6 - NLE
8664     //  7 - ORD
8665     switch (SetCCOpcode) {
8666     default: break;
8667     case ISD::SETOEQ:
8668     case ISD::SETEQ:  SSECC = 0; break;
8669     case ISD::SETOGT:
8670     case ISD::SETGT: Swap = true; // Fallthrough
8671     case ISD::SETLT:
8672     case ISD::SETOLT: SSECC = 1; break;
8673     case ISD::SETOGE:
8674     case ISD::SETGE: Swap = true; // Fallthrough
8675     case ISD::SETLE:
8676     case ISD::SETOLE: SSECC = 2; break;
8677     case ISD::SETUO:  SSECC = 3; break;
8678     case ISD::SETUNE:
8679     case ISD::SETNE:  SSECC = 4; break;
8680     case ISD::SETULE: Swap = true;
8681     case ISD::SETUGE: SSECC = 5; break;
8682     case ISD::SETULT: Swap = true;
8683     case ISD::SETUGT: SSECC = 6; break;
8684     case ISD::SETO:   SSECC = 7; break;
8685     }
8686     if (Swap)
8687       std::swap(Op0, Op1);
8688
8689     // In the two special cases we can't handle, emit two comparisons.
8690     if (SSECC == 8) {
8691       if (SetCCOpcode == ISD::SETUEQ) {
8692         SDValue UNORD, EQ;
8693         UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
8694         EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
8695         return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
8696       } else if (SetCCOpcode == ISD::SETONE) {
8697         SDValue ORD, NEQ;
8698         ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
8699         NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
8700         return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
8701       }
8702       llvm_unreachable("Illegal FP comparison");
8703     }
8704     // Handle all other FP comparisons here.
8705     return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
8706   }
8707
8708   // Break 256-bit integer vector compare into smaller ones.
8709   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
8710     return Lower256IntVSETCC(Op, DAG);
8711
8712   // We are handling one of the integer comparisons here.  Since SSE only has
8713   // GT and EQ comparisons for integer, swapping operands and multiple
8714   // operations may be required for some comparisons.
8715   unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
8716   bool Swap = false, Invert = false, FlipSigns = false;
8717
8718   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8719   default: break;
8720   case MVT::i8:   EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
8721   case MVT::i16:  EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
8722   case MVT::i32:  EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
8723   case MVT::i64:  EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
8724   }
8725
8726   switch (SetCCOpcode) {
8727   default: break;
8728   case ISD::SETNE:  Invert = true;
8729   case ISD::SETEQ:  Opc = EQOpc; break;
8730   case ISD::SETLT:  Swap = true;
8731   case ISD::SETGT:  Opc = GTOpc; break;
8732   case ISD::SETGE:  Swap = true;
8733   case ISD::SETLE:  Opc = GTOpc; Invert = true; break;
8734   case ISD::SETULT: Swap = true;
8735   case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
8736   case ISD::SETUGE: Swap = true;
8737   case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
8738   }
8739   if (Swap)
8740     std::swap(Op0, Op1);
8741
8742   // Check that the operation in question is available (most are plain SSE2,
8743   // but PCMPGTQ and PCMPEQQ have different requirements).
8744   if (Opc == X86ISD::PCMPGTQ && !Subtarget->hasSSE42() && !Subtarget->hasAVX())
8745     return SDValue();
8746   if (Opc == X86ISD::PCMPEQQ && !Subtarget->hasSSE41() && !Subtarget->hasAVX())
8747     return SDValue();
8748
8749   // Since SSE has no unsigned integer comparisons, we need to flip  the sign
8750   // bits of the inputs before performing those operations.
8751   if (FlipSigns) {
8752     EVT EltVT = VT.getVectorElementType();
8753     SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
8754                                       EltVT);
8755     std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
8756     SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
8757                                     SignBits.size());
8758     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
8759     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
8760   }
8761
8762   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
8763
8764   // If the logical-not of the result is required, perform that now.
8765   if (Invert)
8766     Result = DAG.getNOT(dl, Result, VT);
8767
8768   return Result;
8769 }
8770
8771 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
8772 static bool isX86LogicalCmp(SDValue Op) {
8773   unsigned Opc = Op.getNode()->getOpcode();
8774   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
8775     return true;
8776   if (Op.getResNo() == 1 &&
8777       (Opc == X86ISD::ADD ||
8778        Opc == X86ISD::SUB ||
8779        Opc == X86ISD::ADC ||
8780        Opc == X86ISD::SBB ||
8781        Opc == X86ISD::SMUL ||
8782        Opc == X86ISD::UMUL ||
8783        Opc == X86ISD::INC ||
8784        Opc == X86ISD::DEC ||
8785        Opc == X86ISD::OR ||
8786        Opc == X86ISD::XOR ||
8787        Opc == X86ISD::AND))
8788     return true;
8789
8790   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
8791     return true;
8792
8793   return false;
8794 }
8795
8796 static bool isZero(SDValue V) {
8797   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8798   return C && C->isNullValue();
8799 }
8800
8801 static bool isAllOnes(SDValue V) {
8802   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
8803   return C && C->isAllOnesValue();
8804 }
8805
8806 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8807   bool addTest = true;
8808   SDValue Cond  = Op.getOperand(0);
8809   SDValue Op1 = Op.getOperand(1);
8810   SDValue Op2 = Op.getOperand(2);
8811   DebugLoc DL = Op.getDebugLoc();
8812   SDValue CC;
8813
8814   if (Cond.getOpcode() == ISD::SETCC) {
8815     SDValue NewCond = LowerSETCC(Cond, DAG);
8816     if (NewCond.getNode())
8817       Cond = NewCond;
8818   }
8819
8820   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
8821   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
8822   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
8823   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
8824   if (Cond.getOpcode() == X86ISD::SETCC &&
8825       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
8826       isZero(Cond.getOperand(1).getOperand(1))) {
8827     SDValue Cmp = Cond.getOperand(1);
8828
8829     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
8830
8831     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
8832         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
8833       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
8834
8835       SDValue CmpOp0 = Cmp.getOperand(0);
8836       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
8837                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
8838
8839       SDValue Res =   // Res = 0 or -1.
8840         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8841                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
8842
8843       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
8844         Res = DAG.getNOT(DL, Res, Res.getValueType());
8845
8846       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
8847       if (N2C == 0 || !N2C->isNullValue())
8848         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
8849       return Res;
8850     }
8851   }
8852
8853   // Look past (and (setcc_carry (cmp ...)), 1).
8854   if (Cond.getOpcode() == ISD::AND &&
8855       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
8856     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
8857     if (C && C->getAPIntValue() == 1)
8858       Cond = Cond.getOperand(0);
8859   }
8860
8861   // If condition flag is set by a X86ISD::CMP, then use it as the condition
8862   // setting operand in place of the X86ISD::SETCC.
8863   unsigned CondOpcode = Cond.getOpcode();
8864   if (CondOpcode == X86ISD::SETCC ||
8865       CondOpcode == X86ISD::SETCC_CARRY) {
8866     CC = Cond.getOperand(0);
8867
8868     SDValue Cmp = Cond.getOperand(1);
8869     unsigned Opc = Cmp.getOpcode();
8870     EVT VT = Op.getValueType();
8871
8872     bool IllegalFPCMov = false;
8873     if (VT.isFloatingPoint() && !VT.isVector() &&
8874         !isScalarFPTypeInSSEReg(VT))  // FPStack?
8875       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
8876
8877     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
8878         Opc == X86ISD::BT) { // FIXME
8879       Cond = Cmp;
8880       addTest = false;
8881     }
8882   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
8883              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
8884              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
8885               Cond.getOperand(0).getValueType() != MVT::i8)) {
8886     SDValue LHS = Cond.getOperand(0);
8887     SDValue RHS = Cond.getOperand(1);
8888     unsigned X86Opcode;
8889     unsigned X86Cond;
8890     SDVTList VTs;
8891     switch (CondOpcode) {
8892     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
8893     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
8894     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
8895     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
8896     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
8897     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
8898     default: llvm_unreachable("unexpected overflowing operator");
8899     }
8900     if (CondOpcode == ISD::UMULO)
8901       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
8902                           MVT::i32);
8903     else
8904       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
8905
8906     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
8907
8908     if (CondOpcode == ISD::UMULO)
8909       Cond = X86Op.getValue(2);
8910     else
8911       Cond = X86Op.getValue(1);
8912
8913     CC = DAG.getConstant(X86Cond, MVT::i8);
8914     addTest = false;
8915   }
8916
8917   if (addTest) {
8918     // Look pass the truncate.
8919     if (Cond.getOpcode() == ISD::TRUNCATE)
8920       Cond = Cond.getOperand(0);
8921
8922     // We know the result of AND is compared against zero. Try to match
8923     // it to BT.
8924     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
8925       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
8926       if (NewSetCC.getNode()) {
8927         CC = NewSetCC.getOperand(0);
8928         Cond = NewSetCC.getOperand(1);
8929         addTest = false;
8930       }
8931     }
8932   }
8933
8934   if (addTest) {
8935     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
8936     Cond = EmitTest(Cond, X86::COND_NE, DAG);
8937   }
8938
8939   // a <  b ? -1 :  0 -> RES = ~setcc_carry
8940   // a <  b ?  0 : -1 -> RES = setcc_carry
8941   // a >= b ? -1 :  0 -> RES = setcc_carry
8942   // a >= b ?  0 : -1 -> RES = ~setcc_carry
8943   if (Cond.getOpcode() == X86ISD::CMP) {
8944     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
8945
8946     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
8947         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
8948       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
8949                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
8950       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
8951         return DAG.getNOT(DL, Res, Res.getValueType());
8952       return Res;
8953     }
8954   }
8955
8956   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
8957   // condition is true.
8958   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
8959   SDValue Ops[] = { Op2, Op1, CC, Cond };
8960   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
8961 }
8962
8963 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
8964 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
8965 // from the AND / OR.
8966 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
8967   Opc = Op.getOpcode();
8968   if (Opc != ISD::OR && Opc != ISD::AND)
8969     return false;
8970   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8971           Op.getOperand(0).hasOneUse() &&
8972           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
8973           Op.getOperand(1).hasOneUse());
8974 }
8975
8976 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
8977 // 1 and that the SETCC node has a single use.
8978 static bool isXor1OfSetCC(SDValue Op) {
8979   if (Op.getOpcode() != ISD::XOR)
8980     return false;
8981   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8982   if (N1C && N1C->getAPIntValue() == 1) {
8983     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
8984       Op.getOperand(0).hasOneUse();
8985   }
8986   return false;
8987 }
8988
8989 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
8990   bool addTest = true;
8991   SDValue Chain = Op.getOperand(0);
8992   SDValue Cond  = Op.getOperand(1);
8993   SDValue Dest  = Op.getOperand(2);
8994   DebugLoc dl = Op.getDebugLoc();
8995   SDValue CC;
8996   bool Inverted = false;
8997
8998   if (Cond.getOpcode() == ISD::SETCC) {
8999     // Check for setcc([su]{add,sub,mul}o == 0).
9000     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
9001         isa<ConstantSDNode>(Cond.getOperand(1)) &&
9002         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
9003         Cond.getOperand(0).getResNo() == 1 &&
9004         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
9005          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
9006          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
9007          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
9008          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
9009          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
9010       Inverted = true;
9011       Cond = Cond.getOperand(0);
9012     } else {
9013       SDValue NewCond = LowerSETCC(Cond, DAG);
9014       if (NewCond.getNode())
9015         Cond = NewCond;
9016     }
9017   }
9018 #if 0
9019   // FIXME: LowerXALUO doesn't handle these!!
9020   else if (Cond.getOpcode() == X86ISD::ADD  ||
9021            Cond.getOpcode() == X86ISD::SUB  ||
9022            Cond.getOpcode() == X86ISD::SMUL ||
9023            Cond.getOpcode() == X86ISD::UMUL)
9024     Cond = LowerXALUO(Cond, DAG);
9025 #endif
9026
9027   // Look pass (and (setcc_carry (cmp ...)), 1).
9028   if (Cond.getOpcode() == ISD::AND &&
9029       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
9030     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
9031     if (C && C->getAPIntValue() == 1)
9032       Cond = Cond.getOperand(0);
9033   }
9034
9035   // If condition flag is set by a X86ISD::CMP, then use it as the condition
9036   // setting operand in place of the X86ISD::SETCC.
9037   unsigned CondOpcode = Cond.getOpcode();
9038   if (CondOpcode == X86ISD::SETCC ||
9039       CondOpcode == X86ISD::SETCC_CARRY) {
9040     CC = Cond.getOperand(0);
9041
9042     SDValue Cmp = Cond.getOperand(1);
9043     unsigned Opc = Cmp.getOpcode();
9044     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
9045     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
9046       Cond = Cmp;
9047       addTest = false;
9048     } else {
9049       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
9050       default: break;
9051       case X86::COND_O:
9052       case X86::COND_B:
9053         // These can only come from an arithmetic instruction with overflow,
9054         // e.g. SADDO, UADDO.
9055         Cond = Cond.getNode()->getOperand(1);
9056         addTest = false;
9057         break;
9058       }
9059     }
9060   }
9061   CondOpcode = Cond.getOpcode();
9062   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
9063       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
9064       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
9065        Cond.getOperand(0).getValueType() != MVT::i8)) {
9066     SDValue LHS = Cond.getOperand(0);
9067     SDValue RHS = Cond.getOperand(1);
9068     unsigned X86Opcode;
9069     unsigned X86Cond;
9070     SDVTList VTs;
9071     switch (CondOpcode) {
9072     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
9073     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
9074     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
9075     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
9076     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
9077     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
9078     default: llvm_unreachable("unexpected overflowing operator");
9079     }
9080     if (Inverted)
9081       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
9082     if (CondOpcode == ISD::UMULO)
9083       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
9084                           MVT::i32);
9085     else
9086       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
9087
9088     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
9089
9090     if (CondOpcode == ISD::UMULO)
9091       Cond = X86Op.getValue(2);
9092     else
9093       Cond = X86Op.getValue(1);
9094
9095     CC = DAG.getConstant(X86Cond, MVT::i8);
9096     addTest = false;
9097   } else {
9098     unsigned CondOpc;
9099     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
9100       SDValue Cmp = Cond.getOperand(0).getOperand(1);
9101       if (CondOpc == ISD::OR) {
9102         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
9103         // two branches instead of an explicit OR instruction with a
9104         // separate test.
9105         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9106             isX86LogicalCmp(Cmp)) {
9107           CC = Cond.getOperand(0).getOperand(0);
9108           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9109                               Chain, Dest, CC, Cmp);
9110           CC = Cond.getOperand(1).getOperand(0);
9111           Cond = Cmp;
9112           addTest = false;
9113         }
9114       } else { // ISD::AND
9115         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
9116         // two branches instead of an explicit AND instruction with a
9117         // separate test. However, we only do this if this block doesn't
9118         // have a fall-through edge, because this requires an explicit
9119         // jmp when the condition is false.
9120         if (Cmp == Cond.getOperand(1).getOperand(1) &&
9121             isX86LogicalCmp(Cmp) &&
9122             Op.getNode()->hasOneUse()) {
9123           X86::CondCode CCode =
9124             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9125           CCode = X86::GetOppositeBranchCondition(CCode);
9126           CC = DAG.getConstant(CCode, MVT::i8);
9127           SDNode *User = *Op.getNode()->use_begin();
9128           // Look for an unconditional branch following this conditional branch.
9129           // We need this because we need to reverse the successors in order
9130           // to implement FCMP_OEQ.
9131           if (User->getOpcode() == ISD::BR) {
9132             SDValue FalseBB = User->getOperand(1);
9133             SDNode *NewBR =
9134               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9135             assert(NewBR == User);
9136             (void)NewBR;
9137             Dest = FalseBB;
9138
9139             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9140                                 Chain, Dest, CC, Cmp);
9141             X86::CondCode CCode =
9142               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
9143             CCode = X86::GetOppositeBranchCondition(CCode);
9144             CC = DAG.getConstant(CCode, MVT::i8);
9145             Cond = Cmp;
9146             addTest = false;
9147           }
9148         }
9149       }
9150     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
9151       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
9152       // It should be transformed during dag combiner except when the condition
9153       // is set by a arithmetics with overflow node.
9154       X86::CondCode CCode =
9155         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
9156       CCode = X86::GetOppositeBranchCondition(CCode);
9157       CC = DAG.getConstant(CCode, MVT::i8);
9158       Cond = Cond.getOperand(0).getOperand(1);
9159       addTest = false;
9160     } else if (Cond.getOpcode() == ISD::SETCC &&
9161                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
9162       // For FCMP_OEQ, we can emit
9163       // two branches instead of an explicit AND instruction with a
9164       // separate test. However, we only do this if this block doesn't
9165       // have a fall-through edge, because this requires an explicit
9166       // jmp when the condition is false.
9167       if (Op.getNode()->hasOneUse()) {
9168         SDNode *User = *Op.getNode()->use_begin();
9169         // Look for an unconditional branch following this conditional branch.
9170         // We need this because we need to reverse the successors in order
9171         // to implement FCMP_OEQ.
9172         if (User->getOpcode() == ISD::BR) {
9173           SDValue FalseBB = User->getOperand(1);
9174           SDNode *NewBR =
9175             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9176           assert(NewBR == User);
9177           (void)NewBR;
9178           Dest = FalseBB;
9179
9180           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9181                                     Cond.getOperand(0), Cond.getOperand(1));
9182           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9183           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9184                               Chain, Dest, CC, Cmp);
9185           CC = DAG.getConstant(X86::COND_P, MVT::i8);
9186           Cond = Cmp;
9187           addTest = false;
9188         }
9189       }
9190     } else if (Cond.getOpcode() == ISD::SETCC &&
9191                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
9192       // For FCMP_UNE, we can emit
9193       // two branches instead of an explicit AND instruction with a
9194       // separate test. However, we only do this if this block doesn't
9195       // have a fall-through edge, because this requires an explicit
9196       // jmp when the condition is false.
9197       if (Op.getNode()->hasOneUse()) {
9198         SDNode *User = *Op.getNode()->use_begin();
9199         // Look for an unconditional branch following this conditional branch.
9200         // We need this because we need to reverse the successors in order
9201         // to implement FCMP_UNE.
9202         if (User->getOpcode() == ISD::BR) {
9203           SDValue FalseBB = User->getOperand(1);
9204           SDNode *NewBR =
9205             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
9206           assert(NewBR == User);
9207           (void)NewBR;
9208
9209           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9210                                     Cond.getOperand(0), Cond.getOperand(1));
9211           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9212           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9213                               Chain, Dest, CC, Cmp);
9214           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
9215           Cond = Cmp;
9216           addTest = false;
9217           Dest = FalseBB;
9218         }
9219       }
9220     }
9221   }
9222
9223   if (addTest) {
9224     // Look pass the truncate.
9225     if (Cond.getOpcode() == ISD::TRUNCATE)
9226       Cond = Cond.getOperand(0);
9227
9228     // We know the result of AND is compared against zero. Try to match
9229     // it to BT.
9230     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
9231       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
9232       if (NewSetCC.getNode()) {
9233         CC = NewSetCC.getOperand(0);
9234         Cond = NewSetCC.getOperand(1);
9235         addTest = false;
9236       }
9237     }
9238   }
9239
9240   if (addTest) {
9241     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9242     Cond = EmitTest(Cond, X86::COND_NE, DAG);
9243   }
9244   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
9245                      Chain, Dest, CC, Cond);
9246 }
9247
9248
9249 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
9250 // Calls to _alloca is needed to probe the stack when allocating more than 4k
9251 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
9252 // that the guard pages used by the OS virtual memory manager are allocated in
9253 // correct sequence.
9254 SDValue
9255 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
9256                                            SelectionDAG &DAG) const {
9257   assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows() ||
9258           EnableSegmentedStacks) &&
9259          "This should be used only on Windows targets or when segmented stacks "
9260          "are being used");
9261   assert(!Subtarget->isTargetEnvMacho() && "Not implemented");
9262   DebugLoc dl = Op.getDebugLoc();
9263
9264   // Get the inputs.
9265   SDValue Chain = Op.getOperand(0);
9266   SDValue Size  = Op.getOperand(1);
9267   // FIXME: Ensure alignment here
9268
9269   bool Is64Bit = Subtarget->is64Bit();
9270   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
9271
9272   if (EnableSegmentedStacks) {
9273     MachineFunction &MF = DAG.getMachineFunction();
9274     MachineRegisterInfo &MRI = MF.getRegInfo();
9275
9276     if (Is64Bit) {
9277       // The 64 bit implementation of segmented stacks needs to clobber both r10
9278       // r11. This makes it impossible to use it along with nested parameters.
9279       const Function *F = MF.getFunction();
9280
9281       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
9282            I != E; I++)
9283         if (I->hasNestAttr())
9284           report_fatal_error("Cannot use segmented stacks with functions that "
9285                              "have nested arguments.");
9286     }
9287
9288     const TargetRegisterClass *AddrRegClass =
9289       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
9290     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
9291     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
9292     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
9293                                 DAG.getRegister(Vreg, SPTy));
9294     SDValue Ops1[2] = { Value, Chain };
9295     return DAG.getMergeValues(Ops1, 2, dl);
9296   } else {
9297     SDValue Flag;
9298     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
9299
9300     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
9301     Flag = Chain.getValue(1);
9302     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9303
9304     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
9305     Flag = Chain.getValue(1);
9306
9307     Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
9308
9309     SDValue Ops1[2] = { Chain.getValue(0), Chain };
9310     return DAG.getMergeValues(Ops1, 2, dl);
9311   }
9312 }
9313
9314 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
9315   MachineFunction &MF = DAG.getMachineFunction();
9316   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
9317
9318   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9319   DebugLoc DL = Op.getDebugLoc();
9320
9321   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
9322     // vastart just stores the address of the VarArgsFrameIndex slot into the
9323     // memory location argument.
9324     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9325                                    getPointerTy());
9326     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
9327                         MachinePointerInfo(SV), false, false, 0);
9328   }
9329
9330   // __va_list_tag:
9331   //   gp_offset         (0 - 6 * 8)
9332   //   fp_offset         (48 - 48 + 8 * 16)
9333   //   overflow_arg_area (point to parameters coming in memory).
9334   //   reg_save_area
9335   SmallVector<SDValue, 8> MemOps;
9336   SDValue FIN = Op.getOperand(1);
9337   // Store gp_offset
9338   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
9339                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
9340                                                MVT::i32),
9341                                FIN, MachinePointerInfo(SV), false, false, 0);
9342   MemOps.push_back(Store);
9343
9344   // Store fp_offset
9345   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9346                     FIN, DAG.getIntPtrConstant(4));
9347   Store = DAG.getStore(Op.getOperand(0), DL,
9348                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
9349                                        MVT::i32),
9350                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
9351   MemOps.push_back(Store);
9352
9353   // Store ptr to overflow_arg_area
9354   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9355                     FIN, DAG.getIntPtrConstant(4));
9356   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
9357                                     getPointerTy());
9358   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
9359                        MachinePointerInfo(SV, 8),
9360                        false, false, 0);
9361   MemOps.push_back(Store);
9362
9363   // Store ptr to reg_save_area.
9364   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9365                     FIN, DAG.getIntPtrConstant(8));
9366   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
9367                                     getPointerTy());
9368   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
9369                        MachinePointerInfo(SV, 16), false, false, 0);
9370   MemOps.push_back(Store);
9371   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
9372                      &MemOps[0], MemOps.size());
9373 }
9374
9375 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
9376   assert(Subtarget->is64Bit() &&
9377          "LowerVAARG only handles 64-bit va_arg!");
9378   assert((Subtarget->isTargetLinux() ||
9379           Subtarget->isTargetDarwin()) &&
9380           "Unhandled target in LowerVAARG");
9381   assert(Op.getNode()->getNumOperands() == 4);
9382   SDValue Chain = Op.getOperand(0);
9383   SDValue SrcPtr = Op.getOperand(1);
9384   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
9385   unsigned Align = Op.getConstantOperandVal(3);
9386   DebugLoc dl = Op.getDebugLoc();
9387
9388   EVT ArgVT = Op.getNode()->getValueType(0);
9389   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9390   uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
9391   uint8_t ArgMode;
9392
9393   // Decide which area this value should be read from.
9394   // TODO: Implement the AMD64 ABI in its entirety. This simple
9395   // selection mechanism works only for the basic types.
9396   if (ArgVT == MVT::f80) {
9397     llvm_unreachable("va_arg for f80 not yet implemented");
9398   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
9399     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
9400   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
9401     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
9402   } else {
9403     llvm_unreachable("Unhandled argument type in LowerVAARG");
9404   }
9405
9406   if (ArgMode == 2) {
9407     // Sanity Check: Make sure using fp_offset makes sense.
9408     assert(!UseSoftFloat &&
9409            !(DAG.getMachineFunction()
9410                 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
9411            Subtarget->hasXMM());
9412   }
9413
9414   // Insert VAARG_64 node into the DAG
9415   // VAARG_64 returns two values: Variable Argument Address, Chain
9416   SmallVector<SDValue, 11> InstOps;
9417   InstOps.push_back(Chain);
9418   InstOps.push_back(SrcPtr);
9419   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
9420   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
9421   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
9422   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
9423   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
9424                                           VTs, &InstOps[0], InstOps.size(),
9425                                           MVT::i64,
9426                                           MachinePointerInfo(SV),
9427                                           /*Align=*/0,
9428                                           /*Volatile=*/false,
9429                                           /*ReadMem=*/true,
9430                                           /*WriteMem=*/true);
9431   Chain = VAARG.getValue(1);
9432
9433   // Load the next argument and return it
9434   return DAG.getLoad(ArgVT, dl,
9435                      Chain,
9436                      VAARG,
9437                      MachinePointerInfo(),
9438                      false, false, false, 0);
9439 }
9440
9441 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
9442   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
9443   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
9444   SDValue Chain = Op.getOperand(0);
9445   SDValue DstPtr = Op.getOperand(1);
9446   SDValue SrcPtr = Op.getOperand(2);
9447   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
9448   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9449   DebugLoc DL = Op.getDebugLoc();
9450
9451   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
9452                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
9453                        false,
9454                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
9455 }
9456
9457 SDValue
9458 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
9459   DebugLoc dl = Op.getDebugLoc();
9460   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9461   switch (IntNo) {
9462   default: return SDValue();    // Don't custom lower most intrinsics.
9463   // Comparison intrinsics.
9464   case Intrinsic::x86_sse_comieq_ss:
9465   case Intrinsic::x86_sse_comilt_ss:
9466   case Intrinsic::x86_sse_comile_ss:
9467   case Intrinsic::x86_sse_comigt_ss:
9468   case Intrinsic::x86_sse_comige_ss:
9469   case Intrinsic::x86_sse_comineq_ss:
9470   case Intrinsic::x86_sse_ucomieq_ss:
9471   case Intrinsic::x86_sse_ucomilt_ss:
9472   case Intrinsic::x86_sse_ucomile_ss:
9473   case Intrinsic::x86_sse_ucomigt_ss:
9474   case Intrinsic::x86_sse_ucomige_ss:
9475   case Intrinsic::x86_sse_ucomineq_ss:
9476   case Intrinsic::x86_sse2_comieq_sd:
9477   case Intrinsic::x86_sse2_comilt_sd:
9478   case Intrinsic::x86_sse2_comile_sd:
9479   case Intrinsic::x86_sse2_comigt_sd:
9480   case Intrinsic::x86_sse2_comige_sd:
9481   case Intrinsic::x86_sse2_comineq_sd:
9482   case Intrinsic::x86_sse2_ucomieq_sd:
9483   case Intrinsic::x86_sse2_ucomilt_sd:
9484   case Intrinsic::x86_sse2_ucomile_sd:
9485   case Intrinsic::x86_sse2_ucomigt_sd:
9486   case Intrinsic::x86_sse2_ucomige_sd:
9487   case Intrinsic::x86_sse2_ucomineq_sd: {
9488     unsigned Opc = 0;
9489     ISD::CondCode CC = ISD::SETCC_INVALID;
9490     switch (IntNo) {
9491     default: break;
9492     case Intrinsic::x86_sse_comieq_ss:
9493     case Intrinsic::x86_sse2_comieq_sd:
9494       Opc = X86ISD::COMI;
9495       CC = ISD::SETEQ;
9496       break;
9497     case Intrinsic::x86_sse_comilt_ss:
9498     case Intrinsic::x86_sse2_comilt_sd:
9499       Opc = X86ISD::COMI;
9500       CC = ISD::SETLT;
9501       break;
9502     case Intrinsic::x86_sse_comile_ss:
9503     case Intrinsic::x86_sse2_comile_sd:
9504       Opc = X86ISD::COMI;
9505       CC = ISD::SETLE;
9506       break;
9507     case Intrinsic::x86_sse_comigt_ss:
9508     case Intrinsic::x86_sse2_comigt_sd:
9509       Opc = X86ISD::COMI;
9510       CC = ISD::SETGT;
9511       break;
9512     case Intrinsic::x86_sse_comige_ss:
9513     case Intrinsic::x86_sse2_comige_sd:
9514       Opc = X86ISD::COMI;
9515       CC = ISD::SETGE;
9516       break;
9517     case Intrinsic::x86_sse_comineq_ss:
9518     case Intrinsic::x86_sse2_comineq_sd:
9519       Opc = X86ISD::COMI;
9520       CC = ISD::SETNE;
9521       break;
9522     case Intrinsic::x86_sse_ucomieq_ss:
9523     case Intrinsic::x86_sse2_ucomieq_sd:
9524       Opc = X86ISD::UCOMI;
9525       CC = ISD::SETEQ;
9526       break;
9527     case Intrinsic::x86_sse_ucomilt_ss:
9528     case Intrinsic::x86_sse2_ucomilt_sd:
9529       Opc = X86ISD::UCOMI;
9530       CC = ISD::SETLT;
9531       break;
9532     case Intrinsic::x86_sse_ucomile_ss:
9533     case Intrinsic::x86_sse2_ucomile_sd:
9534       Opc = X86ISD::UCOMI;
9535       CC = ISD::SETLE;
9536       break;
9537     case Intrinsic::x86_sse_ucomigt_ss:
9538     case Intrinsic::x86_sse2_ucomigt_sd:
9539       Opc = X86ISD::UCOMI;
9540       CC = ISD::SETGT;
9541       break;
9542     case Intrinsic::x86_sse_ucomige_ss:
9543     case Intrinsic::x86_sse2_ucomige_sd:
9544       Opc = X86ISD::UCOMI;
9545       CC = ISD::SETGE;
9546       break;
9547     case Intrinsic::x86_sse_ucomineq_ss:
9548     case Intrinsic::x86_sse2_ucomineq_sd:
9549       Opc = X86ISD::UCOMI;
9550       CC = ISD::SETNE;
9551       break;
9552     }
9553
9554     SDValue LHS = Op.getOperand(1);
9555     SDValue RHS = Op.getOperand(2);
9556     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
9557     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
9558     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
9559     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
9560                                 DAG.getConstant(X86CC, MVT::i8), Cond);
9561     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9562   }
9563   // Arithmetic intrinsics.
9564   case Intrinsic::x86_sse3_hadd_ps:
9565   case Intrinsic::x86_sse3_hadd_pd:
9566   case Intrinsic::x86_avx_hadd_ps_256:
9567   case Intrinsic::x86_avx_hadd_pd_256:
9568     return DAG.getNode(X86ISD::FHADD, dl, Op.getValueType(),
9569                        Op.getOperand(1), Op.getOperand(2));
9570   case Intrinsic::x86_sse3_hsub_ps:
9571   case Intrinsic::x86_sse3_hsub_pd:
9572   case Intrinsic::x86_avx_hsub_ps_256:
9573   case Intrinsic::x86_avx_hsub_pd_256:
9574     return DAG.getNode(X86ISD::FHSUB, dl, Op.getValueType(),
9575                        Op.getOperand(1), Op.getOperand(2));
9576   case Intrinsic::x86_avx2_psllv_d:
9577   case Intrinsic::x86_avx2_psllv_q:
9578   case Intrinsic::x86_avx2_psllv_d_256:
9579   case Intrinsic::x86_avx2_psllv_q_256:
9580     return DAG.getNode(ISD::SHL, dl, Op.getValueType(),
9581                       Op.getOperand(1), Op.getOperand(2));
9582   case Intrinsic::x86_avx2_psrlv_d:
9583   case Intrinsic::x86_avx2_psrlv_q:
9584   case Intrinsic::x86_avx2_psrlv_d_256:
9585   case Intrinsic::x86_avx2_psrlv_q_256:
9586     return DAG.getNode(ISD::SRL, dl, Op.getValueType(),
9587                       Op.getOperand(1), Op.getOperand(2));
9588   case Intrinsic::x86_avx2_psrav_d:
9589   case Intrinsic::x86_avx2_psrav_d_256:
9590     return DAG.getNode(ISD::SRA, dl, Op.getValueType(),
9591                       Op.getOperand(1), Op.getOperand(2));
9592
9593   // ptest and testp intrinsics. The intrinsic these come from are designed to
9594   // return an integer value, not just an instruction so lower it to the ptest
9595   // or testp pattern and a setcc for the result.
9596   case Intrinsic::x86_sse41_ptestz:
9597   case Intrinsic::x86_sse41_ptestc:
9598   case Intrinsic::x86_sse41_ptestnzc:
9599   case Intrinsic::x86_avx_ptestz_256:
9600   case Intrinsic::x86_avx_ptestc_256:
9601   case Intrinsic::x86_avx_ptestnzc_256:
9602   case Intrinsic::x86_avx_vtestz_ps:
9603   case Intrinsic::x86_avx_vtestc_ps:
9604   case Intrinsic::x86_avx_vtestnzc_ps:
9605   case Intrinsic::x86_avx_vtestz_pd:
9606   case Intrinsic::x86_avx_vtestc_pd:
9607   case Intrinsic::x86_avx_vtestnzc_pd:
9608   case Intrinsic::x86_avx_vtestz_ps_256:
9609   case Intrinsic::x86_avx_vtestc_ps_256:
9610   case Intrinsic::x86_avx_vtestnzc_ps_256:
9611   case Intrinsic::x86_avx_vtestz_pd_256:
9612   case Intrinsic::x86_avx_vtestc_pd_256:
9613   case Intrinsic::x86_avx_vtestnzc_pd_256: {
9614     bool IsTestPacked = false;
9615     unsigned X86CC = 0;
9616     switch (IntNo) {
9617     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
9618     case Intrinsic::x86_avx_vtestz_ps:
9619     case Intrinsic::x86_avx_vtestz_pd:
9620     case Intrinsic::x86_avx_vtestz_ps_256:
9621     case Intrinsic::x86_avx_vtestz_pd_256:
9622       IsTestPacked = true; // Fallthrough
9623     case Intrinsic::x86_sse41_ptestz:
9624     case Intrinsic::x86_avx_ptestz_256:
9625       // ZF = 1
9626       X86CC = X86::COND_E;
9627       break;
9628     case Intrinsic::x86_avx_vtestc_ps:
9629     case Intrinsic::x86_avx_vtestc_pd:
9630     case Intrinsic::x86_avx_vtestc_ps_256:
9631     case Intrinsic::x86_avx_vtestc_pd_256:
9632       IsTestPacked = true; // Fallthrough
9633     case Intrinsic::x86_sse41_ptestc:
9634     case Intrinsic::x86_avx_ptestc_256:
9635       // CF = 1
9636       X86CC = X86::COND_B;
9637       break;
9638     case Intrinsic::x86_avx_vtestnzc_ps:
9639     case Intrinsic::x86_avx_vtestnzc_pd:
9640     case Intrinsic::x86_avx_vtestnzc_ps_256:
9641     case Intrinsic::x86_avx_vtestnzc_pd_256:
9642       IsTestPacked = true; // Fallthrough
9643     case Intrinsic::x86_sse41_ptestnzc:
9644     case Intrinsic::x86_avx_ptestnzc_256:
9645       // ZF and CF = 0
9646       X86CC = X86::COND_A;
9647       break;
9648     }
9649
9650     SDValue LHS = Op.getOperand(1);
9651     SDValue RHS = Op.getOperand(2);
9652     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
9653     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
9654     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
9655     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
9656     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
9657   }
9658
9659   // Fix vector shift instructions where the last operand is a non-immediate
9660   // i32 value.
9661   case Intrinsic::x86_avx2_pslli_w:
9662   case Intrinsic::x86_avx2_pslli_d:
9663   case Intrinsic::x86_avx2_pslli_q:
9664   case Intrinsic::x86_avx2_psrli_w:
9665   case Intrinsic::x86_avx2_psrli_d:
9666   case Intrinsic::x86_avx2_psrli_q:
9667   case Intrinsic::x86_avx2_psrai_w:
9668   case Intrinsic::x86_avx2_psrai_d:
9669   case Intrinsic::x86_sse2_pslli_w:
9670   case Intrinsic::x86_sse2_pslli_d:
9671   case Intrinsic::x86_sse2_pslli_q:
9672   case Intrinsic::x86_sse2_psrli_w:
9673   case Intrinsic::x86_sse2_psrli_d:
9674   case Intrinsic::x86_sse2_psrli_q:
9675   case Intrinsic::x86_sse2_psrai_w:
9676   case Intrinsic::x86_sse2_psrai_d:
9677   case Intrinsic::x86_mmx_pslli_w:
9678   case Intrinsic::x86_mmx_pslli_d:
9679   case Intrinsic::x86_mmx_pslli_q:
9680   case Intrinsic::x86_mmx_psrli_w:
9681   case Intrinsic::x86_mmx_psrli_d:
9682   case Intrinsic::x86_mmx_psrli_q:
9683   case Intrinsic::x86_mmx_psrai_w:
9684   case Intrinsic::x86_mmx_psrai_d: {
9685     SDValue ShAmt = Op.getOperand(2);
9686     if (isa<ConstantSDNode>(ShAmt))
9687       return SDValue();
9688
9689     unsigned NewIntNo = 0;
9690     EVT ShAmtVT = MVT::v4i32;
9691     switch (IntNo) {
9692     case Intrinsic::x86_sse2_pslli_w:
9693       NewIntNo = Intrinsic::x86_sse2_psll_w;
9694       break;
9695     case Intrinsic::x86_sse2_pslli_d:
9696       NewIntNo = Intrinsic::x86_sse2_psll_d;
9697       break;
9698     case Intrinsic::x86_sse2_pslli_q:
9699       NewIntNo = Intrinsic::x86_sse2_psll_q;
9700       break;
9701     case Intrinsic::x86_sse2_psrli_w:
9702       NewIntNo = Intrinsic::x86_sse2_psrl_w;
9703       break;
9704     case Intrinsic::x86_sse2_psrli_d:
9705       NewIntNo = Intrinsic::x86_sse2_psrl_d;
9706       break;
9707     case Intrinsic::x86_sse2_psrli_q:
9708       NewIntNo = Intrinsic::x86_sse2_psrl_q;
9709       break;
9710     case Intrinsic::x86_sse2_psrai_w:
9711       NewIntNo = Intrinsic::x86_sse2_psra_w;
9712       break;
9713     case Intrinsic::x86_sse2_psrai_d:
9714       NewIntNo = Intrinsic::x86_sse2_psra_d;
9715       break;
9716     case Intrinsic::x86_avx2_pslli_w:
9717       NewIntNo = Intrinsic::x86_avx2_psll_w;
9718       break;
9719     case Intrinsic::x86_avx2_pslli_d:
9720       NewIntNo = Intrinsic::x86_avx2_psll_d;
9721       break;
9722     case Intrinsic::x86_avx2_pslli_q:
9723       NewIntNo = Intrinsic::x86_avx2_psll_q;
9724       break;
9725     case Intrinsic::x86_avx2_psrli_w:
9726       NewIntNo = Intrinsic::x86_avx2_psrl_w;
9727       break;
9728     case Intrinsic::x86_avx2_psrli_d:
9729       NewIntNo = Intrinsic::x86_avx2_psrl_d;
9730       break;
9731     case Intrinsic::x86_avx2_psrli_q:
9732       NewIntNo = Intrinsic::x86_avx2_psrl_q;
9733       break;
9734     case Intrinsic::x86_avx2_psrai_w:
9735       NewIntNo = Intrinsic::x86_avx2_psra_w;
9736       break;
9737     case Intrinsic::x86_avx2_psrai_d:
9738       NewIntNo = Intrinsic::x86_avx2_psra_d;
9739       break;
9740     default: {
9741       ShAmtVT = MVT::v2i32;
9742       switch (IntNo) {
9743       case Intrinsic::x86_mmx_pslli_w:
9744         NewIntNo = Intrinsic::x86_mmx_psll_w;
9745         break;
9746       case Intrinsic::x86_mmx_pslli_d:
9747         NewIntNo = Intrinsic::x86_mmx_psll_d;
9748         break;
9749       case Intrinsic::x86_mmx_pslli_q:
9750         NewIntNo = Intrinsic::x86_mmx_psll_q;
9751         break;
9752       case Intrinsic::x86_mmx_psrli_w:
9753         NewIntNo = Intrinsic::x86_mmx_psrl_w;
9754         break;
9755       case Intrinsic::x86_mmx_psrli_d:
9756         NewIntNo = Intrinsic::x86_mmx_psrl_d;
9757         break;
9758       case Intrinsic::x86_mmx_psrli_q:
9759         NewIntNo = Intrinsic::x86_mmx_psrl_q;
9760         break;
9761       case Intrinsic::x86_mmx_psrai_w:
9762         NewIntNo = Intrinsic::x86_mmx_psra_w;
9763         break;
9764       case Intrinsic::x86_mmx_psrai_d:
9765         NewIntNo = Intrinsic::x86_mmx_psra_d;
9766         break;
9767       default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
9768       }
9769       break;
9770     }
9771     }
9772
9773     // The vector shift intrinsics with scalars uses 32b shift amounts but
9774     // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
9775     // to be zero.
9776     SDValue ShOps[4];
9777     ShOps[0] = ShAmt;
9778     ShOps[1] = DAG.getConstant(0, MVT::i32);
9779     if (ShAmtVT == MVT::v4i32) {
9780       ShOps[2] = DAG.getUNDEF(MVT::i32);
9781       ShOps[3] = DAG.getUNDEF(MVT::i32);
9782       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
9783     } else {
9784       ShAmt =  DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
9785 // FIXME this must be lowered to get rid of the invalid type.
9786     }
9787
9788     EVT VT = Op.getValueType();
9789     ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
9790     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
9791                        DAG.getConstant(NewIntNo, MVT::i32),
9792                        Op.getOperand(1), ShAmt);
9793   }
9794   }
9795 }
9796
9797 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
9798                                            SelectionDAG &DAG) const {
9799   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9800   MFI->setReturnAddressIsTaken(true);
9801
9802   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9803   DebugLoc dl = Op.getDebugLoc();
9804
9805   if (Depth > 0) {
9806     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9807     SDValue Offset =
9808       DAG.getConstant(TD->getPointerSize(),
9809                       Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
9810     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9811                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9812                                    FrameAddr, Offset),
9813                        MachinePointerInfo(), false, false, false, 0);
9814   }
9815
9816   // Just load the return address.
9817   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
9818   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9819                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9820 }
9821
9822 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
9823   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9824   MFI->setFrameAddressIsTaken(true);
9825
9826   EVT VT = Op.getValueType();
9827   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
9828   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9829   unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
9830   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
9831   while (Depth--)
9832     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
9833                             MachinePointerInfo(),
9834                             false, false, false, 0);
9835   return FrameAddr;
9836 }
9837
9838 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
9839                                                      SelectionDAG &DAG) const {
9840   return DAG.getIntPtrConstant(2*TD->getPointerSize());
9841 }
9842
9843 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
9844   MachineFunction &MF = DAG.getMachineFunction();
9845   SDValue Chain     = Op.getOperand(0);
9846   SDValue Offset    = Op.getOperand(1);
9847   SDValue Handler   = Op.getOperand(2);
9848   DebugLoc dl       = Op.getDebugLoc();
9849
9850   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
9851                                      Subtarget->is64Bit() ? X86::RBP : X86::EBP,
9852                                      getPointerTy());
9853   unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
9854
9855   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
9856                                   DAG.getIntPtrConstant(TD->getPointerSize()));
9857   StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
9858   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
9859                        false, false, 0);
9860   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
9861   MF.getRegInfo().addLiveOut(StoreAddrReg);
9862
9863   return DAG.getNode(X86ISD::EH_RETURN, dl,
9864                      MVT::Other,
9865                      Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
9866 }
9867
9868 SDValue X86TargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
9869                                                   SelectionDAG &DAG) const {
9870   return Op.getOperand(0);
9871 }
9872
9873 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
9874                                                 SelectionDAG &DAG) const {
9875   SDValue Root = Op.getOperand(0);
9876   SDValue Trmp = Op.getOperand(1); // trampoline
9877   SDValue FPtr = Op.getOperand(2); // nested function
9878   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
9879   DebugLoc dl  = Op.getDebugLoc();
9880
9881   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
9882
9883   if (Subtarget->is64Bit()) {
9884     SDValue OutChains[6];
9885
9886     // Large code-model.
9887     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
9888     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
9889
9890     const unsigned char N86R10 = X86_MC::getX86RegNum(X86::R10);
9891     const unsigned char N86R11 = X86_MC::getX86RegNum(X86::R11);
9892
9893     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
9894
9895     // Load the pointer to the nested function into R11.
9896     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
9897     SDValue Addr = Trmp;
9898     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9899                                 Addr, MachinePointerInfo(TrmpAddr),
9900                                 false, false, 0);
9901
9902     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9903                        DAG.getConstant(2, MVT::i64));
9904     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
9905                                 MachinePointerInfo(TrmpAddr, 2),
9906                                 false, false, 2);
9907
9908     // Load the 'nest' parameter value into R10.
9909     // R10 is specified in X86CallingConv.td
9910     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
9911     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9912                        DAG.getConstant(10, MVT::i64));
9913     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9914                                 Addr, MachinePointerInfo(TrmpAddr, 10),
9915                                 false, false, 0);
9916
9917     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9918                        DAG.getConstant(12, MVT::i64));
9919     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
9920                                 MachinePointerInfo(TrmpAddr, 12),
9921                                 false, false, 2);
9922
9923     // Jump to the nested function.
9924     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
9925     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9926                        DAG.getConstant(20, MVT::i64));
9927     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
9928                                 Addr, MachinePointerInfo(TrmpAddr, 20),
9929                                 false, false, 0);
9930
9931     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
9932     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
9933                        DAG.getConstant(22, MVT::i64));
9934     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
9935                                 MachinePointerInfo(TrmpAddr, 22),
9936                                 false, false, 0);
9937
9938     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6);
9939   } else {
9940     const Function *Func =
9941       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
9942     CallingConv::ID CC = Func->getCallingConv();
9943     unsigned NestReg;
9944
9945     switch (CC) {
9946     default:
9947       llvm_unreachable("Unsupported calling convention");
9948     case CallingConv::C:
9949     case CallingConv::X86_StdCall: {
9950       // Pass 'nest' parameter in ECX.
9951       // Must be kept in sync with X86CallingConv.td
9952       NestReg = X86::ECX;
9953
9954       // Check that ECX wasn't needed by an 'inreg' parameter.
9955       FunctionType *FTy = Func->getFunctionType();
9956       const AttrListPtr &Attrs = Func->getAttributes();
9957
9958       if (!Attrs.isEmpty() && !Func->isVarArg()) {
9959         unsigned InRegCount = 0;
9960         unsigned Idx = 1;
9961
9962         for (FunctionType::param_iterator I = FTy->param_begin(),
9963              E = FTy->param_end(); I != E; ++I, ++Idx)
9964           if (Attrs.paramHasAttr(Idx, Attribute::InReg))
9965             // FIXME: should only count parameters that are lowered to integers.
9966             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
9967
9968         if (InRegCount > 2) {
9969           report_fatal_error("Nest register in use - reduce number of inreg"
9970                              " parameters!");
9971         }
9972       }
9973       break;
9974     }
9975     case CallingConv::X86_FastCall:
9976     case CallingConv::X86_ThisCall:
9977     case CallingConv::Fast:
9978       // Pass 'nest' parameter in EAX.
9979       // Must be kept in sync with X86CallingConv.td
9980       NestReg = X86::EAX;
9981       break;
9982     }
9983
9984     SDValue OutChains[4];
9985     SDValue Addr, Disp;
9986
9987     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
9988                        DAG.getConstant(10, MVT::i32));
9989     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
9990
9991     // This is storing the opcode for MOV32ri.
9992     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
9993     const unsigned char N86Reg = X86_MC::getX86RegNum(NestReg);
9994     OutChains[0] = DAG.getStore(Root, dl,
9995                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
9996                                 Trmp, MachinePointerInfo(TrmpAddr),
9997                                 false, false, 0);
9998
9999     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10000                        DAG.getConstant(1, MVT::i32));
10001     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
10002                                 MachinePointerInfo(TrmpAddr, 1),
10003                                 false, false, 1);
10004
10005     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
10006     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10007                        DAG.getConstant(5, MVT::i32));
10008     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
10009                                 MachinePointerInfo(TrmpAddr, 5),
10010                                 false, false, 1);
10011
10012     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
10013                        DAG.getConstant(6, MVT::i32));
10014     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
10015                                 MachinePointerInfo(TrmpAddr, 6),
10016                                 false, false, 1);
10017
10018     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4);
10019   }
10020 }
10021
10022 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
10023                                             SelectionDAG &DAG) const {
10024   /*
10025    The rounding mode is in bits 11:10 of FPSR, and has the following
10026    settings:
10027      00 Round to nearest
10028      01 Round to -inf
10029      10 Round to +inf
10030      11 Round to 0
10031
10032   FLT_ROUNDS, on the other hand, expects the following:
10033     -1 Undefined
10034      0 Round to 0
10035      1 Round to nearest
10036      2 Round to +inf
10037      3 Round to -inf
10038
10039   To perform the conversion, we do:
10040     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
10041   */
10042
10043   MachineFunction &MF = DAG.getMachineFunction();
10044   const TargetMachine &TM = MF.getTarget();
10045   const TargetFrameLowering &TFI = *TM.getFrameLowering();
10046   unsigned StackAlignment = TFI.getStackAlignment();
10047   EVT VT = Op.getValueType();
10048   DebugLoc DL = Op.getDebugLoc();
10049
10050   // Save FP Control Word to stack slot
10051   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
10052   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10053
10054
10055   MachineMemOperand *MMO =
10056    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10057                            MachineMemOperand::MOStore, 2, 2);
10058
10059   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
10060   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
10061                                           DAG.getVTList(MVT::Other),
10062                                           Ops, 2, MVT::i16, MMO);
10063
10064   // Load FP Control Word from stack slot
10065   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
10066                             MachinePointerInfo(), false, false, false, 0);
10067
10068   // Transform as necessary
10069   SDValue CWD1 =
10070     DAG.getNode(ISD::SRL, DL, MVT::i16,
10071                 DAG.getNode(ISD::AND, DL, MVT::i16,
10072                             CWD, DAG.getConstant(0x800, MVT::i16)),
10073                 DAG.getConstant(11, MVT::i8));
10074   SDValue CWD2 =
10075     DAG.getNode(ISD::SRL, DL, MVT::i16,
10076                 DAG.getNode(ISD::AND, DL, MVT::i16,
10077                             CWD, DAG.getConstant(0x400, MVT::i16)),
10078                 DAG.getConstant(9, MVT::i8));
10079
10080   SDValue RetVal =
10081     DAG.getNode(ISD::AND, DL, MVT::i16,
10082                 DAG.getNode(ISD::ADD, DL, MVT::i16,
10083                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
10084                             DAG.getConstant(1, MVT::i16)),
10085                 DAG.getConstant(3, MVT::i16));
10086
10087
10088   return DAG.getNode((VT.getSizeInBits() < 16 ?
10089                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
10090 }
10091
10092 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
10093   EVT VT = Op.getValueType();
10094   EVT OpVT = VT;
10095   unsigned NumBits = VT.getSizeInBits();
10096   DebugLoc dl = Op.getDebugLoc();
10097
10098   Op = Op.getOperand(0);
10099   if (VT == MVT::i8) {
10100     // Zero extend to i32 since there is not an i8 bsr.
10101     OpVT = MVT::i32;
10102     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10103   }
10104
10105   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
10106   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10107   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
10108
10109   // If src is zero (i.e. bsr sets ZF), returns NumBits.
10110   SDValue Ops[] = {
10111     Op,
10112     DAG.getConstant(NumBits+NumBits-1, OpVT),
10113     DAG.getConstant(X86::COND_E, MVT::i8),
10114     Op.getValue(1)
10115   };
10116   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10117
10118   // Finally xor with NumBits-1.
10119   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
10120
10121   if (VT == MVT::i8)
10122     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10123   return Op;
10124 }
10125
10126 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
10127   EVT VT = Op.getValueType();
10128   EVT OpVT = VT;
10129   unsigned NumBits = VT.getSizeInBits();
10130   DebugLoc dl = Op.getDebugLoc();
10131
10132   Op = Op.getOperand(0);
10133   if (VT == MVT::i8) {
10134     OpVT = MVT::i32;
10135     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
10136   }
10137
10138   // Issue a bsf (scan bits forward) which also sets EFLAGS.
10139   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
10140   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
10141
10142   // If src is zero (i.e. bsf sets ZF), returns NumBits.
10143   SDValue Ops[] = {
10144     Op,
10145     DAG.getConstant(NumBits, OpVT),
10146     DAG.getConstant(X86::COND_E, MVT::i8),
10147     Op.getValue(1)
10148   };
10149   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
10150
10151   if (VT == MVT::i8)
10152     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
10153   return Op;
10154 }
10155
10156 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
10157 // ones, and then concatenate the result back.
10158 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
10159   EVT VT = Op.getValueType();
10160
10161   assert(VT.getSizeInBits() == 256 && VT.isInteger() &&
10162          "Unsupported value type for operation");
10163
10164   int NumElems = VT.getVectorNumElements();
10165   DebugLoc dl = Op.getDebugLoc();
10166   SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10167   SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10168
10169   // Extract the LHS vectors
10170   SDValue LHS = Op.getOperand(0);
10171   SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10172   SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10173
10174   // Extract the RHS vectors
10175   SDValue RHS = Op.getOperand(1);
10176   SDValue RHS1 = Extract128BitVector(RHS, Idx0, DAG, dl);
10177   SDValue RHS2 = Extract128BitVector(RHS, Idx1, DAG, dl);
10178
10179   MVT EltVT = VT.getVectorElementType().getSimpleVT();
10180   EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10181
10182   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10183                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
10184                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
10185 }
10186
10187 SDValue X86TargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
10188   assert(Op.getValueType().getSizeInBits() == 256 &&
10189          Op.getValueType().isInteger() &&
10190          "Only handle AVX 256-bit vector integer operation");
10191   return Lower256IntArith(Op, DAG);
10192 }
10193
10194 SDValue X86TargetLowering::LowerSUB(SDValue Op, SelectionDAG &DAG) const {
10195   assert(Op.getValueType().getSizeInBits() == 256 &&
10196          Op.getValueType().isInteger() &&
10197          "Only handle AVX 256-bit vector integer operation");
10198   return Lower256IntArith(Op, DAG);
10199 }
10200
10201 SDValue X86TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10202   EVT VT = Op.getValueType();
10203
10204   // Decompose 256-bit ops into smaller 128-bit ops.
10205   if (VT.getSizeInBits() == 256 && !Subtarget->hasAVX2())
10206     return Lower256IntArith(Op, DAG);
10207
10208   DebugLoc dl = Op.getDebugLoc();
10209
10210   SDValue A = Op.getOperand(0);
10211   SDValue B = Op.getOperand(1);
10212
10213   if (VT == MVT::v4i64) {
10214     assert(Subtarget->hasAVX2() && "Lowering v4i64 multiply requires AVX2");
10215
10216     //  ulong2 Ahi = __builtin_ia32_psrlqi256( a, 32);
10217     //  ulong2 Bhi = __builtin_ia32_psrlqi256( b, 32);
10218     //  ulong2 AloBlo = __builtin_ia32_pmuludq256( a, b );
10219     //  ulong2 AloBhi = __builtin_ia32_pmuludq256( a, Bhi );
10220     //  ulong2 AhiBlo = __builtin_ia32_pmuludq256( Ahi, b );
10221     //
10222     //  AloBhi = __builtin_ia32_psllqi256( AloBhi, 32 );
10223     //  AhiBlo = __builtin_ia32_psllqi256( AhiBlo, 32 );
10224     //  return AloBlo + AloBhi + AhiBlo;
10225
10226     SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10227                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10228                          A, DAG.getConstant(32, MVT::i32));
10229     SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10230                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
10231                          B, DAG.getConstant(32, MVT::i32));
10232     SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10233                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10234                          A, B);
10235     SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10236                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10237                          A, Bhi);
10238     SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10239                          DAG.getConstant(Intrinsic::x86_avx2_pmulu_dq, MVT::i32),
10240                          Ahi, B);
10241     AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10242                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10243                          AloBhi, DAG.getConstant(32, MVT::i32));
10244     AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10245                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
10246                          AhiBlo, DAG.getConstant(32, MVT::i32));
10247     SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10248     Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10249     return Res;
10250   }
10251
10252   assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
10253
10254   //  ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
10255   //  ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
10256   //  ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
10257   //  ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
10258   //  ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
10259   //
10260   //  AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
10261   //  AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
10262   //  return AloBlo + AloBhi + AhiBlo;
10263
10264   SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10265                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10266                        A, DAG.getConstant(32, MVT::i32));
10267   SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10268                        DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10269                        B, DAG.getConstant(32, MVT::i32));
10270   SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10271                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10272                        A, B);
10273   SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10274                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10275                        A, Bhi);
10276   SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10277                        DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
10278                        Ahi, B);
10279   AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10280                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10281                        AloBhi, DAG.getConstant(32, MVT::i32));
10282   AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10283                        DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10284                        AhiBlo, DAG.getConstant(32, MVT::i32));
10285   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
10286   Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
10287   return Res;
10288 }
10289
10290 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
10291
10292   EVT VT = Op.getValueType();
10293   DebugLoc dl = Op.getDebugLoc();
10294   SDValue R = Op.getOperand(0);
10295   SDValue Amt = Op.getOperand(1);
10296   LLVMContext *Context = DAG.getContext();
10297
10298   if (!Subtarget->hasXMMInt())
10299     return SDValue();
10300
10301   // Optimize shl/srl/sra with constant shift amount.
10302   if (isSplatVector(Amt.getNode())) {
10303     SDValue SclrAmt = Amt->getOperand(0);
10304     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
10305       uint64_t ShiftAmt = C->getZExtValue();
10306
10307       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SHL) {
10308         // Make a large shift.
10309         SDValue SHL =
10310           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10311                       DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10312                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10313         // Zero out the rightmost bits.
10314         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10315                                                        MVT::i8));
10316         return DAG.getNode(ISD::AND, dl, VT, SHL,
10317                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10318       }
10319
10320       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SHL)
10321        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10322                      DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10323                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10324
10325       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SHL)
10326        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10327                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10328                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10329
10330       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SHL)
10331        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10332                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10333                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10334
10335       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRL) {
10336         // Make a large shift.
10337         SDValue SRL =
10338           DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10339                       DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10340                       R, DAG.getConstant(ShiftAmt, MVT::i32));
10341         // Zero out the leftmost bits.
10342         SmallVector<SDValue, 16> V(16, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10343                                                        MVT::i8));
10344         return DAG.getNode(ISD::AND, dl, VT, SRL,
10345                            DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16));
10346       }
10347
10348       if (VT == MVT::v2i64 && Op.getOpcode() == ISD::SRL)
10349        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10350                      DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10351                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10352
10353       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRL)
10354        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10355                      DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10356                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10357
10358       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRL)
10359        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10360                      DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10361                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10362
10363       if (VT == MVT::v4i32 && Op.getOpcode() == ISD::SRA)
10364        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10365                      DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10366                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10367
10368       if (VT == MVT::v8i16 && Op.getOpcode() == ISD::SRA)
10369        return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10370                      DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10371                      R, DAG.getConstant(ShiftAmt, MVT::i32));
10372
10373       if (VT == MVT::v16i8 && Op.getOpcode() == ISD::SRA) {
10374         if (ShiftAmt == 7) {
10375           // R s>> 7  ===  R s< 0
10376           SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10377           return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10378         }
10379
10380         // R s>> a === ((R u>> a) ^ m) - m
10381         SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10382         SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
10383                                                        MVT::i8));
10384         SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 16);
10385         Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10386         Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10387         return Res;
10388       }
10389
10390       if (Subtarget->hasAVX2() && VT == MVT::v32i8) {
10391         if (Op.getOpcode() == ISD::SHL) {
10392           // Make a large shift.
10393           SDValue SHL =
10394             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10395                         DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
10396                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10397           // Zero out the rightmost bits.
10398           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U << ShiftAmt),
10399                                                          MVT::i8));
10400           return DAG.getNode(ISD::AND, dl, VT, SHL,
10401                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10402         }
10403         if (Op.getOpcode() == ISD::SRL) {
10404           // Make a large shift.
10405           SDValue SRL =
10406             DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10407                         DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
10408                         R, DAG.getConstant(ShiftAmt, MVT::i32));
10409           // Zero out the leftmost bits.
10410           SmallVector<SDValue, 32> V(32, DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
10411                                                          MVT::i8));
10412           return DAG.getNode(ISD::AND, dl, VT, SRL,
10413                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32));
10414         }
10415         if (Op.getOpcode() == ISD::SRA) {
10416           if (ShiftAmt == 7) {
10417             // R s>> 7  ===  R s< 0
10418             SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
10419             return DAG.getNode(X86ISD::PCMPGTB, dl, VT, Zeros, R);
10420           }
10421
10422           // R s>> a === ((R u>> a) ^ m) - m
10423           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
10424           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
10425                                                          MVT::i8));
10426           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &V[0], 32);
10427           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
10428           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
10429           return Res;
10430         }
10431       }
10432     }
10433   }
10434
10435   // Lower SHL with variable shift amount.
10436   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
10437     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10438                      DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10439                      Op.getOperand(1), DAG.getConstant(23, MVT::i32));
10440
10441     ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
10442
10443     std::vector<Constant*> CV(4, CI);
10444     Constant *C = ConstantVector::get(CV);
10445     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10446     SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10447                                  MachinePointerInfo::getConstantPool(),
10448                                  false, false, false, 16);
10449
10450     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
10451     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
10452     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
10453     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
10454   }
10455   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
10456     // a = a << 5;
10457     Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10458                      DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10459                      Op.getOperand(1), DAG.getConstant(5, MVT::i32));
10460
10461     ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
10462     ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
10463
10464     std::vector<Constant*> CVM1(16, CM1);
10465     std::vector<Constant*> CVM2(16, CM2);
10466     Constant *C = ConstantVector::get(CVM1);
10467     SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10468     SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10469                             MachinePointerInfo::getConstantPool(),
10470                             false, false, false, 16);
10471
10472     // r = pblendv(r, psllw(r & (char16)15, 4), a);
10473     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10474     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10475                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10476                     DAG.getConstant(4, MVT::i32));
10477     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10478     // a += a
10479     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10480
10481     C = ConstantVector::get(CVM2);
10482     CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
10483     M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10484                     MachinePointerInfo::getConstantPool(),
10485                     false, false, false, 16);
10486
10487     // r = pblendv(r, psllw(r & (char16)63, 2), a);
10488     M = DAG.getNode(ISD::AND, dl, VT, R, M);
10489     M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10490                     DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
10491                     DAG.getConstant(2, MVT::i32));
10492     R = DAG.getNode(ISD::VSELECT, dl, VT, Op, R, M);
10493     // a += a
10494     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
10495
10496     // return pblendv(r, r+r, a);
10497     R = DAG.getNode(ISD::VSELECT, dl, VT, Op,
10498                     R, DAG.getNode(ISD::ADD, dl, VT, R, R));
10499     return R;
10500   }
10501
10502   // Decompose 256-bit shifts into smaller 128-bit shifts.
10503   if (VT.getSizeInBits() == 256) {
10504     int NumElems = VT.getVectorNumElements();
10505     MVT EltVT = VT.getVectorElementType().getSimpleVT();
10506     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10507
10508     // Extract the two vectors
10509     SDValue V1 = Extract128BitVector(R, DAG.getConstant(0, MVT::i32), DAG, dl);
10510     SDValue V2 = Extract128BitVector(R, DAG.getConstant(NumElems/2, MVT::i32),
10511                                      DAG, dl);
10512
10513     // Recreate the shift amount vectors
10514     SDValue Amt1, Amt2;
10515     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
10516       // Constant shift amount
10517       SmallVector<SDValue, 4> Amt1Csts;
10518       SmallVector<SDValue, 4> Amt2Csts;
10519       for (int i = 0; i < NumElems/2; ++i)
10520         Amt1Csts.push_back(Amt->getOperand(i));
10521       for (int i = NumElems/2; i < NumElems; ++i)
10522         Amt2Csts.push_back(Amt->getOperand(i));
10523
10524       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10525                                  &Amt1Csts[0], NumElems/2);
10526       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT,
10527                                  &Amt2Csts[0], NumElems/2);
10528     } else {
10529       // Variable shift amount
10530       Amt1 = Extract128BitVector(Amt, DAG.getConstant(0, MVT::i32), DAG, dl);
10531       Amt2 = Extract128BitVector(Amt, DAG.getConstant(NumElems/2, MVT::i32),
10532                                  DAG, dl);
10533     }
10534
10535     // Issue new vector shifts for the smaller types
10536     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
10537     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
10538
10539     // Concatenate the result back
10540     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
10541   }
10542
10543   return SDValue();
10544 }
10545
10546 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
10547   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
10548   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
10549   // looks for this combo and may remove the "setcc" instruction if the "setcc"
10550   // has only one use.
10551   SDNode *N = Op.getNode();
10552   SDValue LHS = N->getOperand(0);
10553   SDValue RHS = N->getOperand(1);
10554   unsigned BaseOp = 0;
10555   unsigned Cond = 0;
10556   DebugLoc DL = Op.getDebugLoc();
10557   switch (Op.getOpcode()) {
10558   default: llvm_unreachable("Unknown ovf instruction!");
10559   case ISD::SADDO:
10560     // A subtract of one will be selected as a INC. Note that INC doesn't
10561     // set CF, so we can't do this for UADDO.
10562     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10563       if (C->isOne()) {
10564         BaseOp = X86ISD::INC;
10565         Cond = X86::COND_O;
10566         break;
10567       }
10568     BaseOp = X86ISD::ADD;
10569     Cond = X86::COND_O;
10570     break;
10571   case ISD::UADDO:
10572     BaseOp = X86ISD::ADD;
10573     Cond = X86::COND_B;
10574     break;
10575   case ISD::SSUBO:
10576     // A subtract of one will be selected as a DEC. Note that DEC doesn't
10577     // set CF, so we can't do this for USUBO.
10578     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
10579       if (C->isOne()) {
10580         BaseOp = X86ISD::DEC;
10581         Cond = X86::COND_O;
10582         break;
10583       }
10584     BaseOp = X86ISD::SUB;
10585     Cond = X86::COND_O;
10586     break;
10587   case ISD::USUBO:
10588     BaseOp = X86ISD::SUB;
10589     Cond = X86::COND_B;
10590     break;
10591   case ISD::SMULO:
10592     BaseOp = X86ISD::SMUL;
10593     Cond = X86::COND_O;
10594     break;
10595   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
10596     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
10597                                  MVT::i32);
10598     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
10599
10600     SDValue SetCC =
10601       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10602                   DAG.getConstant(X86::COND_O, MVT::i32),
10603                   SDValue(Sum.getNode(), 2));
10604
10605     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10606   }
10607   }
10608
10609   // Also sets EFLAGS.
10610   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
10611   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
10612
10613   SDValue SetCC =
10614     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
10615                 DAG.getConstant(Cond, MVT::i32),
10616                 SDValue(Sum.getNode(), 1));
10617
10618   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
10619 }
10620
10621 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op, SelectionDAG &DAG) const{
10622   DebugLoc dl = Op.getDebugLoc();
10623   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
10624   EVT VT = Op.getValueType();
10625
10626   if (Subtarget->hasXMMInt() && VT.isVector()) {
10627     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
10628                         ExtraVT.getScalarType().getSizeInBits();
10629     SDValue ShAmt = DAG.getConstant(BitsDiff, MVT::i32);
10630
10631     unsigned SHLIntrinsicsID = 0;
10632     unsigned SRAIntrinsicsID = 0;
10633     switch (VT.getSimpleVT().SimpleTy) {
10634       default:
10635         return SDValue();
10636       case MVT::v4i32:
10637         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_d;
10638         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_d;
10639         break;
10640       case MVT::v8i16:
10641         SHLIntrinsicsID = Intrinsic::x86_sse2_pslli_w;
10642         SRAIntrinsicsID = Intrinsic::x86_sse2_psrai_w;
10643         break;
10644       case MVT::v8i32:
10645       case MVT::v16i16:
10646         if (!Subtarget->hasAVX())
10647           return SDValue();
10648         if (!Subtarget->hasAVX2()) {
10649           // needs to be split
10650           int NumElems = VT.getVectorNumElements();
10651           SDValue Idx0 = DAG.getConstant(0, MVT::i32);
10652           SDValue Idx1 = DAG.getConstant(NumElems/2, MVT::i32);
10653
10654           // Extract the LHS vectors
10655           SDValue LHS = Op.getOperand(0);
10656           SDValue LHS1 = Extract128BitVector(LHS, Idx0, DAG, dl);
10657           SDValue LHS2 = Extract128BitVector(LHS, Idx1, DAG, dl);
10658
10659           MVT EltVT = VT.getVectorElementType().getSimpleVT();
10660           EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10661
10662           EVT ExtraEltVT = ExtraVT.getVectorElementType();
10663           int ExtraNumElems = ExtraVT.getVectorNumElements();
10664           ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
10665                                      ExtraNumElems/2);
10666           SDValue Extra = DAG.getValueType(ExtraVT);
10667
10668           LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
10669           LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
10670
10671           return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);;
10672         }
10673         if (VT == MVT::v8i32) {
10674           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_d;
10675           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_d;
10676         } else {
10677           SHLIntrinsicsID = Intrinsic::x86_avx2_pslli_w;
10678           SRAIntrinsicsID = Intrinsic::x86_avx2_psrai_w;
10679         }
10680     }
10681
10682     SDValue Tmp1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10683                          DAG.getConstant(SHLIntrinsicsID, MVT::i32),
10684                          Op.getOperand(0), ShAmt);
10685
10686     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
10687                        DAG.getConstant(SRAIntrinsicsID, MVT::i32),
10688                        Tmp1, ShAmt);
10689   }
10690
10691   return SDValue();
10692 }
10693
10694
10695 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
10696   DebugLoc dl = Op.getDebugLoc();
10697
10698   // Go ahead and emit the fence on x86-64 even if we asked for no-sse2.
10699   // There isn't any reason to disable it if the target processor supports it.
10700   if (!Subtarget->hasXMMInt() && !Subtarget->is64Bit()) {
10701     SDValue Chain = Op.getOperand(0);
10702     SDValue Zero = DAG.getConstant(0, MVT::i32);
10703     SDValue Ops[] = {
10704       DAG.getRegister(X86::ESP, MVT::i32), // Base
10705       DAG.getTargetConstant(1, MVT::i8),   // Scale
10706       DAG.getRegister(0, MVT::i32),        // Index
10707       DAG.getTargetConstant(0, MVT::i32),  // Disp
10708       DAG.getRegister(0, MVT::i32),        // Segment.
10709       Zero,
10710       Chain
10711     };
10712     SDNode *Res =
10713       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10714                           array_lengthof(Ops));
10715     return SDValue(Res, 0);
10716   }
10717
10718   unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
10719   if (!isDev)
10720     return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10721
10722   unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10723   unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
10724   unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
10725   unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
10726
10727   // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
10728   if (!Op1 && !Op2 && !Op3 && Op4)
10729     return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
10730
10731   // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
10732   if (Op1 && !Op2 && !Op3 && !Op4)
10733     return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
10734
10735   // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
10736   //           (MFENCE)>;
10737   return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10738 }
10739
10740 SDValue X86TargetLowering::LowerATOMIC_FENCE(SDValue Op,
10741                                              SelectionDAG &DAG) const {
10742   DebugLoc dl = Op.getDebugLoc();
10743   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
10744     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
10745   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
10746     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
10747
10748   // The only fence that needs an instruction is a sequentially-consistent
10749   // cross-thread fence.
10750   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
10751     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
10752     // no-sse2). There isn't any reason to disable it if the target processor
10753     // supports it.
10754     if (Subtarget->hasXMMInt() || Subtarget->is64Bit())
10755       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
10756
10757     SDValue Chain = Op.getOperand(0);
10758     SDValue Zero = DAG.getConstant(0, MVT::i32);
10759     SDValue Ops[] = {
10760       DAG.getRegister(X86::ESP, MVT::i32), // Base
10761       DAG.getTargetConstant(1, MVT::i8),   // Scale
10762       DAG.getRegister(0, MVT::i32),        // Index
10763       DAG.getTargetConstant(0, MVT::i32),  // Disp
10764       DAG.getRegister(0, MVT::i32),        // Segment.
10765       Zero,
10766       Chain
10767     };
10768     SDNode *Res =
10769       DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
10770                          array_lengthof(Ops));
10771     return SDValue(Res, 0);
10772   }
10773
10774   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
10775   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
10776 }
10777
10778
10779 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
10780   EVT T = Op.getValueType();
10781   DebugLoc DL = Op.getDebugLoc();
10782   unsigned Reg = 0;
10783   unsigned size = 0;
10784   switch(T.getSimpleVT().SimpleTy) {
10785   default:
10786     assert(false && "Invalid value type!");
10787   case MVT::i8:  Reg = X86::AL;  size = 1; break;
10788   case MVT::i16: Reg = X86::AX;  size = 2; break;
10789   case MVT::i32: Reg = X86::EAX; size = 4; break;
10790   case MVT::i64:
10791     assert(Subtarget->is64Bit() && "Node not type legal!");
10792     Reg = X86::RAX; size = 8;
10793     break;
10794   }
10795   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
10796                                     Op.getOperand(2), SDValue());
10797   SDValue Ops[] = { cpIn.getValue(0),
10798                     Op.getOperand(1),
10799                     Op.getOperand(3),
10800                     DAG.getTargetConstant(size, MVT::i8),
10801                     cpIn.getValue(1) };
10802   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10803   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
10804   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
10805                                            Ops, 5, T, MMO);
10806   SDValue cpOut =
10807     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
10808   return cpOut;
10809 }
10810
10811 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
10812                                                  SelectionDAG &DAG) const {
10813   assert(Subtarget->is64Bit() && "Result not type legalized?");
10814   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
10815   SDValue TheChain = Op.getOperand(0);
10816   DebugLoc dl = Op.getDebugLoc();
10817   SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
10818   SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
10819   SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
10820                                    rax.getValue(2));
10821   SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
10822                             DAG.getConstant(32, MVT::i8));
10823   SDValue Ops[] = {
10824     DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
10825     rdx.getValue(1)
10826   };
10827   return DAG.getMergeValues(Ops, 2, dl);
10828 }
10829
10830 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
10831                                             SelectionDAG &DAG) const {
10832   EVT SrcVT = Op.getOperand(0).getValueType();
10833   EVT DstVT = Op.getValueType();
10834   assert(Subtarget->is64Bit() && !Subtarget->hasXMMInt() &&
10835          Subtarget->hasMMX() && "Unexpected custom BITCAST");
10836   assert((DstVT == MVT::i64 ||
10837           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
10838          "Unexpected custom BITCAST");
10839   // i64 <=> MMX conversions are Legal.
10840   if (SrcVT==MVT::i64 && DstVT.isVector())
10841     return Op;
10842   if (DstVT==MVT::i64 && SrcVT.isVector())
10843     return Op;
10844   // MMX <=> MMX conversions are Legal.
10845   if (SrcVT.isVector() && DstVT.isVector())
10846     return Op;
10847   // All other conversions need to be expanded.
10848   return SDValue();
10849 }
10850
10851 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
10852   SDNode *Node = Op.getNode();
10853   DebugLoc dl = Node->getDebugLoc();
10854   EVT T = Node->getValueType(0);
10855   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
10856                               DAG.getConstant(0, T), Node->getOperand(2));
10857   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
10858                        cast<AtomicSDNode>(Node)->getMemoryVT(),
10859                        Node->getOperand(0),
10860                        Node->getOperand(1), negOp,
10861                        cast<AtomicSDNode>(Node)->getSrcValue(),
10862                        cast<AtomicSDNode>(Node)->getAlignment(),
10863                        cast<AtomicSDNode>(Node)->getOrdering(),
10864                        cast<AtomicSDNode>(Node)->getSynchScope());
10865 }
10866
10867 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
10868   SDNode *Node = Op.getNode();
10869   DebugLoc dl = Node->getDebugLoc();
10870   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10871
10872   // Convert seq_cst store -> xchg
10873   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
10874   // FIXME: On 32-bit, store -> fist or movq would be more efficient
10875   //        (The only way to get a 16-byte store is cmpxchg16b)
10876   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
10877   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
10878       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10879     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
10880                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
10881                                  Node->getOperand(0),
10882                                  Node->getOperand(1), Node->getOperand(2),
10883                                  cast<AtomicSDNode>(Node)->getMemOperand(),
10884                                  cast<AtomicSDNode>(Node)->getOrdering(),
10885                                  cast<AtomicSDNode>(Node)->getSynchScope());
10886     return Swap.getValue(1);
10887   }
10888   // Other atomic stores have a simple pattern.
10889   return Op;
10890 }
10891
10892 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
10893   EVT VT = Op.getNode()->getValueType(0);
10894
10895   // Let legalize expand this if it isn't a legal type yet.
10896   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10897     return SDValue();
10898
10899   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
10900
10901   unsigned Opc;
10902   bool ExtraOp = false;
10903   switch (Op.getOpcode()) {
10904   default: assert(0 && "Invalid code");
10905   case ISD::ADDC: Opc = X86ISD::ADD; break;
10906   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
10907   case ISD::SUBC: Opc = X86ISD::SUB; break;
10908   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
10909   }
10910
10911   if (!ExtraOp)
10912     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10913                        Op.getOperand(1));
10914   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
10915                      Op.getOperand(1), Op.getOperand(2));
10916 }
10917
10918 /// LowerOperation - Provide custom lowering hooks for some operations.
10919 ///
10920 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10921   switch (Op.getOpcode()) {
10922   default: llvm_unreachable("Should not custom lower this!");
10923   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
10924   case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op,DAG);
10925   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op,DAG);
10926   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op,DAG);
10927   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
10928   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
10929   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10930   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
10931   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10932   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10933   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10934   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op, DAG);
10935   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, DAG);
10936   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10937   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10938   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10939   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10940   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
10941   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10942   case ISD::SHL_PARTS:
10943   case ISD::SRA_PARTS:
10944   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
10945   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
10946   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
10947   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
10948   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
10949   case ISD::FABS:               return LowerFABS(Op, DAG);
10950   case ISD::FNEG:               return LowerFNEG(Op, DAG);
10951   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
10952   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
10953   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10954   case ISD::SELECT:             return LowerSELECT(Op, DAG);
10955   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
10956   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10957   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10958   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10959   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10960   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10961   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10962   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10963   case ISD::FRAME_TO_ARGS_OFFSET:
10964                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
10965   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10966   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
10967   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10968   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10969   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10970   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
10971   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
10972   case ISD::MUL:                return LowerMUL(Op, DAG);
10973   case ISD::SRA:
10974   case ISD::SRL:
10975   case ISD::SHL:                return LowerShift(Op, DAG);
10976   case ISD::SADDO:
10977   case ISD::UADDO:
10978   case ISD::SSUBO:
10979   case ISD::USUBO:
10980   case ISD::SMULO:
10981   case ISD::UMULO:              return LowerXALUO(Op, DAG);
10982   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, DAG);
10983   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10984   case ISD::ADDC:
10985   case ISD::ADDE:
10986   case ISD::SUBC:
10987   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
10988   case ISD::ADD:                return LowerADD(Op, DAG);
10989   case ISD::SUB:                return LowerSUB(Op, DAG);
10990   }
10991 }
10992
10993 static void ReplaceATOMIC_LOAD(SDNode *Node,
10994                                   SmallVectorImpl<SDValue> &Results,
10995                                   SelectionDAG &DAG) {
10996   DebugLoc dl = Node->getDebugLoc();
10997   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
10998
10999   // Convert wide load -> cmpxchg8b/cmpxchg16b
11000   // FIXME: On 32-bit, load -> fild or movq would be more efficient
11001   //        (The only way to get a 16-byte load is cmpxchg16b)
11002   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
11003   SDValue Zero = DAG.getConstant(0, VT);
11004   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
11005                                Node->getOperand(0),
11006                                Node->getOperand(1), Zero, Zero,
11007                                cast<AtomicSDNode>(Node)->getMemOperand(),
11008                                cast<AtomicSDNode>(Node)->getOrdering(),
11009                                cast<AtomicSDNode>(Node)->getSynchScope());
11010   Results.push_back(Swap.getValue(0));
11011   Results.push_back(Swap.getValue(1));
11012 }
11013
11014 void X86TargetLowering::
11015 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
11016                         SelectionDAG &DAG, unsigned NewOp) const {
11017   DebugLoc dl = Node->getDebugLoc();
11018   assert (Node->getValueType(0) == MVT::i64 &&
11019           "Only know how to expand i64 atomics");
11020
11021   SDValue Chain = Node->getOperand(0);
11022   SDValue In1 = Node->getOperand(1);
11023   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11024                              Node->getOperand(2), DAG.getIntPtrConstant(0));
11025   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
11026                              Node->getOperand(2), DAG.getIntPtrConstant(1));
11027   SDValue Ops[] = { Chain, In1, In2L, In2H };
11028   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
11029   SDValue Result =
11030     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
11031                             cast<MemSDNode>(Node)->getMemOperand());
11032   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
11033   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
11034   Results.push_back(Result.getValue(2));
11035 }
11036
11037 /// ReplaceNodeResults - Replace a node with an illegal result type
11038 /// with a new node built out of custom code.
11039 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
11040                                            SmallVectorImpl<SDValue>&Results,
11041                                            SelectionDAG &DAG) const {
11042   DebugLoc dl = N->getDebugLoc();
11043   switch (N->getOpcode()) {
11044   default:
11045     assert(false && "Do not know how to custom type legalize this operation!");
11046     return;
11047   case ISD::SIGN_EXTEND_INREG:
11048   case ISD::ADDC:
11049   case ISD::ADDE:
11050   case ISD::SUBC:
11051   case ISD::SUBE:
11052     // We don't want to expand or promote these.
11053     return;
11054   case ISD::FP_TO_SINT: {
11055     std::pair<SDValue,SDValue> Vals =
11056         FP_TO_INTHelper(SDValue(N, 0), DAG, true);
11057     SDValue FIST = Vals.first, StackSlot = Vals.second;
11058     if (FIST.getNode() != 0) {
11059       EVT VT = N->getValueType(0);
11060       // Return a load from the stack slot.
11061       Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
11062                                     MachinePointerInfo(), 
11063                                     false, false, false, 0));
11064     }
11065     return;
11066   }
11067   case ISD::READCYCLECOUNTER: {
11068     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11069     SDValue TheChain = N->getOperand(0);
11070     SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
11071     SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
11072                                      rd.getValue(1));
11073     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
11074                                      eax.getValue(2));
11075     // Use a buildpair to merge the two 32-bit values into a 64-bit one.
11076     SDValue Ops[] = { eax, edx };
11077     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
11078     Results.push_back(edx.getValue(1));
11079     return;
11080   }
11081   case ISD::ATOMIC_CMP_SWAP: {
11082     EVT T = N->getValueType(0);
11083     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
11084     bool Regs64bit = T == MVT::i128;
11085     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
11086     SDValue cpInL, cpInH;
11087     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11088                         DAG.getConstant(0, HalfT));
11089     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
11090                         DAG.getConstant(1, HalfT));
11091     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
11092                              Regs64bit ? X86::RAX : X86::EAX,
11093                              cpInL, SDValue());
11094     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
11095                              Regs64bit ? X86::RDX : X86::EDX,
11096                              cpInH, cpInL.getValue(1));
11097     SDValue swapInL, swapInH;
11098     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11099                           DAG.getConstant(0, HalfT));
11100     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
11101                           DAG.getConstant(1, HalfT));
11102     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
11103                                Regs64bit ? X86::RBX : X86::EBX,
11104                                swapInL, cpInH.getValue(1));
11105     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
11106                                Regs64bit ? X86::RCX : X86::ECX, 
11107                                swapInH, swapInL.getValue(1));
11108     SDValue Ops[] = { swapInH.getValue(0),
11109                       N->getOperand(1),
11110                       swapInH.getValue(1) };
11111     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
11112     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
11113     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
11114                                   X86ISD::LCMPXCHG8_DAG;
11115     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys,
11116                                              Ops, 3, T, MMO);
11117     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
11118                                         Regs64bit ? X86::RAX : X86::EAX,
11119                                         HalfT, Result.getValue(1));
11120     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
11121                                         Regs64bit ? X86::RDX : X86::EDX,
11122                                         HalfT, cpOutL.getValue(2));
11123     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
11124     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF, 2));
11125     Results.push_back(cpOutH.getValue(1));
11126     return;
11127   }
11128   case ISD::ATOMIC_LOAD_ADD:
11129     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
11130     return;
11131   case ISD::ATOMIC_LOAD_AND:
11132     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
11133     return;
11134   case ISD::ATOMIC_LOAD_NAND:
11135     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
11136     return;
11137   case ISD::ATOMIC_LOAD_OR:
11138     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
11139     return;
11140   case ISD::ATOMIC_LOAD_SUB:
11141     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
11142     return;
11143   case ISD::ATOMIC_LOAD_XOR:
11144     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
11145     return;
11146   case ISD::ATOMIC_SWAP:
11147     ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
11148     return;
11149   case ISD::ATOMIC_LOAD:
11150     ReplaceATOMIC_LOAD(N, Results, DAG);
11151   }
11152 }
11153
11154 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
11155   switch (Opcode) {
11156   default: return NULL;
11157   case X86ISD::BSF:                return "X86ISD::BSF";
11158   case X86ISD::BSR:                return "X86ISD::BSR";
11159   case X86ISD::SHLD:               return "X86ISD::SHLD";
11160   case X86ISD::SHRD:               return "X86ISD::SHRD";
11161   case X86ISD::FAND:               return "X86ISD::FAND";
11162   case X86ISD::FOR:                return "X86ISD::FOR";
11163   case X86ISD::FXOR:               return "X86ISD::FXOR";
11164   case X86ISD::FSRL:               return "X86ISD::FSRL";
11165   case X86ISD::FILD:               return "X86ISD::FILD";
11166   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
11167   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
11168   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
11169   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
11170   case X86ISD::FLD:                return "X86ISD::FLD";
11171   case X86ISD::FST:                return "X86ISD::FST";
11172   case X86ISD::CALL:               return "X86ISD::CALL";
11173   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
11174   case X86ISD::BT:                 return "X86ISD::BT";
11175   case X86ISD::CMP:                return "X86ISD::CMP";
11176   case X86ISD::COMI:               return "X86ISD::COMI";
11177   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
11178   case X86ISD::SETCC:              return "X86ISD::SETCC";
11179   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
11180   case X86ISD::FSETCCsd:           return "X86ISD::FSETCCsd";
11181   case X86ISD::FSETCCss:           return "X86ISD::FSETCCss";
11182   case X86ISD::CMOV:               return "X86ISD::CMOV";
11183   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
11184   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
11185   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
11186   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
11187   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
11188   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
11189   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
11190   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
11191   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
11192   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
11193   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
11194   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
11195   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
11196   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
11197   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
11198   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
11199   case X86ISD::FHADD:              return "X86ISD::FHADD";
11200   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
11201   case X86ISD::FMAX:               return "X86ISD::FMAX";
11202   case X86ISD::FMIN:               return "X86ISD::FMIN";
11203   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
11204   case X86ISD::FRCP:               return "X86ISD::FRCP";
11205   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
11206   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
11207   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
11208   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
11209   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
11210   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
11211   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
11212   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
11213   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
11214   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
11215   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
11216   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
11217   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
11218   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
11219   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
11220   case X86ISD::VSHL:               return "X86ISD::VSHL";
11221   case X86ISD::VSRL:               return "X86ISD::VSRL";
11222   case X86ISD::CMPPD:              return "X86ISD::CMPPD";
11223   case X86ISD::CMPPS:              return "X86ISD::CMPPS";
11224   case X86ISD::PCMPEQB:            return "X86ISD::PCMPEQB";
11225   case X86ISD::PCMPEQW:            return "X86ISD::PCMPEQW";
11226   case X86ISD::PCMPEQD:            return "X86ISD::PCMPEQD";
11227   case X86ISD::PCMPEQQ:            return "X86ISD::PCMPEQQ";
11228   case X86ISD::PCMPGTB:            return "X86ISD::PCMPGTB";
11229   case X86ISD::PCMPGTW:            return "X86ISD::PCMPGTW";
11230   case X86ISD::PCMPGTD:            return "X86ISD::PCMPGTD";
11231   case X86ISD::PCMPGTQ:            return "X86ISD::PCMPGTQ";
11232   case X86ISD::ADD:                return "X86ISD::ADD";
11233   case X86ISD::SUB:                return "X86ISD::SUB";
11234   case X86ISD::ADC:                return "X86ISD::ADC";
11235   case X86ISD::SBB:                return "X86ISD::SBB";
11236   case X86ISD::SMUL:               return "X86ISD::SMUL";
11237   case X86ISD::UMUL:               return "X86ISD::UMUL";
11238   case X86ISD::INC:                return "X86ISD::INC";
11239   case X86ISD::DEC:                return "X86ISD::DEC";
11240   case X86ISD::OR:                 return "X86ISD::OR";
11241   case X86ISD::XOR:                return "X86ISD::XOR";
11242   case X86ISD::AND:                return "X86ISD::AND";
11243   case X86ISD::ANDN:               return "X86ISD::ANDN";
11244   case X86ISD::BLSI:               return "X86ISD::BLSI";
11245   case X86ISD::BLSMSK:             return "X86ISD::BLSMSK";
11246   case X86ISD::BLSR:               return "X86ISD::BLSR";
11247   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
11248   case X86ISD::PTEST:              return "X86ISD::PTEST";
11249   case X86ISD::TESTP:              return "X86ISD::TESTP";
11250   case X86ISD::PALIGN:             return "X86ISD::PALIGN";
11251   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
11252   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
11253   case X86ISD::PSHUFHW_LD:         return "X86ISD::PSHUFHW_LD";
11254   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
11255   case X86ISD::PSHUFLW_LD:         return "X86ISD::PSHUFLW_LD";
11256   case X86ISD::SHUFPS:             return "X86ISD::SHUFPS";
11257   case X86ISD::SHUFPD:             return "X86ISD::SHUFPD";
11258   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
11259   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
11260   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
11261   case X86ISD::MOVHLPD:            return "X86ISD::MOVHLPD";
11262   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
11263   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
11264   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
11265   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
11266   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
11267   case X86ISD::MOVSHDUP_LD:        return "X86ISD::MOVSHDUP_LD";
11268   case X86ISD::MOVSLDUP_LD:        return "X86ISD::MOVSLDUP_LD";
11269   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
11270   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
11271   case X86ISD::UNPCKLPS:           return "X86ISD::UNPCKLPS";
11272   case X86ISD::UNPCKLPD:           return "X86ISD::UNPCKLPD";
11273   case X86ISD::VUNPCKLPSY:         return "X86ISD::VUNPCKLPSY";
11274   case X86ISD::VUNPCKLPDY:         return "X86ISD::VUNPCKLPDY";
11275   case X86ISD::UNPCKHPS:           return "X86ISD::UNPCKHPS";
11276   case X86ISD::UNPCKHPD:           return "X86ISD::UNPCKHPD";
11277   case X86ISD::PUNPCKLBW:          return "X86ISD::PUNPCKLBW";
11278   case X86ISD::PUNPCKLWD:          return "X86ISD::PUNPCKLWD";
11279   case X86ISD::PUNPCKLDQ:          return "X86ISD::PUNPCKLDQ";
11280   case X86ISD::PUNPCKLQDQ:         return "X86ISD::PUNPCKLQDQ";
11281   case X86ISD::VPUNPCKLBWY:        return "X86ISD::VPUNPCKLBWY";
11282   case X86ISD::VPUNPCKLWDY:        return "X86ISD::VPUNPCKLWDY";
11283   case X86ISD::VPUNPCKLDQY:        return "X86ISD::VPUNPCKLDQY";
11284   case X86ISD::VPUNPCKLQDQY:       return "X86ISD::VPUNPCKLQDQY";
11285   case X86ISD::PUNPCKHBW:          return "X86ISD::PUNPCKHBW";
11286   case X86ISD::PUNPCKHWD:          return "X86ISD::PUNPCKHWD";
11287   case X86ISD::PUNPCKHDQ:          return "X86ISD::PUNPCKHDQ";
11288   case X86ISD::PUNPCKHQDQ:         return "X86ISD::PUNPCKHQDQ";
11289   case X86ISD::VPUNPCKHBWY:        return "X86ISD::VPUNPCKHBWY";
11290   case X86ISD::VPUNPCKHWDY:        return "X86ISD::VPUNPCKHWDY";
11291   case X86ISD::VPUNPCKHDQY:        return "X86ISD::VPUNPCKHDQY";
11292   case X86ISD::VPUNPCKHQDQY:       return "X86ISD::VPUNPCKHQDQY";
11293   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
11294   case X86ISD::VPERMILPS:          return "X86ISD::VPERMILPS";
11295   case X86ISD::VPERMILPSY:         return "X86ISD::VPERMILPSY";
11296   case X86ISD::VPERMILPD:          return "X86ISD::VPERMILPD";
11297   case X86ISD::VPERMILPDY:         return "X86ISD::VPERMILPDY";
11298   case X86ISD::VPERM2F128:         return "X86ISD::VPERM2F128";
11299   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
11300   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
11301   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
11302   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
11303   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
11304   }
11305 }
11306
11307 // isLegalAddressingMode - Return true if the addressing mode represented
11308 // by AM is legal for this target, for a load/store of the specified type.
11309 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
11310                                               Type *Ty) const {
11311   // X86 supports extremely general addressing modes.
11312   CodeModel::Model M = getTargetMachine().getCodeModel();
11313   Reloc::Model R = getTargetMachine().getRelocationModel();
11314
11315   // X86 allows a sign-extended 32-bit immediate field as a displacement.
11316   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
11317     return false;
11318
11319   if (AM.BaseGV) {
11320     unsigned GVFlags =
11321       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
11322
11323     // If a reference to this global requires an extra load, we can't fold it.
11324     if (isGlobalStubReference(GVFlags))
11325       return false;
11326
11327     // If BaseGV requires a register for the PIC base, we cannot also have a
11328     // BaseReg specified.
11329     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
11330       return false;
11331
11332     // If lower 4G is not available, then we must use rip-relative addressing.
11333     if ((M != CodeModel::Small || R != Reloc::Static) &&
11334         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
11335       return false;
11336   }
11337
11338   switch (AM.Scale) {
11339   case 0:
11340   case 1:
11341   case 2:
11342   case 4:
11343   case 8:
11344     // These scales always work.
11345     break;
11346   case 3:
11347   case 5:
11348   case 9:
11349     // These scales are formed with basereg+scalereg.  Only accept if there is
11350     // no basereg yet.
11351     if (AM.HasBaseReg)
11352       return false;
11353     break;
11354   default:  // Other stuff never works.
11355     return false;
11356   }
11357
11358   return true;
11359 }
11360
11361
11362 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
11363   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11364     return false;
11365   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
11366   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
11367   if (NumBits1 <= NumBits2)
11368     return false;
11369   return true;
11370 }
11371
11372 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
11373   if (!VT1.isInteger() || !VT2.isInteger())
11374     return false;
11375   unsigned NumBits1 = VT1.getSizeInBits();
11376   unsigned NumBits2 = VT2.getSizeInBits();
11377   if (NumBits1 <= NumBits2)
11378     return false;
11379   return true;
11380 }
11381
11382 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
11383   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11384   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
11385 }
11386
11387 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
11388   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
11389   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
11390 }
11391
11392 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
11393   // i16 instructions are longer (0x66 prefix) and potentially slower.
11394   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
11395 }
11396
11397 /// isShuffleMaskLegal - Targets can use this to indicate that they only
11398 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
11399 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
11400 /// are assumed to be legal.
11401 bool
11402 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
11403                                       EVT VT) const {
11404   // Very little shuffling can be done for 64-bit vectors right now.
11405   if (VT.getSizeInBits() == 64)
11406     return isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX());
11407
11408   // FIXME: pshufb, blends, shifts.
11409   return (VT.getVectorNumElements() == 2 ||
11410           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
11411           isMOVLMask(M, VT) ||
11412           isSHUFPMask(M, VT) ||
11413           isPSHUFDMask(M, VT) ||
11414           isPSHUFHWMask(M, VT) ||
11415           isPSHUFLWMask(M, VT) ||
11416           isPALIGNRMask(M, VT, Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
11417           isUNPCKLMask(M, VT, Subtarget->hasAVX2()) ||
11418           isUNPCKHMask(M, VT, Subtarget->hasAVX2()) ||
11419           isUNPCKL_v_undef_Mask(M, VT) ||
11420           isUNPCKH_v_undef_Mask(M, VT));
11421 }
11422
11423 bool
11424 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
11425                                           EVT VT) const {
11426   unsigned NumElts = VT.getVectorNumElements();
11427   // FIXME: This collection of masks seems suspect.
11428   if (NumElts == 2)
11429     return true;
11430   if (NumElts == 4 && VT.getSizeInBits() == 128) {
11431     return (isMOVLMask(Mask, VT)  ||
11432             isCommutedMOVLMask(Mask, VT, true) ||
11433             isSHUFPMask(Mask, VT) ||
11434             isCommutedSHUFPMask(Mask, VT));
11435   }
11436   return false;
11437 }
11438
11439 //===----------------------------------------------------------------------===//
11440 //                           X86 Scheduler Hooks
11441 //===----------------------------------------------------------------------===//
11442
11443 // private utility function
11444 MachineBasicBlock *
11445 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
11446                                                        MachineBasicBlock *MBB,
11447                                                        unsigned regOpc,
11448                                                        unsigned immOpc,
11449                                                        unsigned LoadOpc,
11450                                                        unsigned CXchgOpc,
11451                                                        unsigned notOpc,
11452                                                        unsigned EAXreg,
11453                                                        TargetRegisterClass *RC,
11454                                                        bool invSrc) const {
11455   // For the atomic bitwise operator, we generate
11456   //   thisMBB:
11457   //   newMBB:
11458   //     ld  t1 = [bitinstr.addr]
11459   //     op  t2 = t1, [bitinstr.val]
11460   //     mov EAX = t1
11461   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11462   //     bz  newMBB
11463   //     fallthrough -->nextMBB
11464   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11465   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11466   MachineFunction::iterator MBBIter = MBB;
11467   ++MBBIter;
11468
11469   /// First build the CFG
11470   MachineFunction *F = MBB->getParent();
11471   MachineBasicBlock *thisMBB = MBB;
11472   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11473   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11474   F->insert(MBBIter, newMBB);
11475   F->insert(MBBIter, nextMBB);
11476
11477   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11478   nextMBB->splice(nextMBB->begin(), thisMBB,
11479                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11480                   thisMBB->end());
11481   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11482
11483   // Update thisMBB to fall through to newMBB
11484   thisMBB->addSuccessor(newMBB);
11485
11486   // newMBB jumps to itself and fall through to nextMBB
11487   newMBB->addSuccessor(nextMBB);
11488   newMBB->addSuccessor(newMBB);
11489
11490   // Insert instructions into newMBB based on incoming instruction
11491   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11492          "unexpected number of operands");
11493   DebugLoc dl = bInstr->getDebugLoc();
11494   MachineOperand& destOper = bInstr->getOperand(0);
11495   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11496   int numArgs = bInstr->getNumOperands() - 1;
11497   for (int i=0; i < numArgs; ++i)
11498     argOpers[i] = &bInstr->getOperand(i+1);
11499
11500   // x86 address has 4 operands: base, index, scale, and displacement
11501   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11502   int valArgIndx = lastAddrIndx + 1;
11503
11504   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11505   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
11506   for (int i=0; i <= lastAddrIndx; ++i)
11507     (*MIB).addOperand(*argOpers[i]);
11508
11509   unsigned tt = F->getRegInfo().createVirtualRegister(RC);
11510   if (invSrc) {
11511     MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
11512   }
11513   else
11514     tt = t1;
11515
11516   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11517   assert((argOpers[valArgIndx]->isReg() ||
11518           argOpers[valArgIndx]->isImm()) &&
11519          "invalid operand");
11520   if (argOpers[valArgIndx]->isReg())
11521     MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
11522   else
11523     MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
11524   MIB.addReg(tt);
11525   (*MIB).addOperand(*argOpers[valArgIndx]);
11526
11527   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
11528   MIB.addReg(t1);
11529
11530   MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
11531   for (int i=0; i <= lastAddrIndx; ++i)
11532     (*MIB).addOperand(*argOpers[i]);
11533   MIB.addReg(t2);
11534   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11535   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11536                     bInstr->memoperands_end());
11537
11538   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11539   MIB.addReg(EAXreg);
11540
11541   // insert branch
11542   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11543
11544   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11545   return nextMBB;
11546 }
11547
11548 // private utility function:  64 bit atomics on 32 bit host.
11549 MachineBasicBlock *
11550 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
11551                                                        MachineBasicBlock *MBB,
11552                                                        unsigned regOpcL,
11553                                                        unsigned regOpcH,
11554                                                        unsigned immOpcL,
11555                                                        unsigned immOpcH,
11556                                                        bool invSrc) const {
11557   // For the atomic bitwise operator, we generate
11558   //   thisMBB (instructions are in pairs, except cmpxchg8b)
11559   //     ld t1,t2 = [bitinstr.addr]
11560   //   newMBB:
11561   //     out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
11562   //     op  t5, t6 <- out1, out2, [bitinstr.val]
11563   //      (for SWAP, substitute:  mov t5, t6 <- [bitinstr.val])
11564   //     mov ECX, EBX <- t5, t6
11565   //     mov EAX, EDX <- t1, t2
11566   //     cmpxchg8b [bitinstr.addr]  [EAX, EDX, EBX, ECX implicit]
11567   //     mov t3, t4 <- EAX, EDX
11568   //     bz  newMBB
11569   //     result in out1, out2
11570   //     fallthrough -->nextMBB
11571
11572   const TargetRegisterClass *RC = X86::GR32RegisterClass;
11573   const unsigned LoadOpc = X86::MOV32rm;
11574   const unsigned NotOpc = X86::NOT32r;
11575   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11576   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11577   MachineFunction::iterator MBBIter = MBB;
11578   ++MBBIter;
11579
11580   /// First build the CFG
11581   MachineFunction *F = MBB->getParent();
11582   MachineBasicBlock *thisMBB = MBB;
11583   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11584   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11585   F->insert(MBBIter, newMBB);
11586   F->insert(MBBIter, nextMBB);
11587
11588   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11589   nextMBB->splice(nextMBB->begin(), thisMBB,
11590                   llvm::next(MachineBasicBlock::iterator(bInstr)),
11591                   thisMBB->end());
11592   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11593
11594   // Update thisMBB to fall through to newMBB
11595   thisMBB->addSuccessor(newMBB);
11596
11597   // newMBB jumps to itself and fall through to nextMBB
11598   newMBB->addSuccessor(nextMBB);
11599   newMBB->addSuccessor(newMBB);
11600
11601   DebugLoc dl = bInstr->getDebugLoc();
11602   // Insert instructions into newMBB based on incoming instruction
11603   // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
11604   assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
11605          "unexpected number of operands");
11606   MachineOperand& dest1Oper = bInstr->getOperand(0);
11607   MachineOperand& dest2Oper = bInstr->getOperand(1);
11608   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11609   for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
11610     argOpers[i] = &bInstr->getOperand(i+2);
11611
11612     // We use some of the operands multiple times, so conservatively just
11613     // clear any kill flags that might be present.
11614     if (argOpers[i]->isReg() && argOpers[i]->isUse())
11615       argOpers[i]->setIsKill(false);
11616   }
11617
11618   // x86 address has 5 operands: base, index, scale, displacement, and segment.
11619   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11620
11621   unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
11622   MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
11623   for (int i=0; i <= lastAddrIndx; ++i)
11624     (*MIB).addOperand(*argOpers[i]);
11625   unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
11626   MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
11627   // add 4 to displacement.
11628   for (int i=0; i <= lastAddrIndx-2; ++i)
11629     (*MIB).addOperand(*argOpers[i]);
11630   MachineOperand newOp3 = *(argOpers[3]);
11631   if (newOp3.isImm())
11632     newOp3.setImm(newOp3.getImm()+4);
11633   else
11634     newOp3.setOffset(newOp3.getOffset()+4);
11635   (*MIB).addOperand(newOp3);
11636   (*MIB).addOperand(*argOpers[lastAddrIndx]);
11637
11638   // t3/4 are defined later, at the bottom of the loop
11639   unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
11640   unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
11641   BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
11642     .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
11643   BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
11644     .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
11645
11646   // The subsequent operations should be using the destination registers of
11647   //the PHI instructions.
11648   if (invSrc) {
11649     t1 = F->getRegInfo().createVirtualRegister(RC);
11650     t2 = F->getRegInfo().createVirtualRegister(RC);
11651     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
11652     MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
11653   } else {
11654     t1 = dest1Oper.getReg();
11655     t2 = dest2Oper.getReg();
11656   }
11657
11658   int valArgIndx = lastAddrIndx + 1;
11659   assert((argOpers[valArgIndx]->isReg() ||
11660           argOpers[valArgIndx]->isImm()) &&
11661          "invalid operand");
11662   unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
11663   unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
11664   if (argOpers[valArgIndx]->isReg())
11665     MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
11666   else
11667     MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
11668   if (regOpcL != X86::MOV32rr)
11669     MIB.addReg(t1);
11670   (*MIB).addOperand(*argOpers[valArgIndx]);
11671   assert(argOpers[valArgIndx + 1]->isReg() ==
11672          argOpers[valArgIndx]->isReg());
11673   assert(argOpers[valArgIndx + 1]->isImm() ==
11674          argOpers[valArgIndx]->isImm());
11675   if (argOpers[valArgIndx + 1]->isReg())
11676     MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
11677   else
11678     MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
11679   if (regOpcH != X86::MOV32rr)
11680     MIB.addReg(t2);
11681   (*MIB).addOperand(*argOpers[valArgIndx + 1]);
11682
11683   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11684   MIB.addReg(t1);
11685   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
11686   MIB.addReg(t2);
11687
11688   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
11689   MIB.addReg(t5);
11690   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
11691   MIB.addReg(t6);
11692
11693   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
11694   for (int i=0; i <= lastAddrIndx; ++i)
11695     (*MIB).addOperand(*argOpers[i]);
11696
11697   assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11698   (*MIB).setMemRefs(bInstr->memoperands_begin(),
11699                     bInstr->memoperands_end());
11700
11701   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
11702   MIB.addReg(X86::EAX);
11703   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
11704   MIB.addReg(X86::EDX);
11705
11706   // insert branch
11707   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11708
11709   bInstr->eraseFromParent();   // The pseudo instruction is gone now.
11710   return nextMBB;
11711 }
11712
11713 // private utility function
11714 MachineBasicBlock *
11715 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
11716                                                       MachineBasicBlock *MBB,
11717                                                       unsigned cmovOpc) const {
11718   // For the atomic min/max operator, we generate
11719   //   thisMBB:
11720   //   newMBB:
11721   //     ld t1 = [min/max.addr]
11722   //     mov t2 = [min/max.val]
11723   //     cmp  t1, t2
11724   //     cmov[cond] t2 = t1
11725   //     mov EAX = t1
11726   //     lcs dest = [bitinstr.addr], t2  [EAX is implicit]
11727   //     bz   newMBB
11728   //     fallthrough -->nextMBB
11729   //
11730   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11731   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11732   MachineFunction::iterator MBBIter = MBB;
11733   ++MBBIter;
11734
11735   /// First build the CFG
11736   MachineFunction *F = MBB->getParent();
11737   MachineBasicBlock *thisMBB = MBB;
11738   MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
11739   MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
11740   F->insert(MBBIter, newMBB);
11741   F->insert(MBBIter, nextMBB);
11742
11743   // Transfer the remainder of thisMBB and its successor edges to nextMBB.
11744   nextMBB->splice(nextMBB->begin(), thisMBB,
11745                   llvm::next(MachineBasicBlock::iterator(mInstr)),
11746                   thisMBB->end());
11747   nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
11748
11749   // Update thisMBB to fall through to newMBB
11750   thisMBB->addSuccessor(newMBB);
11751
11752   // newMBB jumps to newMBB and fall through to nextMBB
11753   newMBB->addSuccessor(nextMBB);
11754   newMBB->addSuccessor(newMBB);
11755
11756   DebugLoc dl = mInstr->getDebugLoc();
11757   // Insert instructions into newMBB based on incoming instruction
11758   assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
11759          "unexpected number of operands");
11760   MachineOperand& destOper = mInstr->getOperand(0);
11761   MachineOperand* argOpers[2 + X86::AddrNumOperands];
11762   int numArgs = mInstr->getNumOperands() - 1;
11763   for (int i=0; i < numArgs; ++i)
11764     argOpers[i] = &mInstr->getOperand(i+1);
11765
11766   // x86 address has 4 operands: base, index, scale, and displacement
11767   int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
11768   int valArgIndx = lastAddrIndx + 1;
11769
11770   unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11771   MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
11772   for (int i=0; i <= lastAddrIndx; ++i)
11773     (*MIB).addOperand(*argOpers[i]);
11774
11775   // We only support register and immediate values
11776   assert((argOpers[valArgIndx]->isReg() ||
11777           argOpers[valArgIndx]->isImm()) &&
11778          "invalid operand");
11779
11780   unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11781   if (argOpers[valArgIndx]->isReg())
11782     MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
11783   else
11784     MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
11785   (*MIB).addOperand(*argOpers[valArgIndx]);
11786
11787   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
11788   MIB.addReg(t1);
11789
11790   MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
11791   MIB.addReg(t1);
11792   MIB.addReg(t2);
11793
11794   // Generate movc
11795   unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
11796   MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
11797   MIB.addReg(t2);
11798   MIB.addReg(t1);
11799
11800   // Cmp and exchange if none has modified the memory location
11801   MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
11802   for (int i=0; i <= lastAddrIndx; ++i)
11803     (*MIB).addOperand(*argOpers[i]);
11804   MIB.addReg(t3);
11805   assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
11806   (*MIB).setMemRefs(mInstr->memoperands_begin(),
11807                     mInstr->memoperands_end());
11808
11809   MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
11810   MIB.addReg(X86::EAX);
11811
11812   // insert branch
11813   BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
11814
11815   mInstr->eraseFromParent();   // The pseudo instruction is gone now.
11816   return nextMBB;
11817 }
11818
11819 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
11820 // or XMM0_V32I8 in AVX all of this code can be replaced with that
11821 // in the .td file.
11822 MachineBasicBlock *
11823 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
11824                             unsigned numArgs, bool memArg) const {
11825   assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
11826          "Target must have SSE4.2 or AVX features enabled");
11827
11828   DebugLoc dl = MI->getDebugLoc();
11829   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11830   unsigned Opc;
11831   if (!Subtarget->hasAVX()) {
11832     if (memArg)
11833       Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
11834     else
11835       Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
11836   } else {
11837     if (memArg)
11838       Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
11839     else
11840       Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
11841   }
11842
11843   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
11844   for (unsigned i = 0; i < numArgs; ++i) {
11845     MachineOperand &Op = MI->getOperand(i+1);
11846     if (!(Op.isReg() && Op.isImplicit()))
11847       MIB.addOperand(Op);
11848   }
11849   BuildMI(*BB, MI, dl,
11850     TII->get(Subtarget->hasAVX() ? X86::VMOVAPSrr : X86::MOVAPSrr),
11851              MI->getOperand(0).getReg())
11852     .addReg(X86::XMM0);
11853
11854   MI->eraseFromParent();
11855   return BB;
11856 }
11857
11858 MachineBasicBlock *
11859 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
11860   DebugLoc dl = MI->getDebugLoc();
11861   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11862
11863   // Address into RAX/EAX, other two args into ECX, EDX.
11864   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
11865   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11866   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
11867   for (int i = 0; i < X86::AddrNumOperands; ++i)
11868     MIB.addOperand(MI->getOperand(i));
11869
11870   unsigned ValOps = X86::AddrNumOperands;
11871   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11872     .addReg(MI->getOperand(ValOps).getReg());
11873   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
11874     .addReg(MI->getOperand(ValOps+1).getReg());
11875
11876   // The instruction doesn't actually take any operands though.
11877   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
11878
11879   MI->eraseFromParent(); // The pseudo is gone now.
11880   return BB;
11881 }
11882
11883 MachineBasicBlock *
11884 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
11885   DebugLoc dl = MI->getDebugLoc();
11886   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11887
11888   // First arg in ECX, the second in EAX.
11889   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
11890     .addReg(MI->getOperand(0).getReg());
11891   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
11892     .addReg(MI->getOperand(1).getReg());
11893
11894   // The instruction doesn't actually take any operands though.
11895   BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
11896
11897   MI->eraseFromParent(); // The pseudo is gone now.
11898   return BB;
11899 }
11900
11901 MachineBasicBlock *
11902 X86TargetLowering::EmitVAARG64WithCustomInserter(
11903                    MachineInstr *MI,
11904                    MachineBasicBlock *MBB) const {
11905   // Emit va_arg instruction on X86-64.
11906
11907   // Operands to this pseudo-instruction:
11908   // 0  ) Output        : destination address (reg)
11909   // 1-5) Input         : va_list address (addr, i64mem)
11910   // 6  ) ArgSize       : Size (in bytes) of vararg type
11911   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
11912   // 8  ) Align         : Alignment of type
11913   // 9  ) EFLAGS (implicit-def)
11914
11915   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
11916   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
11917
11918   unsigned DestReg = MI->getOperand(0).getReg();
11919   MachineOperand &Base = MI->getOperand(1);
11920   MachineOperand &Scale = MI->getOperand(2);
11921   MachineOperand &Index = MI->getOperand(3);
11922   MachineOperand &Disp = MI->getOperand(4);
11923   MachineOperand &Segment = MI->getOperand(5);
11924   unsigned ArgSize = MI->getOperand(6).getImm();
11925   unsigned ArgMode = MI->getOperand(7).getImm();
11926   unsigned Align = MI->getOperand(8).getImm();
11927
11928   // Memory Reference
11929   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
11930   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
11931   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
11932
11933   // Machine Information
11934   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
11935   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
11936   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
11937   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
11938   DebugLoc DL = MI->getDebugLoc();
11939
11940   // struct va_list {
11941   //   i32   gp_offset
11942   //   i32   fp_offset
11943   //   i64   overflow_area (address)
11944   //   i64   reg_save_area (address)
11945   // }
11946   // sizeof(va_list) = 24
11947   // alignment(va_list) = 8
11948
11949   unsigned TotalNumIntRegs = 6;
11950   unsigned TotalNumXMMRegs = 8;
11951   bool UseGPOffset = (ArgMode == 1);
11952   bool UseFPOffset = (ArgMode == 2);
11953   unsigned MaxOffset = TotalNumIntRegs * 8 +
11954                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
11955
11956   /* Align ArgSize to a multiple of 8 */
11957   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
11958   bool NeedsAlign = (Align > 8);
11959
11960   MachineBasicBlock *thisMBB = MBB;
11961   MachineBasicBlock *overflowMBB;
11962   MachineBasicBlock *offsetMBB;
11963   MachineBasicBlock *endMBB;
11964
11965   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
11966   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
11967   unsigned OffsetReg = 0;
11968
11969   if (!UseGPOffset && !UseFPOffset) {
11970     // If we only pull from the overflow region, we don't create a branch.
11971     // We don't need to alter control flow.
11972     OffsetDestReg = 0; // unused
11973     OverflowDestReg = DestReg;
11974
11975     offsetMBB = NULL;
11976     overflowMBB = thisMBB;
11977     endMBB = thisMBB;
11978   } else {
11979     // First emit code to check if gp_offset (or fp_offset) is below the bound.
11980     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
11981     // If not, pull from overflow_area. (branch to overflowMBB)
11982     //
11983     //       thisMBB
11984     //         |     .
11985     //         |        .
11986     //     offsetMBB   overflowMBB
11987     //         |        .
11988     //         |     .
11989     //        endMBB
11990
11991     // Registers for the PHI in endMBB
11992     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
11993     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
11994
11995     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
11996     MachineFunction *MF = MBB->getParent();
11997     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11998     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
11999     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12000
12001     MachineFunction::iterator MBBIter = MBB;
12002     ++MBBIter;
12003
12004     // Insert the new basic blocks
12005     MF->insert(MBBIter, offsetMBB);
12006     MF->insert(MBBIter, overflowMBB);
12007     MF->insert(MBBIter, endMBB);
12008
12009     // Transfer the remainder of MBB and its successor edges to endMBB.
12010     endMBB->splice(endMBB->begin(), thisMBB,
12011                     llvm::next(MachineBasicBlock::iterator(MI)),
12012                     thisMBB->end());
12013     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
12014
12015     // Make offsetMBB and overflowMBB successors of thisMBB
12016     thisMBB->addSuccessor(offsetMBB);
12017     thisMBB->addSuccessor(overflowMBB);
12018
12019     // endMBB is a successor of both offsetMBB and overflowMBB
12020     offsetMBB->addSuccessor(endMBB);
12021     overflowMBB->addSuccessor(endMBB);
12022
12023     // Load the offset value into a register
12024     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12025     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
12026       .addOperand(Base)
12027       .addOperand(Scale)
12028       .addOperand(Index)
12029       .addDisp(Disp, UseFPOffset ? 4 : 0)
12030       .addOperand(Segment)
12031       .setMemRefs(MMOBegin, MMOEnd);
12032
12033     // Check if there is enough room left to pull this argument.
12034     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
12035       .addReg(OffsetReg)
12036       .addImm(MaxOffset + 8 - ArgSizeA8);
12037
12038     // Branch to "overflowMBB" if offset >= max
12039     // Fall through to "offsetMBB" otherwise
12040     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
12041       .addMBB(overflowMBB);
12042   }
12043
12044   // In offsetMBB, emit code to use the reg_save_area.
12045   if (offsetMBB) {
12046     assert(OffsetReg != 0);
12047
12048     // Read the reg_save_area address.
12049     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
12050     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
12051       .addOperand(Base)
12052       .addOperand(Scale)
12053       .addOperand(Index)
12054       .addDisp(Disp, 16)
12055       .addOperand(Segment)
12056       .setMemRefs(MMOBegin, MMOEnd);
12057
12058     // Zero-extend the offset
12059     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
12060       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
12061         .addImm(0)
12062         .addReg(OffsetReg)
12063         .addImm(X86::sub_32bit);
12064
12065     // Add the offset to the reg_save_area to get the final address.
12066     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
12067       .addReg(OffsetReg64)
12068       .addReg(RegSaveReg);
12069
12070     // Compute the offset for the next argument
12071     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
12072     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
12073       .addReg(OffsetReg)
12074       .addImm(UseFPOffset ? 16 : 8);
12075
12076     // Store it back into the va_list.
12077     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
12078       .addOperand(Base)
12079       .addOperand(Scale)
12080       .addOperand(Index)
12081       .addDisp(Disp, UseFPOffset ? 4 : 0)
12082       .addOperand(Segment)
12083       .addReg(NextOffsetReg)
12084       .setMemRefs(MMOBegin, MMOEnd);
12085
12086     // Jump to endMBB
12087     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
12088       .addMBB(endMBB);
12089   }
12090
12091   //
12092   // Emit code to use overflow area
12093   //
12094
12095   // Load the overflow_area address into a register.
12096   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
12097   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
12098     .addOperand(Base)
12099     .addOperand(Scale)
12100     .addOperand(Index)
12101     .addDisp(Disp, 8)
12102     .addOperand(Segment)
12103     .setMemRefs(MMOBegin, MMOEnd);
12104
12105   // If we need to align it, do so. Otherwise, just copy the address
12106   // to OverflowDestReg.
12107   if (NeedsAlign) {
12108     // Align the overflow address
12109     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
12110     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
12111
12112     // aligned_addr = (addr + (align-1)) & ~(align-1)
12113     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
12114       .addReg(OverflowAddrReg)
12115       .addImm(Align-1);
12116
12117     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
12118       .addReg(TmpReg)
12119       .addImm(~(uint64_t)(Align-1));
12120   } else {
12121     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
12122       .addReg(OverflowAddrReg);
12123   }
12124
12125   // Compute the next overflow address after this argument.
12126   // (the overflow address should be kept 8-byte aligned)
12127   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
12128   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
12129     .addReg(OverflowDestReg)
12130     .addImm(ArgSizeA8);
12131
12132   // Store the new overflow address.
12133   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
12134     .addOperand(Base)
12135     .addOperand(Scale)
12136     .addOperand(Index)
12137     .addDisp(Disp, 8)
12138     .addOperand(Segment)
12139     .addReg(NextAddrReg)
12140     .setMemRefs(MMOBegin, MMOEnd);
12141
12142   // If we branched, emit the PHI to the front of endMBB.
12143   if (offsetMBB) {
12144     BuildMI(*endMBB, endMBB->begin(), DL,
12145             TII->get(X86::PHI), DestReg)
12146       .addReg(OffsetDestReg).addMBB(offsetMBB)
12147       .addReg(OverflowDestReg).addMBB(overflowMBB);
12148   }
12149
12150   // Erase the pseudo instruction
12151   MI->eraseFromParent();
12152
12153   return endMBB;
12154 }
12155
12156 MachineBasicBlock *
12157 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
12158                                                  MachineInstr *MI,
12159                                                  MachineBasicBlock *MBB) const {
12160   // Emit code to save XMM registers to the stack. The ABI says that the
12161   // number of registers to save is given in %al, so it's theoretically
12162   // possible to do an indirect jump trick to avoid saving all of them,
12163   // however this code takes a simpler approach and just executes all
12164   // of the stores if %al is non-zero. It's less code, and it's probably
12165   // easier on the hardware branch predictor, and stores aren't all that
12166   // expensive anyway.
12167
12168   // Create the new basic blocks. One block contains all the XMM stores,
12169   // and one block is the final destination regardless of whether any
12170   // stores were performed.
12171   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
12172   MachineFunction *F = MBB->getParent();
12173   MachineFunction::iterator MBBIter = MBB;
12174   ++MBBIter;
12175   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
12176   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
12177   F->insert(MBBIter, XMMSaveMBB);
12178   F->insert(MBBIter, EndMBB);
12179
12180   // Transfer the remainder of MBB and its successor edges to EndMBB.
12181   EndMBB->splice(EndMBB->begin(), MBB,
12182                  llvm::next(MachineBasicBlock::iterator(MI)),
12183                  MBB->end());
12184   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
12185
12186   // The original block will now fall through to the XMM save block.
12187   MBB->addSuccessor(XMMSaveMBB);
12188   // The XMMSaveMBB will fall through to the end block.
12189   XMMSaveMBB->addSuccessor(EndMBB);
12190
12191   // Now add the instructions.
12192   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12193   DebugLoc DL = MI->getDebugLoc();
12194
12195   unsigned CountReg = MI->getOperand(0).getReg();
12196   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
12197   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
12198
12199   if (!Subtarget->isTargetWin64()) {
12200     // If %al is 0, branch around the XMM save block.
12201     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
12202     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
12203     MBB->addSuccessor(EndMBB);
12204   }
12205
12206   unsigned MOVOpc = Subtarget->hasAVX() ? X86::VMOVAPSmr : X86::MOVAPSmr;
12207   // In the XMM save block, save all the XMM argument registers.
12208   for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
12209     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
12210     MachineMemOperand *MMO =
12211       F->getMachineMemOperand(
12212           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
12213         MachineMemOperand::MOStore,
12214         /*Size=*/16, /*Align=*/16);
12215     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
12216       .addFrameIndex(RegSaveFrameIndex)
12217       .addImm(/*Scale=*/1)
12218       .addReg(/*IndexReg=*/0)
12219       .addImm(/*Disp=*/Offset)
12220       .addReg(/*Segment=*/0)
12221       .addReg(MI->getOperand(i).getReg())
12222       .addMemOperand(MMO);
12223   }
12224
12225   MI->eraseFromParent();   // The pseudo instruction is gone now.
12226
12227   return EndMBB;
12228 }
12229
12230 MachineBasicBlock *
12231 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
12232                                      MachineBasicBlock *BB) const {
12233   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12234   DebugLoc DL = MI->getDebugLoc();
12235
12236   // To "insert" a SELECT_CC instruction, we actually have to insert the
12237   // diamond control-flow pattern.  The incoming instruction knows the
12238   // destination vreg to set, the condition code register to branch on, the
12239   // true/false values to select between, and a branch opcode to use.
12240   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12241   MachineFunction::iterator It = BB;
12242   ++It;
12243
12244   //  thisMBB:
12245   //  ...
12246   //   TrueVal = ...
12247   //   cmpTY ccX, r1, r2
12248   //   bCC copy1MBB
12249   //   fallthrough --> copy0MBB
12250   MachineBasicBlock *thisMBB = BB;
12251   MachineFunction *F = BB->getParent();
12252   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
12253   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
12254   F->insert(It, copy0MBB);
12255   F->insert(It, sinkMBB);
12256
12257   // If the EFLAGS register isn't dead in the terminator, then claim that it's
12258   // live into the sink and copy blocks.
12259   if (!MI->killsRegister(X86::EFLAGS)) {
12260     copy0MBB->addLiveIn(X86::EFLAGS);
12261     sinkMBB->addLiveIn(X86::EFLAGS);
12262   }
12263
12264   // Transfer the remainder of BB and its successor edges to sinkMBB.
12265   sinkMBB->splice(sinkMBB->begin(), BB,
12266                   llvm::next(MachineBasicBlock::iterator(MI)),
12267                   BB->end());
12268   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
12269
12270   // Add the true and fallthrough blocks as its successors.
12271   BB->addSuccessor(copy0MBB);
12272   BB->addSuccessor(sinkMBB);
12273
12274   // Create the conditional branch instruction.
12275   unsigned Opc =
12276     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
12277   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
12278
12279   //  copy0MBB:
12280   //   %FalseValue = ...
12281   //   # fallthrough to sinkMBB
12282   copy0MBB->addSuccessor(sinkMBB);
12283
12284   //  sinkMBB:
12285   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
12286   //  ...
12287   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
12288           TII->get(X86::PHI), MI->getOperand(0).getReg())
12289     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
12290     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
12291
12292   MI->eraseFromParent();   // The pseudo instruction is gone now.
12293   return sinkMBB;
12294 }
12295
12296 MachineBasicBlock *
12297 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
12298                                         bool Is64Bit) const {
12299   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12300   DebugLoc DL = MI->getDebugLoc();
12301   MachineFunction *MF = BB->getParent();
12302   const BasicBlock *LLVM_BB = BB->getBasicBlock();
12303
12304   assert(EnableSegmentedStacks);
12305
12306   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
12307   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
12308
12309   // BB:
12310   //  ... [Till the alloca]
12311   // If stacklet is not large enough, jump to mallocMBB
12312   //
12313   // bumpMBB:
12314   //  Allocate by subtracting from RSP
12315   //  Jump to continueMBB
12316   //
12317   // mallocMBB:
12318   //  Allocate by call to runtime
12319   //
12320   // continueMBB:
12321   //  ...
12322   //  [rest of original BB]
12323   //
12324
12325   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12326   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12327   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
12328
12329   MachineRegisterInfo &MRI = MF->getRegInfo();
12330   const TargetRegisterClass *AddrRegClass =
12331     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
12332
12333   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12334     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
12335     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
12336     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
12337     sizeVReg = MI->getOperand(1).getReg(),
12338     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
12339
12340   MachineFunction::iterator MBBIter = BB;
12341   ++MBBIter;
12342
12343   MF->insert(MBBIter, bumpMBB);
12344   MF->insert(MBBIter, mallocMBB);
12345   MF->insert(MBBIter, continueMBB);
12346
12347   continueMBB->splice(continueMBB->begin(), BB, llvm::next
12348                       (MachineBasicBlock::iterator(MI)), BB->end());
12349   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
12350
12351   // Add code to the main basic block to check if the stack limit has been hit,
12352   // and if so, jump to mallocMBB otherwise to bumpMBB.
12353   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
12354   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
12355     .addReg(tmpSPVReg).addReg(sizeVReg);
12356   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
12357     .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg)
12358     .addReg(SPLimitVReg);
12359   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
12360
12361   // bumpMBB simply decreases the stack pointer, since we know the current
12362   // stacklet has enough space.
12363   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
12364     .addReg(SPLimitVReg);
12365   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
12366     .addReg(SPLimitVReg);
12367   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12368
12369   // Calls into a routine in libgcc to allocate more space from the heap.
12370   if (Is64Bit) {
12371     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
12372       .addReg(sizeVReg);
12373     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
12374     .addExternalSymbol("__morestack_allocate_stack_space").addReg(X86::RDI);
12375   } else {
12376     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
12377       .addImm(12);
12378     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
12379     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
12380       .addExternalSymbol("__morestack_allocate_stack_space");
12381   }
12382
12383   if (!Is64Bit)
12384     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
12385       .addImm(16);
12386
12387   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
12388     .addReg(Is64Bit ? X86::RAX : X86::EAX);
12389   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
12390
12391   // Set up the CFG correctly.
12392   BB->addSuccessor(bumpMBB);
12393   BB->addSuccessor(mallocMBB);
12394   mallocMBB->addSuccessor(continueMBB);
12395   bumpMBB->addSuccessor(continueMBB);
12396
12397   // Take care of the PHI nodes.
12398   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
12399           MI->getOperand(0).getReg())
12400     .addReg(mallocPtrVReg).addMBB(mallocMBB)
12401     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
12402
12403   // Delete the original pseudo instruction.
12404   MI->eraseFromParent();
12405
12406   // And we're done.
12407   return continueMBB;
12408 }
12409
12410 MachineBasicBlock *
12411 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
12412                                           MachineBasicBlock *BB) const {
12413   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12414   DebugLoc DL = MI->getDebugLoc();
12415
12416   assert(!Subtarget->isTargetEnvMacho());
12417
12418   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
12419   // non-trivial part is impdef of ESP.
12420
12421   if (Subtarget->isTargetWin64()) {
12422     if (Subtarget->isTargetCygMing()) {
12423       // ___chkstk(Mingw64):
12424       // Clobbers R10, R11, RAX and EFLAGS.
12425       // Updates RSP.
12426       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12427         .addExternalSymbol("___chkstk")
12428         .addReg(X86::RAX, RegState::Implicit)
12429         .addReg(X86::RSP, RegState::Implicit)
12430         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
12431         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
12432         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12433     } else {
12434       // __chkstk(MSVCRT): does not update stack pointer.
12435       // Clobbers R10, R11 and EFLAGS.
12436       // FIXME: RAX(allocated size) might be reused and not killed.
12437       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
12438         .addExternalSymbol("__chkstk")
12439         .addReg(X86::RAX, RegState::Implicit)
12440         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12441       // RAX has the offset to subtracted from RSP.
12442       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
12443         .addReg(X86::RSP)
12444         .addReg(X86::RAX);
12445     }
12446   } else {
12447     const char *StackProbeSymbol =
12448       Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
12449
12450     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
12451       .addExternalSymbol(StackProbeSymbol)
12452       .addReg(X86::EAX, RegState::Implicit)
12453       .addReg(X86::ESP, RegState::Implicit)
12454       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
12455       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
12456       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
12457   }
12458
12459   MI->eraseFromParent();   // The pseudo instruction is gone now.
12460   return BB;
12461 }
12462
12463 MachineBasicBlock *
12464 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
12465                                       MachineBasicBlock *BB) const {
12466   // This is pretty easy.  We're taking the value that we received from
12467   // our load from the relocation, sticking it in either RDI (x86-64)
12468   // or EAX and doing an indirect call.  The return value will then
12469   // be in the normal return register.
12470   const X86InstrInfo *TII
12471     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
12472   DebugLoc DL = MI->getDebugLoc();
12473   MachineFunction *F = BB->getParent();
12474
12475   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
12476   assert(MI->getOperand(3).isGlobal() && "This should be a global");
12477
12478   if (Subtarget->is64Bit()) {
12479     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12480                                       TII->get(X86::MOV64rm), X86::RDI)
12481     .addReg(X86::RIP)
12482     .addImm(0).addReg(0)
12483     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12484                       MI->getOperand(3).getTargetFlags())
12485     .addReg(0);
12486     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
12487     addDirectMem(MIB, X86::RDI);
12488   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
12489     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12490                                       TII->get(X86::MOV32rm), X86::EAX)
12491     .addReg(0)
12492     .addImm(0).addReg(0)
12493     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12494                       MI->getOperand(3).getTargetFlags())
12495     .addReg(0);
12496     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12497     addDirectMem(MIB, X86::EAX);
12498   } else {
12499     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
12500                                       TII->get(X86::MOV32rm), X86::EAX)
12501     .addReg(TII->getGlobalBaseReg(F))
12502     .addImm(0).addReg(0)
12503     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
12504                       MI->getOperand(3).getTargetFlags())
12505     .addReg(0);
12506     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
12507     addDirectMem(MIB, X86::EAX);
12508   }
12509
12510   MI->eraseFromParent(); // The pseudo instruction is gone now.
12511   return BB;
12512 }
12513
12514 MachineBasicBlock *
12515 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
12516                                                MachineBasicBlock *BB) const {
12517   switch (MI->getOpcode()) {
12518   default: assert(0 && "Unexpected instr type to insert");
12519   case X86::TAILJMPd64:
12520   case X86::TAILJMPr64:
12521   case X86::TAILJMPm64:
12522     assert(0 && "TAILJMP64 would not be touched here.");
12523   case X86::TCRETURNdi64:
12524   case X86::TCRETURNri64:
12525   case X86::TCRETURNmi64:
12526     // Defs of TCRETURNxx64 has Win64's callee-saved registers, as subset.
12527     // On AMD64, additional defs should be added before register allocation.
12528     if (!Subtarget->isTargetWin64()) {
12529       MI->addRegisterDefined(X86::RSI);
12530       MI->addRegisterDefined(X86::RDI);
12531       MI->addRegisterDefined(X86::XMM6);
12532       MI->addRegisterDefined(X86::XMM7);
12533       MI->addRegisterDefined(X86::XMM8);
12534       MI->addRegisterDefined(X86::XMM9);
12535       MI->addRegisterDefined(X86::XMM10);
12536       MI->addRegisterDefined(X86::XMM11);
12537       MI->addRegisterDefined(X86::XMM12);
12538       MI->addRegisterDefined(X86::XMM13);
12539       MI->addRegisterDefined(X86::XMM14);
12540       MI->addRegisterDefined(X86::XMM15);
12541     }
12542     return BB;
12543   case X86::WIN_ALLOCA:
12544     return EmitLoweredWinAlloca(MI, BB);
12545   case X86::SEG_ALLOCA_32:
12546     return EmitLoweredSegAlloca(MI, BB, false);
12547   case X86::SEG_ALLOCA_64:
12548     return EmitLoweredSegAlloca(MI, BB, true);
12549   case X86::TLSCall_32:
12550   case X86::TLSCall_64:
12551     return EmitLoweredTLSCall(MI, BB);
12552   case X86::CMOV_GR8:
12553   case X86::CMOV_FR32:
12554   case X86::CMOV_FR64:
12555   case X86::CMOV_V4F32:
12556   case X86::CMOV_V2F64:
12557   case X86::CMOV_V2I64:
12558   case X86::CMOV_V8F32:
12559   case X86::CMOV_V4F64:
12560   case X86::CMOV_V4I64:
12561   case X86::CMOV_GR16:
12562   case X86::CMOV_GR32:
12563   case X86::CMOV_RFP32:
12564   case X86::CMOV_RFP64:
12565   case X86::CMOV_RFP80:
12566     return EmitLoweredSelect(MI, BB);
12567
12568   case X86::FP32_TO_INT16_IN_MEM:
12569   case X86::FP32_TO_INT32_IN_MEM:
12570   case X86::FP32_TO_INT64_IN_MEM:
12571   case X86::FP64_TO_INT16_IN_MEM:
12572   case X86::FP64_TO_INT32_IN_MEM:
12573   case X86::FP64_TO_INT64_IN_MEM:
12574   case X86::FP80_TO_INT16_IN_MEM:
12575   case X86::FP80_TO_INT32_IN_MEM:
12576   case X86::FP80_TO_INT64_IN_MEM: {
12577     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
12578     DebugLoc DL = MI->getDebugLoc();
12579
12580     // Change the floating point control register to use "round towards zero"
12581     // mode when truncating to an integer value.
12582     MachineFunction *F = BB->getParent();
12583     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
12584     addFrameReference(BuildMI(*BB, MI, DL,
12585                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
12586
12587     // Load the old value of the high byte of the control word...
12588     unsigned OldCW =
12589       F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
12590     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
12591                       CWFrameIdx);
12592
12593     // Set the high part to be round to zero...
12594     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
12595       .addImm(0xC7F);
12596
12597     // Reload the modified control word now...
12598     addFrameReference(BuildMI(*BB, MI, DL,
12599                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12600
12601     // Restore the memory image of control word to original value
12602     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
12603       .addReg(OldCW);
12604
12605     // Get the X86 opcode to use.
12606     unsigned Opc;
12607     switch (MI->getOpcode()) {
12608     default: llvm_unreachable("illegal opcode!");
12609     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
12610     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
12611     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
12612     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
12613     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
12614     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
12615     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
12616     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
12617     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
12618     }
12619
12620     X86AddressMode AM;
12621     MachineOperand &Op = MI->getOperand(0);
12622     if (Op.isReg()) {
12623       AM.BaseType = X86AddressMode::RegBase;
12624       AM.Base.Reg = Op.getReg();
12625     } else {
12626       AM.BaseType = X86AddressMode::FrameIndexBase;
12627       AM.Base.FrameIndex = Op.getIndex();
12628     }
12629     Op = MI->getOperand(1);
12630     if (Op.isImm())
12631       AM.Scale = Op.getImm();
12632     Op = MI->getOperand(2);
12633     if (Op.isImm())
12634       AM.IndexReg = Op.getImm();
12635     Op = MI->getOperand(3);
12636     if (Op.isGlobal()) {
12637       AM.GV = Op.getGlobal();
12638     } else {
12639       AM.Disp = Op.getImm();
12640     }
12641     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
12642                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
12643
12644     // Reload the original control word now.
12645     addFrameReference(BuildMI(*BB, MI, DL,
12646                               TII->get(X86::FLDCW16m)), CWFrameIdx);
12647
12648     MI->eraseFromParent();   // The pseudo instruction is gone now.
12649     return BB;
12650   }
12651     // String/text processing lowering.
12652   case X86::PCMPISTRM128REG:
12653   case X86::VPCMPISTRM128REG:
12654     return EmitPCMP(MI, BB, 3, false /* in-mem */);
12655   case X86::PCMPISTRM128MEM:
12656   case X86::VPCMPISTRM128MEM:
12657     return EmitPCMP(MI, BB, 3, true /* in-mem */);
12658   case X86::PCMPESTRM128REG:
12659   case X86::VPCMPESTRM128REG:
12660     return EmitPCMP(MI, BB, 5, false /* in mem */);
12661   case X86::PCMPESTRM128MEM:
12662   case X86::VPCMPESTRM128MEM:
12663     return EmitPCMP(MI, BB, 5, true /* in mem */);
12664
12665     // Thread synchronization.
12666   case X86::MONITOR:
12667     return EmitMonitor(MI, BB);
12668   case X86::MWAIT:
12669     return EmitMwait(MI, BB);
12670
12671     // Atomic Lowering.
12672   case X86::ATOMAND32:
12673     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12674                                                X86::AND32ri, X86::MOV32rm,
12675                                                X86::LCMPXCHG32,
12676                                                X86::NOT32r, X86::EAX,
12677                                                X86::GR32RegisterClass);
12678   case X86::ATOMOR32:
12679     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
12680                                                X86::OR32ri, X86::MOV32rm,
12681                                                X86::LCMPXCHG32,
12682                                                X86::NOT32r, X86::EAX,
12683                                                X86::GR32RegisterClass);
12684   case X86::ATOMXOR32:
12685     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
12686                                                X86::XOR32ri, X86::MOV32rm,
12687                                                X86::LCMPXCHG32,
12688                                                X86::NOT32r, X86::EAX,
12689                                                X86::GR32RegisterClass);
12690   case X86::ATOMNAND32:
12691     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
12692                                                X86::AND32ri, X86::MOV32rm,
12693                                                X86::LCMPXCHG32,
12694                                                X86::NOT32r, X86::EAX,
12695                                                X86::GR32RegisterClass, true);
12696   case X86::ATOMMIN32:
12697     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
12698   case X86::ATOMMAX32:
12699     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
12700   case X86::ATOMUMIN32:
12701     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
12702   case X86::ATOMUMAX32:
12703     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
12704
12705   case X86::ATOMAND16:
12706     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12707                                                X86::AND16ri, X86::MOV16rm,
12708                                                X86::LCMPXCHG16,
12709                                                X86::NOT16r, X86::AX,
12710                                                X86::GR16RegisterClass);
12711   case X86::ATOMOR16:
12712     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
12713                                                X86::OR16ri, X86::MOV16rm,
12714                                                X86::LCMPXCHG16,
12715                                                X86::NOT16r, X86::AX,
12716                                                X86::GR16RegisterClass);
12717   case X86::ATOMXOR16:
12718     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
12719                                                X86::XOR16ri, X86::MOV16rm,
12720                                                X86::LCMPXCHG16,
12721                                                X86::NOT16r, X86::AX,
12722                                                X86::GR16RegisterClass);
12723   case X86::ATOMNAND16:
12724     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
12725                                                X86::AND16ri, X86::MOV16rm,
12726                                                X86::LCMPXCHG16,
12727                                                X86::NOT16r, X86::AX,
12728                                                X86::GR16RegisterClass, true);
12729   case X86::ATOMMIN16:
12730     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
12731   case X86::ATOMMAX16:
12732     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
12733   case X86::ATOMUMIN16:
12734     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
12735   case X86::ATOMUMAX16:
12736     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
12737
12738   case X86::ATOMAND8:
12739     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12740                                                X86::AND8ri, X86::MOV8rm,
12741                                                X86::LCMPXCHG8,
12742                                                X86::NOT8r, X86::AL,
12743                                                X86::GR8RegisterClass);
12744   case X86::ATOMOR8:
12745     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
12746                                                X86::OR8ri, X86::MOV8rm,
12747                                                X86::LCMPXCHG8,
12748                                                X86::NOT8r, X86::AL,
12749                                                X86::GR8RegisterClass);
12750   case X86::ATOMXOR8:
12751     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
12752                                                X86::XOR8ri, X86::MOV8rm,
12753                                                X86::LCMPXCHG8,
12754                                                X86::NOT8r, X86::AL,
12755                                                X86::GR8RegisterClass);
12756   case X86::ATOMNAND8:
12757     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
12758                                                X86::AND8ri, X86::MOV8rm,
12759                                                X86::LCMPXCHG8,
12760                                                X86::NOT8r, X86::AL,
12761                                                X86::GR8RegisterClass, true);
12762   // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
12763   // This group is for 64-bit host.
12764   case X86::ATOMAND64:
12765     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12766                                                X86::AND64ri32, X86::MOV64rm,
12767                                                X86::LCMPXCHG64,
12768                                                X86::NOT64r, X86::RAX,
12769                                                X86::GR64RegisterClass);
12770   case X86::ATOMOR64:
12771     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
12772                                                X86::OR64ri32, X86::MOV64rm,
12773                                                X86::LCMPXCHG64,
12774                                                X86::NOT64r, X86::RAX,
12775                                                X86::GR64RegisterClass);
12776   case X86::ATOMXOR64:
12777     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
12778                                                X86::XOR64ri32, X86::MOV64rm,
12779                                                X86::LCMPXCHG64,
12780                                                X86::NOT64r, X86::RAX,
12781                                                X86::GR64RegisterClass);
12782   case X86::ATOMNAND64:
12783     return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
12784                                                X86::AND64ri32, X86::MOV64rm,
12785                                                X86::LCMPXCHG64,
12786                                                X86::NOT64r, X86::RAX,
12787                                                X86::GR64RegisterClass, true);
12788   case X86::ATOMMIN64:
12789     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
12790   case X86::ATOMMAX64:
12791     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
12792   case X86::ATOMUMIN64:
12793     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
12794   case X86::ATOMUMAX64:
12795     return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
12796
12797   // This group does 64-bit operations on a 32-bit host.
12798   case X86::ATOMAND6432:
12799     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12800                                                X86::AND32rr, X86::AND32rr,
12801                                                X86::AND32ri, X86::AND32ri,
12802                                                false);
12803   case X86::ATOMOR6432:
12804     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12805                                                X86::OR32rr, X86::OR32rr,
12806                                                X86::OR32ri, X86::OR32ri,
12807                                                false);
12808   case X86::ATOMXOR6432:
12809     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12810                                                X86::XOR32rr, X86::XOR32rr,
12811                                                X86::XOR32ri, X86::XOR32ri,
12812                                                false);
12813   case X86::ATOMNAND6432:
12814     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12815                                                X86::AND32rr, X86::AND32rr,
12816                                                X86::AND32ri, X86::AND32ri,
12817                                                true);
12818   case X86::ATOMADD6432:
12819     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12820                                                X86::ADD32rr, X86::ADC32rr,
12821                                                X86::ADD32ri, X86::ADC32ri,
12822                                                false);
12823   case X86::ATOMSUB6432:
12824     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12825                                                X86::SUB32rr, X86::SBB32rr,
12826                                                X86::SUB32ri, X86::SBB32ri,
12827                                                false);
12828   case X86::ATOMSWAP6432:
12829     return EmitAtomicBit6432WithCustomInserter(MI, BB,
12830                                                X86::MOV32rr, X86::MOV32rr,
12831                                                X86::MOV32ri, X86::MOV32ri,
12832                                                false);
12833   case X86::VASTART_SAVE_XMM_REGS:
12834     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
12835
12836   case X86::VAARG_64:
12837     return EmitVAARG64WithCustomInserter(MI, BB);
12838   }
12839 }
12840
12841 //===----------------------------------------------------------------------===//
12842 //                           X86 Optimization Hooks
12843 //===----------------------------------------------------------------------===//
12844
12845 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
12846                                                        const APInt &Mask,
12847                                                        APInt &KnownZero,
12848                                                        APInt &KnownOne,
12849                                                        const SelectionDAG &DAG,
12850                                                        unsigned Depth) const {
12851   unsigned Opc = Op.getOpcode();
12852   assert((Opc >= ISD::BUILTIN_OP_END ||
12853           Opc == ISD::INTRINSIC_WO_CHAIN ||
12854           Opc == ISD::INTRINSIC_W_CHAIN ||
12855           Opc == ISD::INTRINSIC_VOID) &&
12856          "Should use MaskedValueIsZero if you don't know whether Op"
12857          " is a target node!");
12858
12859   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
12860   switch (Opc) {
12861   default: break;
12862   case X86ISD::ADD:
12863   case X86ISD::SUB:
12864   case X86ISD::ADC:
12865   case X86ISD::SBB:
12866   case X86ISD::SMUL:
12867   case X86ISD::UMUL:
12868   case X86ISD::INC:
12869   case X86ISD::DEC:
12870   case X86ISD::OR:
12871   case X86ISD::XOR:
12872   case X86ISD::AND:
12873     // These nodes' second result is a boolean.
12874     if (Op.getResNo() == 0)
12875       break;
12876     // Fallthrough
12877   case X86ISD::SETCC:
12878     KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
12879                                        Mask.getBitWidth() - 1);
12880     break;
12881   case ISD::INTRINSIC_WO_CHAIN: {
12882     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12883     unsigned NumLoBits = 0;
12884     switch (IntId) {
12885     default: break;
12886     case Intrinsic::x86_sse_movmsk_ps:
12887     case Intrinsic::x86_avx_movmsk_ps_256:
12888     case Intrinsic::x86_sse2_movmsk_pd:
12889     case Intrinsic::x86_avx_movmsk_pd_256:
12890     case Intrinsic::x86_mmx_pmovmskb:
12891     case Intrinsic::x86_sse2_pmovmskb_128: {
12892       // High bits of movmskp{s|d}, pmovmskb are known zero.
12893       switch (IntId) {
12894         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
12895         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
12896         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
12897         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
12898         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
12899         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
12900       }
12901       KnownZero = APInt::getHighBitsSet(Mask.getBitWidth(),
12902                                         Mask.getBitWidth() - NumLoBits);
12903       break;
12904     }
12905     }
12906     break;
12907   }
12908   }
12909 }
12910
12911 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
12912                                                          unsigned Depth) const {
12913   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
12914   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
12915     return Op.getValueType().getScalarType().getSizeInBits();
12916
12917   // Fallback case.
12918   return 1;
12919 }
12920
12921 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
12922 /// node is a GlobalAddress + offset.
12923 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
12924                                        const GlobalValue* &GA,
12925                                        int64_t &Offset) const {
12926   if (N->getOpcode() == X86ISD::Wrapper) {
12927     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
12928       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
12929       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
12930       return true;
12931     }
12932   }
12933   return TargetLowering::isGAPlusOffset(N, GA, Offset);
12934 }
12935
12936 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
12937 /// same as extracting the high 128-bit part of 256-bit vector and then
12938 /// inserting the result into the low part of a new 256-bit vector
12939 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
12940   EVT VT = SVOp->getValueType(0);
12941   int NumElems = VT.getVectorNumElements();
12942
12943   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
12944   for (int i = 0, j = NumElems/2; i < NumElems/2; ++i, ++j)
12945     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12946         SVOp->getMaskElt(j) >= 0)
12947       return false;
12948
12949   return true;
12950 }
12951
12952 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
12953 /// same as extracting the low 128-bit part of 256-bit vector and then
12954 /// inserting the result into the high part of a new 256-bit vector
12955 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
12956   EVT VT = SVOp->getValueType(0);
12957   int NumElems = VT.getVectorNumElements();
12958
12959   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
12960   for (int i = NumElems/2, j = 0; i < NumElems; ++i, ++j)
12961     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
12962         SVOp->getMaskElt(j) >= 0)
12963       return false;
12964
12965   return true;
12966 }
12967
12968 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
12969 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
12970                                         TargetLowering::DAGCombinerInfo &DCI) {
12971   DebugLoc dl = N->getDebugLoc();
12972   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
12973   SDValue V1 = SVOp->getOperand(0);
12974   SDValue V2 = SVOp->getOperand(1);
12975   EVT VT = SVOp->getValueType(0);
12976   int NumElems = VT.getVectorNumElements();
12977
12978   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
12979       V2.getOpcode() == ISD::CONCAT_VECTORS) {
12980     //
12981     //                   0,0,0,...
12982     //                      |
12983     //    V      UNDEF    BUILD_VECTOR    UNDEF
12984     //     \      /           \           /
12985     //  CONCAT_VECTOR         CONCAT_VECTOR
12986     //         \                  /
12987     //          \                /
12988     //          RESULT: V + zero extended
12989     //
12990     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
12991         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
12992         V1.getOperand(1).getOpcode() != ISD::UNDEF)
12993       return SDValue();
12994
12995     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
12996       return SDValue();
12997
12998     // To match the shuffle mask, the first half of the mask should
12999     // be exactly the first vector, and all the rest a splat with the
13000     // first element of the second one.
13001     for (int i = 0; i < NumElems/2; ++i)
13002       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
13003           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
13004         return SDValue();
13005
13006     // Emit a zeroed vector and insert the desired subvector on its
13007     // first half.
13008     SDValue Zeros = getZeroVector(VT, true /* HasXMMInt */, DAG, dl);
13009     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0),
13010                          DAG.getConstant(0, MVT::i32), DAG, dl);
13011     return DCI.CombineTo(N, InsV);
13012   }
13013
13014   //===--------------------------------------------------------------------===//
13015   // Combine some shuffles into subvector extracts and inserts:
13016   //
13017
13018   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
13019   if (isShuffleHigh128VectorInsertLow(SVOp)) {
13020     SDValue V = Extract128BitVector(V1, DAG.getConstant(NumElems/2, MVT::i32),
13021                                     DAG, dl);
13022     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13023                                       V, DAG.getConstant(0, MVT::i32), DAG, dl);
13024     return DCI.CombineTo(N, InsV);
13025   }
13026
13027   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
13028   if (isShuffleLow128VectorInsertHigh(SVOp)) {
13029     SDValue V = Extract128BitVector(V1, DAG.getConstant(0, MVT::i32), DAG, dl);
13030     SDValue InsV = Insert128BitVector(DAG.getNode(ISD::UNDEF, dl, VT),
13031                              V, DAG.getConstant(NumElems/2, MVT::i32), DAG, dl);
13032     return DCI.CombineTo(N, InsV);
13033   }
13034
13035   return SDValue();
13036 }
13037
13038 /// PerformShuffleCombine - Performs several different shuffle combines.
13039 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
13040                                      TargetLowering::DAGCombinerInfo &DCI,
13041                                      const X86Subtarget *Subtarget) {
13042   DebugLoc dl = N->getDebugLoc();
13043   EVT VT = N->getValueType(0);
13044
13045   // Don't create instructions with illegal types after legalize types has run.
13046   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13047   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
13048     return SDValue();
13049
13050   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
13051   if (Subtarget->hasAVX() && VT.getSizeInBits() == 256 &&
13052       N->getOpcode() == ISD::VECTOR_SHUFFLE)
13053     return PerformShuffleCombine256(N, DAG, DCI);
13054
13055   // Only handle 128 wide vector from here on.
13056   if (VT.getSizeInBits() != 128)
13057     return SDValue();
13058
13059   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
13060   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
13061   // consecutive, non-overlapping, and in the right order.
13062   SmallVector<SDValue, 16> Elts;
13063   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
13064     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
13065
13066   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
13067 }
13068
13069 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
13070 /// generation and convert it from being a bunch of shuffles and extracts
13071 /// to a simple store and scalar loads to extract the elements.
13072 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
13073                                                 const TargetLowering &TLI) {
13074   SDValue InputVector = N->getOperand(0);
13075
13076   // Only operate on vectors of 4 elements, where the alternative shuffling
13077   // gets to be more expensive.
13078   if (InputVector.getValueType() != MVT::v4i32)
13079     return SDValue();
13080
13081   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
13082   // single use which is a sign-extend or zero-extend, and all elements are
13083   // used.
13084   SmallVector<SDNode *, 4> Uses;
13085   unsigned ExtractedElements = 0;
13086   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
13087        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
13088     if (UI.getUse().getResNo() != InputVector.getResNo())
13089       return SDValue();
13090
13091     SDNode *Extract = *UI;
13092     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13093       return SDValue();
13094
13095     if (Extract->getValueType(0) != MVT::i32)
13096       return SDValue();
13097     if (!Extract->hasOneUse())
13098       return SDValue();
13099     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
13100         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
13101       return SDValue();
13102     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
13103       return SDValue();
13104
13105     // Record which element was extracted.
13106     ExtractedElements |=
13107       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
13108
13109     Uses.push_back(Extract);
13110   }
13111
13112   // If not all the elements were used, this may not be worthwhile.
13113   if (ExtractedElements != 15)
13114     return SDValue();
13115
13116   // Ok, we've now decided to do the transformation.
13117   DebugLoc dl = InputVector.getDebugLoc();
13118
13119   // Store the value to a temporary stack slot.
13120   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
13121   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
13122                             MachinePointerInfo(), false, false, 0);
13123
13124   // Replace each use (extract) with a load of the appropriate element.
13125   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
13126        UE = Uses.end(); UI != UE; ++UI) {
13127     SDNode *Extract = *UI;
13128
13129     // cOMpute the element's address.
13130     SDValue Idx = Extract->getOperand(1);
13131     unsigned EltSize =
13132         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
13133     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
13134     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
13135
13136     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
13137                                      StackPtr, OffsetVal);
13138
13139     // Load the scalar.
13140     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
13141                                      ScalarAddr, MachinePointerInfo(),
13142                                      false, false, false, 0);
13143
13144     // Replace the exact with the load.
13145     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
13146   }
13147
13148   // The replacement was made in place; don't return anything.
13149   return SDValue();
13150 }
13151
13152 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
13153 /// nodes.
13154 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
13155                                     const X86Subtarget *Subtarget) {
13156   DebugLoc DL = N->getDebugLoc();
13157   SDValue Cond = N->getOperand(0);
13158   // Get the LHS/RHS of the select.
13159   SDValue LHS = N->getOperand(1);
13160   SDValue RHS = N->getOperand(2);
13161   EVT VT = LHS.getValueType();
13162
13163   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
13164   // instructions match the semantics of the common C idiom x<y?x:y but not
13165   // x<=y?x:y, because of how they handle negative zero (which can be
13166   // ignored in unsafe-math mode).
13167   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
13168       VT != MVT::f80 && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
13169       (Subtarget->hasXMMInt() ||
13170        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
13171     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
13172
13173     unsigned Opcode = 0;
13174     // Check for x CC y ? x : y.
13175     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
13176         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
13177       switch (CC) {
13178       default: break;
13179       case ISD::SETULT:
13180         // Converting this to a min would handle NaNs incorrectly, and swapping
13181         // the operands would cause it to handle comparisons between positive
13182         // and negative zero incorrectly.
13183         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13184           if (!UnsafeFPMath &&
13185               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13186             break;
13187           std::swap(LHS, RHS);
13188         }
13189         Opcode = X86ISD::FMIN;
13190         break;
13191       case ISD::SETOLE:
13192         // Converting this to a min would handle comparisons between positive
13193         // and negative zero incorrectly.
13194         if (!UnsafeFPMath &&
13195             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13196           break;
13197         Opcode = X86ISD::FMIN;
13198         break;
13199       case ISD::SETULE:
13200         // Converting this to a min would handle both negative zeros and NaNs
13201         // incorrectly, but we can swap the operands to fix both.
13202         std::swap(LHS, RHS);
13203       case ISD::SETOLT:
13204       case ISD::SETLT:
13205       case ISD::SETLE:
13206         Opcode = X86ISD::FMIN;
13207         break;
13208
13209       case ISD::SETOGE:
13210         // Converting this to a max would handle comparisons between positive
13211         // and negative zero incorrectly.
13212         if (!UnsafeFPMath &&
13213             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
13214           break;
13215         Opcode = X86ISD::FMAX;
13216         break;
13217       case ISD::SETUGT:
13218         // Converting this to a max would handle NaNs incorrectly, and swapping
13219         // the operands would cause it to handle comparisons between positive
13220         // and negative zero incorrectly.
13221         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
13222           if (!UnsafeFPMath &&
13223               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
13224             break;
13225           std::swap(LHS, RHS);
13226         }
13227         Opcode = X86ISD::FMAX;
13228         break;
13229       case ISD::SETUGE:
13230         // Converting this to a max would handle both negative zeros and NaNs
13231         // incorrectly, but we can swap the operands to fix both.
13232         std::swap(LHS, RHS);
13233       case ISD::SETOGT:
13234       case ISD::SETGT:
13235       case ISD::SETGE:
13236         Opcode = X86ISD::FMAX;
13237         break;
13238       }
13239     // Check for x CC y ? y : x -- a min/max with reversed arms.
13240     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
13241                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
13242       switch (CC) {
13243       default: break;
13244       case ISD::SETOGE:
13245         // Converting this to a min would handle comparisons between positive
13246         // and negative zero incorrectly, and swapping the operands would
13247         // cause it to handle NaNs incorrectly.
13248         if (!UnsafeFPMath &&
13249             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
13250           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13251             break;
13252           std::swap(LHS, RHS);
13253         }
13254         Opcode = X86ISD::FMIN;
13255         break;
13256       case ISD::SETUGT:
13257         // Converting this to a min would handle NaNs incorrectly.
13258         if (!UnsafeFPMath &&
13259             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
13260           break;
13261         Opcode = X86ISD::FMIN;
13262         break;
13263       case ISD::SETUGE:
13264         // Converting this to a min would handle both negative zeros and NaNs
13265         // incorrectly, but we can swap the operands to fix both.
13266         std::swap(LHS, RHS);
13267       case ISD::SETOGT:
13268       case ISD::SETGT:
13269       case ISD::SETGE:
13270         Opcode = X86ISD::FMIN;
13271         break;
13272
13273       case ISD::SETULT:
13274         // Converting this to a max would handle NaNs incorrectly.
13275         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13276           break;
13277         Opcode = X86ISD::FMAX;
13278         break;
13279       case ISD::SETOLE:
13280         // Converting this to a max would handle comparisons between positive
13281         // and negative zero incorrectly, and swapping the operands would
13282         // cause it to handle NaNs incorrectly.
13283         if (!UnsafeFPMath &&
13284             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
13285           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
13286             break;
13287           std::swap(LHS, RHS);
13288         }
13289         Opcode = X86ISD::FMAX;
13290         break;
13291       case ISD::SETULE:
13292         // Converting this to a max would handle both negative zeros and NaNs
13293         // incorrectly, but we can swap the operands to fix both.
13294         std::swap(LHS, RHS);
13295       case ISD::SETOLT:
13296       case ISD::SETLT:
13297       case ISD::SETLE:
13298         Opcode = X86ISD::FMAX;
13299         break;
13300       }
13301     }
13302
13303     if (Opcode)
13304       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
13305   }
13306
13307   // If this is a select between two integer constants, try to do some
13308   // optimizations.
13309   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
13310     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
13311       // Don't do this for crazy integer types.
13312       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
13313         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
13314         // so that TrueC (the true value) is larger than FalseC.
13315         bool NeedsCondInvert = false;
13316
13317         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
13318             // Efficiently invertible.
13319             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
13320              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
13321               isa<ConstantSDNode>(Cond.getOperand(1))))) {
13322           NeedsCondInvert = true;
13323           std::swap(TrueC, FalseC);
13324         }
13325
13326         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
13327         if (FalseC->getAPIntValue() == 0 &&
13328             TrueC->getAPIntValue().isPowerOf2()) {
13329           if (NeedsCondInvert) // Invert the condition if needed.
13330             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13331                                DAG.getConstant(1, Cond.getValueType()));
13332
13333           // Zero extend the condition if needed.
13334           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
13335
13336           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13337           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
13338                              DAG.getConstant(ShAmt, MVT::i8));
13339         }
13340
13341         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
13342         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13343           if (NeedsCondInvert) // Invert the condition if needed.
13344             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13345                                DAG.getConstant(1, Cond.getValueType()));
13346
13347           // Zero extend the condition if needed.
13348           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13349                              FalseC->getValueType(0), Cond);
13350           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13351                              SDValue(FalseC, 0));
13352         }
13353
13354         // Optimize cases that will turn into an LEA instruction.  This requires
13355         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13356         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13357           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13358           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13359
13360           bool isFastMultiplier = false;
13361           if (Diff < 10) {
13362             switch ((unsigned char)Diff) {
13363               default: break;
13364               case 1:  // result = add base, cond
13365               case 2:  // result = lea base(    , cond*2)
13366               case 3:  // result = lea base(cond, cond*2)
13367               case 4:  // result = lea base(    , cond*4)
13368               case 5:  // result = lea base(cond, cond*4)
13369               case 8:  // result = lea base(    , cond*8)
13370               case 9:  // result = lea base(cond, cond*8)
13371                 isFastMultiplier = true;
13372                 break;
13373             }
13374           }
13375
13376           if (isFastMultiplier) {
13377             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13378             if (NeedsCondInvert) // Invert the condition if needed.
13379               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
13380                                  DAG.getConstant(1, Cond.getValueType()));
13381
13382             // Zero extend the condition if needed.
13383             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13384                                Cond);
13385             // Scale the condition by the difference.
13386             if (Diff != 1)
13387               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13388                                  DAG.getConstant(Diff, Cond.getValueType()));
13389
13390             // Add the base if non-zero.
13391             if (FalseC->getAPIntValue() != 0)
13392               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13393                                  SDValue(FalseC, 0));
13394             return Cond;
13395           }
13396         }
13397       }
13398   }
13399
13400   return SDValue();
13401 }
13402
13403 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
13404 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
13405                                   TargetLowering::DAGCombinerInfo &DCI) {
13406   DebugLoc DL = N->getDebugLoc();
13407
13408   // If the flag operand isn't dead, don't touch this CMOV.
13409   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
13410     return SDValue();
13411
13412   SDValue FalseOp = N->getOperand(0);
13413   SDValue TrueOp = N->getOperand(1);
13414   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
13415   SDValue Cond = N->getOperand(3);
13416   if (CC == X86::COND_E || CC == X86::COND_NE) {
13417     switch (Cond.getOpcode()) {
13418     default: break;
13419     case X86ISD::BSR:
13420     case X86ISD::BSF:
13421       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
13422       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
13423         return (CC == X86::COND_E) ? FalseOp : TrueOp;
13424     }
13425   }
13426
13427   // If this is a select between two integer constants, try to do some
13428   // optimizations.  Note that the operands are ordered the opposite of SELECT
13429   // operands.
13430   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
13431     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
13432       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
13433       // larger than FalseC (the false value).
13434       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
13435         CC = X86::GetOppositeBranchCondition(CC);
13436         std::swap(TrueC, FalseC);
13437       }
13438
13439       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
13440       // This is efficient for any integer data type (including i8/i16) and
13441       // shift amount.
13442       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
13443         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13444                            DAG.getConstant(CC, MVT::i8), Cond);
13445
13446         // Zero extend the condition if needed.
13447         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
13448
13449         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
13450         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
13451                            DAG.getConstant(ShAmt, MVT::i8));
13452         if (N->getNumValues() == 2)  // Dead flag value?
13453           return DCI.CombineTo(N, Cond, SDValue());
13454         return Cond;
13455       }
13456
13457       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
13458       // for any integer data type, including i8/i16.
13459       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
13460         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13461                            DAG.getConstant(CC, MVT::i8), Cond);
13462
13463         // Zero extend the condition if needed.
13464         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
13465                            FalseC->getValueType(0), Cond);
13466         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13467                            SDValue(FalseC, 0));
13468
13469         if (N->getNumValues() == 2)  // Dead flag value?
13470           return DCI.CombineTo(N, Cond, SDValue());
13471         return Cond;
13472       }
13473
13474       // Optimize cases that will turn into an LEA instruction.  This requires
13475       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
13476       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
13477         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
13478         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
13479
13480         bool isFastMultiplier = false;
13481         if (Diff < 10) {
13482           switch ((unsigned char)Diff) {
13483           default: break;
13484           case 1:  // result = add base, cond
13485           case 2:  // result = lea base(    , cond*2)
13486           case 3:  // result = lea base(cond, cond*2)
13487           case 4:  // result = lea base(    , cond*4)
13488           case 5:  // result = lea base(cond, cond*4)
13489           case 8:  // result = lea base(    , cond*8)
13490           case 9:  // result = lea base(cond, cond*8)
13491             isFastMultiplier = true;
13492             break;
13493           }
13494         }
13495
13496         if (isFastMultiplier) {
13497           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
13498           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
13499                              DAG.getConstant(CC, MVT::i8), Cond);
13500           // Zero extend the condition if needed.
13501           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
13502                              Cond);
13503           // Scale the condition by the difference.
13504           if (Diff != 1)
13505             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
13506                                DAG.getConstant(Diff, Cond.getValueType()));
13507
13508           // Add the base if non-zero.
13509           if (FalseC->getAPIntValue() != 0)
13510             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
13511                                SDValue(FalseC, 0));
13512           if (N->getNumValues() == 2)  // Dead flag value?
13513             return DCI.CombineTo(N, Cond, SDValue());
13514           return Cond;
13515         }
13516       }
13517     }
13518   }
13519   return SDValue();
13520 }
13521
13522
13523 /// PerformMulCombine - Optimize a single multiply with constant into two
13524 /// in order to implement it with two cheaper instructions, e.g.
13525 /// LEA + SHL, LEA + LEA.
13526 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
13527                                  TargetLowering::DAGCombinerInfo &DCI) {
13528   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13529     return SDValue();
13530
13531   EVT VT = N->getValueType(0);
13532   if (VT != MVT::i64)
13533     return SDValue();
13534
13535   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
13536   if (!C)
13537     return SDValue();
13538   uint64_t MulAmt = C->getZExtValue();
13539   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
13540     return SDValue();
13541
13542   uint64_t MulAmt1 = 0;
13543   uint64_t MulAmt2 = 0;
13544   if ((MulAmt % 9) == 0) {
13545     MulAmt1 = 9;
13546     MulAmt2 = MulAmt / 9;
13547   } else if ((MulAmt % 5) == 0) {
13548     MulAmt1 = 5;
13549     MulAmt2 = MulAmt / 5;
13550   } else if ((MulAmt % 3) == 0) {
13551     MulAmt1 = 3;
13552     MulAmt2 = MulAmt / 3;
13553   }
13554   if (MulAmt2 &&
13555       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
13556     DebugLoc DL = N->getDebugLoc();
13557
13558     if (isPowerOf2_64(MulAmt2) &&
13559         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
13560       // If second multiplifer is pow2, issue it first. We want the multiply by
13561       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
13562       // is an add.
13563       std::swap(MulAmt1, MulAmt2);
13564
13565     SDValue NewMul;
13566     if (isPowerOf2_64(MulAmt1))
13567       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
13568                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
13569     else
13570       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
13571                            DAG.getConstant(MulAmt1, VT));
13572
13573     if (isPowerOf2_64(MulAmt2))
13574       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
13575                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
13576     else
13577       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
13578                            DAG.getConstant(MulAmt2, VT));
13579
13580     // Do not add new nodes to DAG combiner worklist.
13581     DCI.CombineTo(N, NewMul, false);
13582   }
13583   return SDValue();
13584 }
13585
13586 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
13587   SDValue N0 = N->getOperand(0);
13588   SDValue N1 = N->getOperand(1);
13589   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
13590   EVT VT = N0.getValueType();
13591
13592   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
13593   // since the result of setcc_c is all zero's or all ones.
13594   if (VT.isInteger() && !VT.isVector() &&
13595       N1C && N0.getOpcode() == ISD::AND &&
13596       N0.getOperand(1).getOpcode() == ISD::Constant) {
13597     SDValue N00 = N0.getOperand(0);
13598     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
13599         ((N00.getOpcode() == ISD::ANY_EXTEND ||
13600           N00.getOpcode() == ISD::ZERO_EXTEND) &&
13601          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
13602       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
13603       APInt ShAmt = N1C->getAPIntValue();
13604       Mask = Mask.shl(ShAmt);
13605       if (Mask != 0)
13606         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
13607                            N00, DAG.getConstant(Mask, VT));
13608     }
13609   }
13610
13611
13612   // Hardware support for vector shifts is sparse which makes us scalarize the
13613   // vector operations in many cases. Also, on sandybridge ADD is faster than
13614   // shl.
13615   // (shl V, 1) -> add V,V
13616   if (isSplatVector(N1.getNode())) {
13617     assert(N0.getValueType().isVector() && "Invalid vector shift type");
13618     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
13619     // We shift all of the values by one. In many cases we do not have
13620     // hardware support for this operation. This is better expressed as an ADD
13621     // of two values.
13622     if (N1C && (1 == N1C->getZExtValue())) {
13623       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N0);
13624     }
13625   }
13626
13627   return SDValue();
13628 }
13629
13630 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
13631 ///                       when possible.
13632 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
13633                                    const X86Subtarget *Subtarget) {
13634   EVT VT = N->getValueType(0);
13635   if (N->getOpcode() == ISD::SHL) {
13636     SDValue V = PerformSHLCombine(N, DAG);
13637     if (V.getNode()) return V;
13638   }
13639
13640   // On X86 with SSE2 support, we can transform this to a vector shift if
13641   // all elements are shifted by the same amount.  We can't do this in legalize
13642   // because the a constant vector is typically transformed to a constant pool
13643   // so we have no knowledge of the shift amount.
13644   if (!Subtarget->hasXMMInt())
13645     return SDValue();
13646
13647   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
13648       (!Subtarget->hasAVX2() ||
13649        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
13650     return SDValue();
13651
13652   SDValue ShAmtOp = N->getOperand(1);
13653   EVT EltVT = VT.getVectorElementType();
13654   DebugLoc DL = N->getDebugLoc();
13655   SDValue BaseShAmt = SDValue();
13656   if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
13657     unsigned NumElts = VT.getVectorNumElements();
13658     unsigned i = 0;
13659     for (; i != NumElts; ++i) {
13660       SDValue Arg = ShAmtOp.getOperand(i);
13661       if (Arg.getOpcode() == ISD::UNDEF) continue;
13662       BaseShAmt = Arg;
13663       break;
13664     }
13665     for (; i != NumElts; ++i) {
13666       SDValue Arg = ShAmtOp.getOperand(i);
13667       if (Arg.getOpcode() == ISD::UNDEF) continue;
13668       if (Arg != BaseShAmt) {
13669         return SDValue();
13670       }
13671     }
13672   } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
13673              cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
13674     SDValue InVec = ShAmtOp.getOperand(0);
13675     if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13676       unsigned NumElts = InVec.getValueType().getVectorNumElements();
13677       unsigned i = 0;
13678       for (; i != NumElts; ++i) {
13679         SDValue Arg = InVec.getOperand(i);
13680         if (Arg.getOpcode() == ISD::UNDEF) continue;
13681         BaseShAmt = Arg;
13682         break;
13683       }
13684     } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13685        if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13686          unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
13687          if (C->getZExtValue() == SplatIdx)
13688            BaseShAmt = InVec.getOperand(1);
13689        }
13690     }
13691     if (BaseShAmt.getNode() == 0)
13692       BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
13693                               DAG.getIntPtrConstant(0));
13694   } else
13695     return SDValue();
13696
13697   // The shift amount is an i32.
13698   if (EltVT.bitsGT(MVT::i32))
13699     BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
13700   else if (EltVT.bitsLT(MVT::i32))
13701     BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
13702
13703   // The shift amount is identical so we can do a vector shift.
13704   SDValue  ValOp = N->getOperand(0);
13705   switch (N->getOpcode()) {
13706   default:
13707     llvm_unreachable("Unknown shift opcode!");
13708     break;
13709   case ISD::SHL:
13710     if (VT == MVT::v2i64)
13711       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13712                          DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
13713                          ValOp, BaseShAmt);
13714     if (VT == MVT::v4i32)
13715       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13716                          DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
13717                          ValOp, BaseShAmt);
13718     if (VT == MVT::v8i16)
13719       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13720                          DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
13721                          ValOp, BaseShAmt);
13722     if (VT == MVT::v4i64)
13723       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13724                          DAG.getConstant(Intrinsic::x86_avx2_pslli_q, MVT::i32),
13725                          ValOp, BaseShAmt);
13726     if (VT == MVT::v8i32)
13727       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13728                          DAG.getConstant(Intrinsic::x86_avx2_pslli_d, MVT::i32),
13729                          ValOp, BaseShAmt);
13730     if (VT == MVT::v16i16)
13731       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13732                          DAG.getConstant(Intrinsic::x86_avx2_pslli_w, MVT::i32),
13733                          ValOp, BaseShAmt);
13734     break;
13735   case ISD::SRA:
13736     if (VT == MVT::v4i32)
13737       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13738                          DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
13739                          ValOp, BaseShAmt);
13740     if (VT == MVT::v8i16)
13741       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13742                          DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
13743                          ValOp, BaseShAmt);
13744     if (VT == MVT::v8i32)
13745       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13746                          DAG.getConstant(Intrinsic::x86_avx2_psrai_d, MVT::i32),
13747                          ValOp, BaseShAmt);
13748     if (VT == MVT::v16i16)
13749       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13750                          DAG.getConstant(Intrinsic::x86_avx2_psrai_w, MVT::i32),
13751                          ValOp, BaseShAmt);
13752     break;
13753   case ISD::SRL:
13754     if (VT == MVT::v2i64)
13755       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13756                          DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
13757                          ValOp, BaseShAmt);
13758     if (VT == MVT::v4i32)
13759       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13760                          DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
13761                          ValOp, BaseShAmt);
13762     if (VT ==  MVT::v8i16)
13763       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13764                          DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
13765                          ValOp, BaseShAmt);
13766     if (VT == MVT::v4i64)
13767       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13768                          DAG.getConstant(Intrinsic::x86_avx2_psrli_q, MVT::i32),
13769                          ValOp, BaseShAmt);
13770     if (VT == MVT::v8i32)
13771       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13772                          DAG.getConstant(Intrinsic::x86_avx2_psrli_d, MVT::i32),
13773                          ValOp, BaseShAmt);
13774     if (VT ==  MVT::v16i16)
13775       return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
13776                          DAG.getConstant(Intrinsic::x86_avx2_psrli_w, MVT::i32),
13777                          ValOp, BaseShAmt);
13778     break;
13779   }
13780   return SDValue();
13781 }
13782
13783
13784 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
13785 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
13786 // and friends.  Likewise for OR -> CMPNEQSS.
13787 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
13788                             TargetLowering::DAGCombinerInfo &DCI,
13789                             const X86Subtarget *Subtarget) {
13790   unsigned opcode;
13791
13792   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
13793   // we're requiring SSE2 for both.
13794   if (Subtarget->hasXMMInt() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
13795     SDValue N0 = N->getOperand(0);
13796     SDValue N1 = N->getOperand(1);
13797     SDValue CMP0 = N0->getOperand(1);
13798     SDValue CMP1 = N1->getOperand(1);
13799     DebugLoc DL = N->getDebugLoc();
13800
13801     // The SETCCs should both refer to the same CMP.
13802     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
13803       return SDValue();
13804
13805     SDValue CMP00 = CMP0->getOperand(0);
13806     SDValue CMP01 = CMP0->getOperand(1);
13807     EVT     VT    = CMP00.getValueType();
13808
13809     if (VT == MVT::f32 || VT == MVT::f64) {
13810       bool ExpectingFlags = false;
13811       // Check for any users that want flags:
13812       for (SDNode::use_iterator UI = N->use_begin(),
13813              UE = N->use_end();
13814            !ExpectingFlags && UI != UE; ++UI)
13815         switch (UI->getOpcode()) {
13816         default:
13817         case ISD::BR_CC:
13818         case ISD::BRCOND:
13819         case ISD::SELECT:
13820           ExpectingFlags = true;
13821           break;
13822         case ISD::CopyToReg:
13823         case ISD::SIGN_EXTEND:
13824         case ISD::ZERO_EXTEND:
13825         case ISD::ANY_EXTEND:
13826           break;
13827         }
13828
13829       if (!ExpectingFlags) {
13830         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
13831         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
13832
13833         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
13834           X86::CondCode tmp = cc0;
13835           cc0 = cc1;
13836           cc1 = tmp;
13837         }
13838
13839         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
13840             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
13841           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
13842           X86ISD::NodeType NTOperator = is64BitFP ?
13843             X86ISD::FSETCCsd : X86ISD::FSETCCss;
13844           // FIXME: need symbolic constants for these magic numbers.
13845           // See X86ATTInstPrinter.cpp:printSSECC().
13846           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
13847           SDValue OnesOrZeroesF = DAG.getNode(NTOperator, DL, MVT::f32, CMP00, CMP01,
13848                                               DAG.getConstant(x86cc, MVT::i8));
13849           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, MVT::i32,
13850                                               OnesOrZeroesF);
13851           SDValue ANDed = DAG.getNode(ISD::AND, DL, MVT::i32, OnesOrZeroesI,
13852                                       DAG.getConstant(1, MVT::i32));
13853           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
13854           return OneBitOfTruth;
13855         }
13856       }
13857     }
13858   }
13859   return SDValue();
13860 }
13861
13862 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
13863 /// so it can be folded inside ANDNP.
13864 static bool CanFoldXORWithAllOnes(const SDNode *N) {
13865   EVT VT = N->getValueType(0);
13866
13867   // Match direct AllOnes for 128 and 256-bit vectors
13868   if (ISD::isBuildVectorAllOnes(N))
13869     return true;
13870
13871   // Look through a bit convert.
13872   if (N->getOpcode() == ISD::BITCAST)
13873     N = N->getOperand(0).getNode();
13874
13875   // Sometimes the operand may come from a insert_subvector building a 256-bit
13876   // allones vector
13877   if (VT.getSizeInBits() == 256 &&
13878       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
13879     SDValue V1 = N->getOperand(0);
13880     SDValue V2 = N->getOperand(1);
13881
13882     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
13883         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
13884         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
13885         ISD::isBuildVectorAllOnes(V2.getNode()))
13886       return true;
13887   }
13888
13889   return false;
13890 }
13891
13892 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
13893                                  TargetLowering::DAGCombinerInfo &DCI,
13894                                  const X86Subtarget *Subtarget) {
13895   if (DCI.isBeforeLegalizeOps())
13896     return SDValue();
13897
13898   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13899   if (R.getNode())
13900     return R;
13901
13902   EVT VT = N->getValueType(0);
13903
13904   // Create ANDN, BLSI, and BLSR instructions
13905   // BLSI is X & (-X)
13906   // BLSR is X & (X-1)
13907   if (Subtarget->hasBMI() && (VT == MVT::i32 || VT == MVT::i64)) {
13908     SDValue N0 = N->getOperand(0);
13909     SDValue N1 = N->getOperand(1);
13910     DebugLoc DL = N->getDebugLoc();
13911
13912     // Check LHS for not
13913     if (N0.getOpcode() == ISD::XOR && isAllOnes(N0.getOperand(1)))
13914       return DAG.getNode(X86ISD::ANDN, DL, VT, N0.getOperand(0), N1);
13915     // Check RHS for not
13916     if (N1.getOpcode() == ISD::XOR && isAllOnes(N1.getOperand(1)))
13917       return DAG.getNode(X86ISD::ANDN, DL, VT, N1.getOperand(0), N0);
13918
13919     // Check LHS for neg
13920     if (N0.getOpcode() == ISD::SUB && N0.getOperand(1) == N1 &&
13921         isZero(N0.getOperand(0)))
13922       return DAG.getNode(X86ISD::BLSI, DL, VT, N1);
13923
13924     // Check RHS for neg
13925     if (N1.getOpcode() == ISD::SUB && N1.getOperand(1) == N0 &&
13926         isZero(N1.getOperand(0)))
13927       return DAG.getNode(X86ISD::BLSI, DL, VT, N0);
13928
13929     // Check LHS for X-1
13930     if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
13931         isAllOnes(N0.getOperand(1)))
13932       return DAG.getNode(X86ISD::BLSR, DL, VT, N1);
13933
13934     // Check RHS for X-1
13935     if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
13936         isAllOnes(N1.getOperand(1)))
13937       return DAG.getNode(X86ISD::BLSR, DL, VT, N0);
13938
13939     return SDValue();
13940   }
13941
13942   // Want to form ANDNP nodes:
13943   // 1) In the hopes of then easily combining them with OR and AND nodes
13944   //    to form PBLEND/PSIGN.
13945   // 2) To match ANDN packed intrinsics
13946   if (VT != MVT::v2i64 && VT != MVT::v4i64)
13947     return SDValue();
13948
13949   SDValue N0 = N->getOperand(0);
13950   SDValue N1 = N->getOperand(1);
13951   DebugLoc DL = N->getDebugLoc();
13952
13953   // Check LHS for vnot
13954   if (N0.getOpcode() == ISD::XOR &&
13955       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
13956       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
13957     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
13958
13959   // Check RHS for vnot
13960   if (N1.getOpcode() == ISD::XOR &&
13961       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
13962       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
13963     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
13964
13965   return SDValue();
13966 }
13967
13968 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
13969                                 TargetLowering::DAGCombinerInfo &DCI,
13970                                 const X86Subtarget *Subtarget) {
13971   if (DCI.isBeforeLegalizeOps())
13972     return SDValue();
13973
13974   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
13975   if (R.getNode())
13976     return R;
13977
13978   EVT VT = N->getValueType(0);
13979
13980   SDValue N0 = N->getOperand(0);
13981   SDValue N1 = N->getOperand(1);
13982
13983   // look for psign/blend
13984   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
13985     if (!(Subtarget->hasSSSE3() || Subtarget->hasAVX()) ||
13986         (VT == MVT::v4i64 && !Subtarget->hasAVX2()))
13987       return SDValue();
13988
13989     // Canonicalize pandn to RHS
13990     if (N0.getOpcode() == X86ISD::ANDNP)
13991       std::swap(N0, N1);
13992     // or (and (m, x), (pandn m, y))
13993     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
13994       SDValue Mask = N1.getOperand(0);
13995       SDValue X    = N1.getOperand(1);
13996       SDValue Y;
13997       if (N0.getOperand(0) == Mask)
13998         Y = N0.getOperand(1);
13999       if (N0.getOperand(1) == Mask)
14000         Y = N0.getOperand(0);
14001
14002       // Check to see if the mask appeared in both the AND and ANDNP and
14003       if (!Y.getNode())
14004         return SDValue();
14005
14006       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
14007       if (Mask.getOpcode() != ISD::BITCAST ||
14008           X.getOpcode() != ISD::BITCAST ||
14009           Y.getOpcode() != ISD::BITCAST)
14010         return SDValue();
14011
14012       // Look through mask bitcast.
14013       Mask = Mask.getOperand(0);
14014       EVT MaskVT = Mask.getValueType();
14015
14016       // Validate that the Mask operand is a vector sra node.  The sra node
14017       // will be an intrinsic.
14018       if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
14019         return SDValue();
14020
14021       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
14022       // there is no psrai.b
14023       switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
14024       case Intrinsic::x86_sse2_psrai_w:
14025       case Intrinsic::x86_sse2_psrai_d:
14026       case Intrinsic::x86_avx2_psrai_w:
14027       case Intrinsic::x86_avx2_psrai_d:
14028         break;
14029       default: return SDValue();
14030       }
14031
14032       // Check that the SRA is all signbits.
14033       SDValue SraC = Mask.getOperand(2);
14034       unsigned SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
14035       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
14036       if ((SraAmt + 1) != EltBits)
14037         return SDValue();
14038
14039       DebugLoc DL = N->getDebugLoc();
14040
14041       // Now we know we at least have a plendvb with the mask val.  See if
14042       // we can form a psignb/w/d.
14043       // psign = x.type == y.type == mask.type && y = sub(0, x);
14044       X = X.getOperand(0);
14045       Y = Y.getOperand(0);
14046       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
14047           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
14048           X.getValueType() == MaskVT && X.getValueType() == Y.getValueType() &&
14049           (EltBits == 8 || EltBits == 16 || EltBits == 32)) {
14050         SDValue Sign = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X,
14051                                    Mask.getOperand(1));
14052         return DAG.getNode(ISD::BITCAST, DL, VT, Sign);
14053       }
14054       // PBLENDVB only available on SSE 4.1
14055       if (!(Subtarget->hasSSE41() || Subtarget->hasAVX()))
14056         return SDValue();
14057
14058       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
14059
14060       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
14061       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
14062       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
14063       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, X, Y);
14064       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
14065     }
14066   }
14067
14068   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
14069     return SDValue();
14070
14071   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
14072   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
14073     std::swap(N0, N1);
14074   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
14075     return SDValue();
14076   if (!N0.hasOneUse() || !N1.hasOneUse())
14077     return SDValue();
14078
14079   SDValue ShAmt0 = N0.getOperand(1);
14080   if (ShAmt0.getValueType() != MVT::i8)
14081     return SDValue();
14082   SDValue ShAmt1 = N1.getOperand(1);
14083   if (ShAmt1.getValueType() != MVT::i8)
14084     return SDValue();
14085   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
14086     ShAmt0 = ShAmt0.getOperand(0);
14087   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
14088     ShAmt1 = ShAmt1.getOperand(0);
14089
14090   DebugLoc DL = N->getDebugLoc();
14091   unsigned Opc = X86ISD::SHLD;
14092   SDValue Op0 = N0.getOperand(0);
14093   SDValue Op1 = N1.getOperand(0);
14094   if (ShAmt0.getOpcode() == ISD::SUB) {
14095     Opc = X86ISD::SHRD;
14096     std::swap(Op0, Op1);
14097     std::swap(ShAmt0, ShAmt1);
14098   }
14099
14100   unsigned Bits = VT.getSizeInBits();
14101   if (ShAmt1.getOpcode() == ISD::SUB) {
14102     SDValue Sum = ShAmt1.getOperand(0);
14103     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
14104       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
14105       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
14106         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
14107       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
14108         return DAG.getNode(Opc, DL, VT,
14109                            Op0, Op1,
14110                            DAG.getNode(ISD::TRUNCATE, DL,
14111                                        MVT::i8, ShAmt0));
14112     }
14113   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
14114     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
14115     if (ShAmt0C &&
14116         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
14117       return DAG.getNode(Opc, DL, VT,
14118                          N0.getOperand(0), N1.getOperand(0),
14119                          DAG.getNode(ISD::TRUNCATE, DL,
14120                                        MVT::i8, ShAmt0));
14121   }
14122
14123   return SDValue();
14124 }
14125
14126 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
14127                                  TargetLowering::DAGCombinerInfo &DCI,
14128                                  const X86Subtarget *Subtarget) {
14129   if (DCI.isBeforeLegalizeOps())
14130     return SDValue();
14131
14132   EVT VT = N->getValueType(0);
14133
14134   if (VT != MVT::i32 && VT != MVT::i64)
14135     return SDValue();
14136
14137   // Create BLSMSK instructions by finding X ^ (X-1)
14138   SDValue N0 = N->getOperand(0);
14139   SDValue N1 = N->getOperand(1);
14140   DebugLoc DL = N->getDebugLoc();
14141
14142   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1 &&
14143       isAllOnes(N0.getOperand(1)))
14144     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N1);
14145
14146   if (N1.getOpcode() == ISD::ADD && N1.getOperand(0) == N0 &&
14147       isAllOnes(N1.getOperand(1)))
14148     return DAG.getNode(X86ISD::BLSMSK, DL, VT, N0);
14149
14150   return SDValue();
14151 }
14152
14153 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
14154 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
14155                                    const X86Subtarget *Subtarget) {
14156   LoadSDNode *Ld = cast<LoadSDNode>(N);
14157   EVT RegVT = Ld->getValueType(0);
14158   EVT MemVT = Ld->getMemoryVT();
14159   DebugLoc dl = Ld->getDebugLoc();
14160   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14161
14162   ISD::LoadExtType Ext = Ld->getExtensionType();
14163
14164   // If this is a vector EXT Load then attempt to optimize it using a
14165   // shuffle. We need SSE4 for the shuffles.
14166   // TODO: It is possible to support ZExt by zeroing the undef values
14167   // during the shuffle phase or after the shuffle.
14168   if (RegVT.isVector() && Ext == ISD::EXTLOAD && Subtarget->hasSSE41()) {
14169     assert(MemVT != RegVT && "Cannot extend to the same type");
14170     assert(MemVT.isVector() && "Must load a vector from memory");
14171
14172     unsigned NumElems = RegVT.getVectorNumElements();
14173     unsigned RegSz = RegVT.getSizeInBits();
14174     unsigned MemSz = MemVT.getSizeInBits();
14175     assert(RegSz > MemSz && "Register size must be greater than the mem size");
14176     // All sizes must be a power of two
14177     if (!isPowerOf2_32(RegSz * MemSz * NumElems)) return SDValue();
14178
14179     // Attempt to load the original value using a single load op.
14180     // Find a scalar type which is equal to the loaded word size.
14181     MVT SclrLoadTy = MVT::i8;
14182     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14183          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14184       MVT Tp = (MVT::SimpleValueType)tp;
14185       if (TLI.isTypeLegal(Tp) &&  Tp.getSizeInBits() == MemSz) {
14186         SclrLoadTy = Tp;
14187         break;
14188       }
14189     }
14190
14191     // Proceed if a load word is found.
14192     if (SclrLoadTy.getSizeInBits() != MemSz) return SDValue();
14193
14194     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
14195       RegSz/SclrLoadTy.getSizeInBits());
14196
14197     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14198                                   RegSz/MemVT.getScalarType().getSizeInBits());
14199     // Can't shuffle using an illegal type.
14200     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14201
14202     // Perform a single load.
14203     SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
14204                                   Ld->getBasePtr(),
14205                                   Ld->getPointerInfo(), Ld->isVolatile(),
14206                                   Ld->isNonTemporal(), Ld->isInvariant(),
14207                                   Ld->getAlignment());
14208
14209     // Insert the word loaded into a vector.
14210     SDValue ScalarInVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14211       LoadUnitVecVT, ScalarLoad);
14212
14213     // Bitcast the loaded value to a vector of the original element type, in
14214     // the size of the target vector type.
14215     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, ScalarInVector);
14216     unsigned SizeRatio = RegSz/MemSz;
14217
14218     // Redistribute the loaded elements into the different locations.
14219     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14220     for (unsigned i = 0; i < NumElems; i++) ShuffleVec[i*SizeRatio] = i;
14221
14222     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14223                                 DAG.getUNDEF(SlicedVec.getValueType()),
14224                                 ShuffleVec.data());
14225
14226     // Bitcast to the requested type.
14227     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14228     // Replace the original load with the new sequence
14229     // and return the new chain.
14230     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Shuff);
14231     return SDValue(ScalarLoad.getNode(), 1);
14232   }
14233
14234   return SDValue();
14235 }
14236
14237 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
14238 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
14239                                    const X86Subtarget *Subtarget) {
14240   StoreSDNode *St = cast<StoreSDNode>(N);
14241   EVT VT = St->getValue().getValueType();
14242   EVT StVT = St->getMemoryVT();
14243   DebugLoc dl = St->getDebugLoc();
14244   SDValue StoredVal = St->getOperand(1);
14245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14246
14247   // If we are saving a concatination of two XMM registers, perform two stores.
14248   // This is better in Sandy Bridge cause one 256-bit mem op is done via two
14249   // 128-bit ones. If in the future the cost becomes only one memory access the
14250   // first version would be better.
14251   if (VT.getSizeInBits() == 256 &&
14252     StoredVal.getNode()->getOpcode() == ISD::CONCAT_VECTORS &&
14253     StoredVal.getNumOperands() == 2) {
14254
14255     SDValue Value0 = StoredVal.getOperand(0);
14256     SDValue Value1 = StoredVal.getOperand(1);
14257
14258     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
14259     SDValue Ptr0 = St->getBasePtr();
14260     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
14261
14262     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
14263                                 St->getPointerInfo(), St->isVolatile(),
14264                                 St->isNonTemporal(), St->getAlignment());
14265     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
14266                                 St->getPointerInfo(), St->isVolatile(),
14267                                 St->isNonTemporal(), St->getAlignment());
14268     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
14269   }
14270
14271   // Optimize trunc store (of multiple scalars) to shuffle and store.
14272   // First, pack all of the elements in one place. Next, store to memory
14273   // in fewer chunks.
14274   if (St->isTruncatingStore() && VT.isVector()) {
14275     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14276     unsigned NumElems = VT.getVectorNumElements();
14277     assert(StVT != VT && "Cannot truncate to the same type");
14278     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
14279     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
14280
14281     // From, To sizes and ElemCount must be pow of two
14282     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
14283     // We are going to use the original vector elt for storing.
14284     // Accumulated smaller vector elements must be a multiple of the store size.
14285     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
14286
14287     unsigned SizeRatio  = FromSz / ToSz;
14288
14289     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
14290
14291     // Create a type on which we perform the shuffle
14292     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
14293             StVT.getScalarType(), NumElems*SizeRatio);
14294
14295     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14296
14297     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
14298     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14299     for (unsigned i = 0; i < NumElems; i++ ) ShuffleVec[i] = i * SizeRatio;
14300
14301     // Can't shuffle using an illegal type
14302     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
14303
14304     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
14305                                 DAG.getUNDEF(WideVec.getValueType()),
14306                                 ShuffleVec.data());
14307     // At this point all of the data is stored at the bottom of the
14308     // register. We now need to save it to mem.
14309
14310     // Find the largest store unit
14311     MVT StoreType = MVT::i8;
14312     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14313          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14314       MVT Tp = (MVT::SimpleValueType)tp;
14315       if (TLI.isTypeLegal(Tp) && StoreType.getSizeInBits() < NumElems * ToSz)
14316         StoreType = Tp;
14317     }
14318
14319     // Bitcast the original vector into a vector of store-size units
14320     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
14321             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
14322     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14323     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
14324     SmallVector<SDValue, 8> Chains;
14325     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
14326                                         TLI.getPointerTy());
14327     SDValue Ptr = St->getBasePtr();
14328
14329     // Perform one or more big stores into memory.
14330     for (unsigned i = 0; i < (ToSz*NumElems)/StoreType.getSizeInBits() ; i++) {
14331       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
14332                                    StoreType, ShuffWide,
14333                                    DAG.getIntPtrConstant(i));
14334       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
14335                                 St->getPointerInfo(), St->isVolatile(),
14336                                 St->isNonTemporal(), St->getAlignment());
14337       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14338       Chains.push_back(Ch);
14339     }
14340
14341     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0],
14342                                Chains.size());
14343   }
14344
14345
14346   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
14347   // the FP state in cases where an emms may be missing.
14348   // A preferable solution to the general problem is to figure out the right
14349   // places to insert EMMS.  This qualifies as a quick hack.
14350
14351   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
14352   if (VT.getSizeInBits() != 64)
14353     return SDValue();
14354
14355   const Function *F = DAG.getMachineFunction().getFunction();
14356   bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
14357   bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
14358                      && Subtarget->hasXMMInt();
14359   if ((VT.isVector() ||
14360        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
14361       isa<LoadSDNode>(St->getValue()) &&
14362       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
14363       St->getChain().hasOneUse() && !St->isVolatile()) {
14364     SDNode* LdVal = St->getValue().getNode();
14365     LoadSDNode *Ld = 0;
14366     int TokenFactorIndex = -1;
14367     SmallVector<SDValue, 8> Ops;
14368     SDNode* ChainVal = St->getChain().getNode();
14369     // Must be a store of a load.  We currently handle two cases:  the load
14370     // is a direct child, and it's under an intervening TokenFactor.  It is
14371     // possible to dig deeper under nested TokenFactors.
14372     if (ChainVal == LdVal)
14373       Ld = cast<LoadSDNode>(St->getChain());
14374     else if (St->getValue().hasOneUse() &&
14375              ChainVal->getOpcode() == ISD::TokenFactor) {
14376       for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
14377         if (ChainVal->getOperand(i).getNode() == LdVal) {
14378           TokenFactorIndex = i;
14379           Ld = cast<LoadSDNode>(St->getValue());
14380         } else
14381           Ops.push_back(ChainVal->getOperand(i));
14382       }
14383     }
14384
14385     if (!Ld || !ISD::isNormalLoad(Ld))
14386       return SDValue();
14387
14388     // If this is not the MMX case, i.e. we are just turning i64 load/store
14389     // into f64 load/store, avoid the transformation if there are multiple
14390     // uses of the loaded value.
14391     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
14392       return SDValue();
14393
14394     DebugLoc LdDL = Ld->getDebugLoc();
14395     DebugLoc StDL = N->getDebugLoc();
14396     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
14397     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
14398     // pair instead.
14399     if (Subtarget->is64Bit() || F64IsLegal) {
14400       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
14401       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
14402                                   Ld->getPointerInfo(), Ld->isVolatile(),
14403                                   Ld->isNonTemporal(), Ld->isInvariant(),
14404                                   Ld->getAlignment());
14405       SDValue NewChain = NewLd.getValue(1);
14406       if (TokenFactorIndex != -1) {
14407         Ops.push_back(NewChain);
14408         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14409                                Ops.size());
14410       }
14411       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
14412                           St->getPointerInfo(),
14413                           St->isVolatile(), St->isNonTemporal(),
14414                           St->getAlignment());
14415     }
14416
14417     // Otherwise, lower to two pairs of 32-bit loads / stores.
14418     SDValue LoAddr = Ld->getBasePtr();
14419     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
14420                                  DAG.getConstant(4, MVT::i32));
14421
14422     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
14423                                Ld->getPointerInfo(),
14424                                Ld->isVolatile(), Ld->isNonTemporal(),
14425                                Ld->isInvariant(), Ld->getAlignment());
14426     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
14427                                Ld->getPointerInfo().getWithOffset(4),
14428                                Ld->isVolatile(), Ld->isNonTemporal(),
14429                                Ld->isInvariant(),
14430                                MinAlign(Ld->getAlignment(), 4));
14431
14432     SDValue NewChain = LoLd.getValue(1);
14433     if (TokenFactorIndex != -1) {
14434       Ops.push_back(LoLd);
14435       Ops.push_back(HiLd);
14436       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
14437                              Ops.size());
14438     }
14439
14440     LoAddr = St->getBasePtr();
14441     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
14442                          DAG.getConstant(4, MVT::i32));
14443
14444     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
14445                                 St->getPointerInfo(),
14446                                 St->isVolatile(), St->isNonTemporal(),
14447                                 St->getAlignment());
14448     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
14449                                 St->getPointerInfo().getWithOffset(4),
14450                                 St->isVolatile(),
14451                                 St->isNonTemporal(),
14452                                 MinAlign(St->getAlignment(), 4));
14453     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
14454   }
14455   return SDValue();
14456 }
14457
14458 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
14459 /// and return the operands for the horizontal operation in LHS and RHS.  A
14460 /// horizontal operation performs the binary operation on successive elements
14461 /// of its first operand, then on successive elements of its second operand,
14462 /// returning the resulting values in a vector.  For example, if
14463 ///   A = < float a0, float a1, float a2, float a3 >
14464 /// and
14465 ///   B = < float b0, float b1, float b2, float b3 >
14466 /// then the result of doing a horizontal operation on A and B is
14467 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
14468 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
14469 /// A horizontal-op B, for some already available A and B, and if so then LHS is
14470 /// set to A, RHS to B, and the routine returns 'true'.
14471 /// Note that the binary operation should have the property that if one of the
14472 /// operands is UNDEF then the result is UNDEF.
14473 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool isCommutative) {
14474   // Look for the following pattern: if
14475   //   A = < float a0, float a1, float a2, float a3 >
14476   //   B = < float b0, float b1, float b2, float b3 >
14477   // and
14478   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
14479   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
14480   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
14481   // which is A horizontal-op B.
14482
14483   // At least one of the operands should be a vector shuffle.
14484   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
14485       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
14486     return false;
14487
14488   EVT VT = LHS.getValueType();
14489   unsigned N = VT.getVectorNumElements();
14490
14491   // View LHS in the form
14492   //   LHS = VECTOR_SHUFFLE A, B, LMask
14493   // If LHS is not a shuffle then pretend it is the shuffle
14494   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
14495   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
14496   // type VT.
14497   SDValue A, B;
14498   SmallVector<int, 8> LMask(N);
14499   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14500     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
14501       A = LHS.getOperand(0);
14502     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
14503       B = LHS.getOperand(1);
14504     cast<ShuffleVectorSDNode>(LHS.getNode())->getMask(LMask);
14505   } else {
14506     if (LHS.getOpcode() != ISD::UNDEF)
14507       A = LHS;
14508     for (unsigned i = 0; i != N; ++i)
14509       LMask[i] = i;
14510   }
14511
14512   // Likewise, view RHS in the form
14513   //   RHS = VECTOR_SHUFFLE C, D, RMask
14514   SDValue C, D;
14515   SmallVector<int, 8> RMask(N);
14516   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
14517     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
14518       C = RHS.getOperand(0);
14519     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
14520       D = RHS.getOperand(1);
14521     cast<ShuffleVectorSDNode>(RHS.getNode())->getMask(RMask);
14522   } else {
14523     if (RHS.getOpcode() != ISD::UNDEF)
14524       C = RHS;
14525     for (unsigned i = 0; i != N; ++i)
14526       RMask[i] = i;
14527   }
14528
14529   // Check that the shuffles are both shuffling the same vectors.
14530   if (!(A == C && B == D) && !(A == D && B == C))
14531     return false;
14532
14533   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
14534   if (!A.getNode() && !B.getNode())
14535     return false;
14536
14537   // If A and B occur in reverse order in RHS, then "swap" them (which means
14538   // rewriting the mask).
14539   if (A != C)
14540     for (unsigned i = 0; i != N; ++i) {
14541       unsigned Idx = RMask[i];
14542       if (Idx < N)
14543         RMask[i] += N;
14544       else if (Idx < 2*N)
14545         RMask[i] -= N;
14546     }
14547
14548   // At this point LHS and RHS are equivalent to
14549   //   LHS = VECTOR_SHUFFLE A, B, LMask
14550   //   RHS = VECTOR_SHUFFLE A, B, RMask
14551   // Check that the masks correspond to performing a horizontal operation.
14552   for (unsigned i = 0; i != N; ++i) {
14553     unsigned LIdx = LMask[i], RIdx = RMask[i];
14554
14555     // Ignore any UNDEF components.
14556     if (LIdx >= 2*N || RIdx >= 2*N || (!A.getNode() && (LIdx < N || RIdx < N))
14557         || (!B.getNode() && (LIdx >= N || RIdx >= N)))
14558       continue;
14559
14560     // Check that successive elements are being operated on.  If not, this is
14561     // not a horizontal operation.
14562     if (!(LIdx == 2*i && RIdx == 2*i + 1) &&
14563         !(isCommutative && LIdx == 2*i + 1 && RIdx == 2*i))
14564       return false;
14565   }
14566
14567   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
14568   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
14569   return true;
14570 }
14571
14572 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
14573 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
14574                                   const X86Subtarget *Subtarget) {
14575   EVT VT = N->getValueType(0);
14576   SDValue LHS = N->getOperand(0);
14577   SDValue RHS = N->getOperand(1);
14578
14579   // Try to synthesize horizontal adds from adds of shuffles.
14580   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14581       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14582       isHorizontalBinOp(LHS, RHS, true))
14583     return DAG.getNode(X86ISD::FHADD, N->getDebugLoc(), VT, LHS, RHS);
14584   return SDValue();
14585 }
14586
14587 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
14588 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
14589                                   const X86Subtarget *Subtarget) {
14590   EVT VT = N->getValueType(0);
14591   SDValue LHS = N->getOperand(0);
14592   SDValue RHS = N->getOperand(1);
14593
14594   // Try to synthesize horizontal subs from subs of shuffles.
14595   if ((Subtarget->hasSSE3() || Subtarget->hasAVX()) &&
14596       (VT == MVT::v4f32 || VT == MVT::v2f64) &&
14597       isHorizontalBinOp(LHS, RHS, false))
14598     return DAG.getNode(X86ISD::FHSUB, N->getDebugLoc(), VT, LHS, RHS);
14599   return SDValue();
14600 }
14601
14602 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
14603 /// X86ISD::FXOR nodes.
14604 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
14605   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
14606   // F[X]OR(0.0, x) -> x
14607   // F[X]OR(x, 0.0) -> x
14608   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14609     if (C->getValueAPF().isPosZero())
14610       return N->getOperand(1);
14611   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14612     if (C->getValueAPF().isPosZero())
14613       return N->getOperand(0);
14614   return SDValue();
14615 }
14616
14617 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
14618 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
14619   // FAND(0.0, x) -> 0.0
14620   // FAND(x, 0.0) -> 0.0
14621   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
14622     if (C->getValueAPF().isPosZero())
14623       return N->getOperand(0);
14624   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
14625     if (C->getValueAPF().isPosZero())
14626       return N->getOperand(1);
14627   return SDValue();
14628 }
14629
14630 static SDValue PerformBTCombine(SDNode *N,
14631                                 SelectionDAG &DAG,
14632                                 TargetLowering::DAGCombinerInfo &DCI) {
14633   // BT ignores high bits in the bit index operand.
14634   SDValue Op1 = N->getOperand(1);
14635   if (Op1.hasOneUse()) {
14636     unsigned BitWidth = Op1.getValueSizeInBits();
14637     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
14638     APInt KnownZero, KnownOne;
14639     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
14640                                           !DCI.isBeforeLegalizeOps());
14641     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14642     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
14643         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
14644       DCI.CommitTargetLoweringOpt(TLO);
14645   }
14646   return SDValue();
14647 }
14648
14649 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
14650   SDValue Op = N->getOperand(0);
14651   if (Op.getOpcode() == ISD::BITCAST)
14652     Op = Op.getOperand(0);
14653   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
14654   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
14655       VT.getVectorElementType().getSizeInBits() ==
14656       OpVT.getVectorElementType().getSizeInBits()) {
14657     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
14658   }
14659   return SDValue();
14660 }
14661
14662 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
14663   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
14664   //           (and (i32 x86isd::setcc_carry), 1)
14665   // This eliminates the zext. This transformation is necessary because
14666   // ISD::SETCC is always legalized to i8.
14667   DebugLoc dl = N->getDebugLoc();
14668   SDValue N0 = N->getOperand(0);
14669   EVT VT = N->getValueType(0);
14670   if (N0.getOpcode() == ISD::AND &&
14671       N0.hasOneUse() &&
14672       N0.getOperand(0).hasOneUse()) {
14673     SDValue N00 = N0.getOperand(0);
14674     if (N00.getOpcode() != X86ISD::SETCC_CARRY)
14675       return SDValue();
14676     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
14677     if (!C || C->getZExtValue() != 1)
14678       return SDValue();
14679     return DAG.getNode(ISD::AND, dl, VT,
14680                        DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
14681                                    N00.getOperand(0), N00.getOperand(1)),
14682                        DAG.getConstant(1, VT));
14683   }
14684
14685   return SDValue();
14686 }
14687
14688 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
14689 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
14690   unsigned X86CC = N->getConstantOperandVal(0);
14691   SDValue EFLAG = N->getOperand(1);
14692   DebugLoc DL = N->getDebugLoc();
14693
14694   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
14695   // a zext and produces an all-ones bit which is more useful than 0/1 in some
14696   // cases.
14697   if (X86CC == X86::COND_B)
14698     return DAG.getNode(ISD::AND, DL, MVT::i8,
14699                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
14700                                    DAG.getConstant(X86CC, MVT::i8), EFLAG),
14701                        DAG.getConstant(1, MVT::i8));
14702
14703   return SDValue();
14704 }
14705
14706 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
14707                                         const X86TargetLowering *XTLI) {
14708   SDValue Op0 = N->getOperand(0);
14709   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
14710   // a 32-bit target where SSE doesn't support i64->FP operations.
14711   if (Op0.getOpcode() == ISD::LOAD) {
14712     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
14713     EVT VT = Ld->getValueType(0);
14714     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
14715         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
14716         !XTLI->getSubtarget()->is64Bit() &&
14717         !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14718       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
14719                                           Ld->getChain(), Op0, DAG);
14720       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
14721       return FILDChain;
14722     }
14723   }
14724   return SDValue();
14725 }
14726
14727 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
14728 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
14729                                  X86TargetLowering::DAGCombinerInfo &DCI) {
14730   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
14731   // the result is either zero or one (depending on the input carry bit).
14732   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
14733   if (X86::isZeroNode(N->getOperand(0)) &&
14734       X86::isZeroNode(N->getOperand(1)) &&
14735       // We don't have a good way to replace an EFLAGS use, so only do this when
14736       // dead right now.
14737       SDValue(N, 1).use_empty()) {
14738     DebugLoc DL = N->getDebugLoc();
14739     EVT VT = N->getValueType(0);
14740     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
14741     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
14742                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
14743                                            DAG.getConstant(X86::COND_B,MVT::i8),
14744                                            N->getOperand(2)),
14745                                DAG.getConstant(1, VT));
14746     return DCI.CombineTo(N, Res1, CarryOut);
14747   }
14748
14749   return SDValue();
14750 }
14751
14752 // fold (add Y, (sete  X, 0)) -> adc  0, Y
14753 //      (add Y, (setne X, 0)) -> sbb -1, Y
14754 //      (sub (sete  X, 0), Y) -> sbb  0, Y
14755 //      (sub (setne X, 0), Y) -> adc -1, Y
14756 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
14757   DebugLoc DL = N->getDebugLoc();
14758
14759   // Look through ZExts.
14760   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
14761   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
14762     return SDValue();
14763
14764   SDValue SetCC = Ext.getOperand(0);
14765   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
14766     return SDValue();
14767
14768   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
14769   if (CC != X86::COND_E && CC != X86::COND_NE)
14770     return SDValue();
14771
14772   SDValue Cmp = SetCC.getOperand(1);
14773   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
14774       !X86::isZeroNode(Cmp.getOperand(1)) ||
14775       !Cmp.getOperand(0).getValueType().isInteger())
14776     return SDValue();
14777
14778   SDValue CmpOp0 = Cmp.getOperand(0);
14779   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
14780                                DAG.getConstant(1, CmpOp0.getValueType()));
14781
14782   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
14783   if (CC == X86::COND_NE)
14784     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
14785                        DL, OtherVal.getValueType(), OtherVal,
14786                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
14787   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
14788                      DL, OtherVal.getValueType(), OtherVal,
14789                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
14790 }
14791
14792 /// PerformADDCombine - Do target-specific dag combines on integer adds.
14793 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
14794                                  const X86Subtarget *Subtarget) {
14795   EVT VT = N->getValueType(0);
14796   SDValue Op0 = N->getOperand(0);
14797   SDValue Op1 = N->getOperand(1);
14798
14799   // Try to synthesize horizontal adds from adds of shuffles.
14800   if ((Subtarget->hasSSSE3() || Subtarget->hasAVX()) &&
14801       (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14802       isHorizontalBinOp(Op0, Op1, true))
14803     return DAG.getNode(X86ISD::HADD, N->getDebugLoc(), VT, Op0, Op1);
14804
14805   return OptimizeConditionalInDecrement(N, DAG);
14806 }
14807
14808 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
14809                                  const X86Subtarget *Subtarget) {
14810   SDValue Op0 = N->getOperand(0);
14811   SDValue Op1 = N->getOperand(1);
14812
14813   // X86 can't encode an immediate LHS of a sub. See if we can push the
14814   // negation into a preceding instruction.
14815   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
14816     // If the RHS of the sub is a XOR with one use and a constant, invert the
14817     // immediate. Then add one to the LHS of the sub so we can turn
14818     // X-Y -> X+~Y+1, saving one register.
14819     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
14820         isa<ConstantSDNode>(Op1.getOperand(1))) {
14821       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
14822       EVT VT = Op0.getValueType();
14823       SDValue NewXor = DAG.getNode(ISD::XOR, Op1.getDebugLoc(), VT,
14824                                    Op1.getOperand(0),
14825                                    DAG.getConstant(~XorC, VT));
14826       return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, NewXor,
14827                          DAG.getConstant(C->getAPIntValue()+1, VT));
14828     }
14829   }
14830
14831   // Try to synthesize horizontal adds from adds of shuffles.
14832   EVT VT = N->getValueType(0);
14833   if ((Subtarget->hasSSSE3() || Subtarget->hasAVX()) &&
14834       (VT == MVT::v8i16 || VT == MVT::v4i32) &&
14835       isHorizontalBinOp(Op0, Op1, false))
14836     return DAG.getNode(X86ISD::HSUB, N->getDebugLoc(), VT, Op0, Op1);
14837
14838   return OptimizeConditionalInDecrement(N, DAG);
14839 }
14840
14841 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
14842                                              DAGCombinerInfo &DCI) const {
14843   SelectionDAG &DAG = DCI.DAG;
14844   switch (N->getOpcode()) {
14845   default: break;
14846   case ISD::EXTRACT_VECTOR_ELT:
14847     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
14848   case ISD::VSELECT:
14849   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, Subtarget);
14850   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI);
14851   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
14852   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
14853   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
14854   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
14855   case ISD::SHL:
14856   case ISD::SRA:
14857   case ISD::SRL:            return PerformShiftCombine(N, DAG, Subtarget);
14858   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
14859   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
14860   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
14861   case ISD::LOAD:           return PerformLOADCombine(N, DAG, Subtarget);
14862   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
14863   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
14864   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
14865   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
14866   case X86ISD::FXOR:
14867   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
14868   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
14869   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
14870   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
14871   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG);
14872   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG);
14873   case X86ISD::SHUFPS:      // Handle all target specific shuffles
14874   case X86ISD::SHUFPD:
14875   case X86ISD::PALIGN:
14876   case X86ISD::PUNPCKHBW:
14877   case X86ISD::PUNPCKHWD:
14878   case X86ISD::PUNPCKHDQ:
14879   case X86ISD::PUNPCKHQDQ:
14880   case X86ISD::VPUNPCKHBWY:
14881   case X86ISD::VPUNPCKHWDY:
14882   case X86ISD::VPUNPCKHDQY:
14883   case X86ISD::VPUNPCKHQDQY:
14884   case X86ISD::UNPCKHPS:
14885   case X86ISD::UNPCKHPD:
14886   case X86ISD::VUNPCKHPSY:
14887   case X86ISD::VUNPCKHPDY:
14888   case X86ISD::PUNPCKLBW:
14889   case X86ISD::PUNPCKLWD:
14890   case X86ISD::PUNPCKLDQ:
14891   case X86ISD::PUNPCKLQDQ:
14892   case X86ISD::VPUNPCKLBWY:
14893   case X86ISD::VPUNPCKLWDY:
14894   case X86ISD::VPUNPCKLDQY:
14895   case X86ISD::VPUNPCKLQDQY:
14896   case X86ISD::UNPCKLPS:
14897   case X86ISD::UNPCKLPD:
14898   case X86ISD::VUNPCKLPSY:
14899   case X86ISD::VUNPCKLPDY:
14900   case X86ISD::MOVHLPS:
14901   case X86ISD::MOVLHPS:
14902   case X86ISD::PSHUFD:
14903   case X86ISD::PSHUFHW:
14904   case X86ISD::PSHUFLW:
14905   case X86ISD::MOVSS:
14906   case X86ISD::MOVSD:
14907   case X86ISD::VPERMILPS:
14908   case X86ISD::VPERMILPSY:
14909   case X86ISD::VPERMILPD:
14910   case X86ISD::VPERMILPDY:
14911   case X86ISD::VPERM2F128:
14912   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
14913   }
14914
14915   return SDValue();
14916 }
14917
14918 /// isTypeDesirableForOp - Return true if the target has native support for
14919 /// the specified value type and it is 'desirable' to use the type for the
14920 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
14921 /// instruction encodings are longer and some i16 instructions are slow.
14922 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
14923   if (!isTypeLegal(VT))
14924     return false;
14925   if (VT != MVT::i16)
14926     return true;
14927
14928   switch (Opc) {
14929   default:
14930     return true;
14931   case ISD::LOAD:
14932   case ISD::SIGN_EXTEND:
14933   case ISD::ZERO_EXTEND:
14934   case ISD::ANY_EXTEND:
14935   case ISD::SHL:
14936   case ISD::SRL:
14937   case ISD::SUB:
14938   case ISD::ADD:
14939   case ISD::MUL:
14940   case ISD::AND:
14941   case ISD::OR:
14942   case ISD::XOR:
14943     return false;
14944   }
14945 }
14946
14947 /// IsDesirableToPromoteOp - This method query the target whether it is
14948 /// beneficial for dag combiner to promote the specified node. If true, it
14949 /// should return the desired promotion type by reference.
14950 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
14951   EVT VT = Op.getValueType();
14952   if (VT != MVT::i16)
14953     return false;
14954
14955   bool Promote = false;
14956   bool Commute = false;
14957   switch (Op.getOpcode()) {
14958   default: break;
14959   case ISD::LOAD: {
14960     LoadSDNode *LD = cast<LoadSDNode>(Op);
14961     // If the non-extending load has a single use and it's not live out, then it
14962     // might be folded.
14963     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
14964                                                      Op.hasOneUse()*/) {
14965       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
14966              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
14967         // The only case where we'd want to promote LOAD (rather then it being
14968         // promoted as an operand is when it's only use is liveout.
14969         if (UI->getOpcode() != ISD::CopyToReg)
14970           return false;
14971       }
14972     }
14973     Promote = true;
14974     break;
14975   }
14976   case ISD::SIGN_EXTEND:
14977   case ISD::ZERO_EXTEND:
14978   case ISD::ANY_EXTEND:
14979     Promote = true;
14980     break;
14981   case ISD::SHL:
14982   case ISD::SRL: {
14983     SDValue N0 = Op.getOperand(0);
14984     // Look out for (store (shl (load), x)).
14985     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
14986       return false;
14987     Promote = true;
14988     break;
14989   }
14990   case ISD::ADD:
14991   case ISD::MUL:
14992   case ISD::AND:
14993   case ISD::OR:
14994   case ISD::XOR:
14995     Commute = true;
14996     // fallthrough
14997   case ISD::SUB: {
14998     SDValue N0 = Op.getOperand(0);
14999     SDValue N1 = Op.getOperand(1);
15000     if (!Commute && MayFoldLoad(N1))
15001       return false;
15002     // Avoid disabling potential load folding opportunities.
15003     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
15004       return false;
15005     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
15006       return false;
15007     Promote = true;
15008   }
15009   }
15010
15011   PVT = MVT::i32;
15012   return Promote;
15013 }
15014
15015 //===----------------------------------------------------------------------===//
15016 //                           X86 Inline Assembly Support
15017 //===----------------------------------------------------------------------===//
15018
15019 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
15020   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15021
15022   std::string AsmStr = IA->getAsmString();
15023
15024   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
15025   SmallVector<StringRef, 4> AsmPieces;
15026   SplitString(AsmStr, AsmPieces, ";\n");
15027
15028   switch (AsmPieces.size()) {
15029   default: return false;
15030   case 1:
15031     AsmStr = AsmPieces[0];
15032     AsmPieces.clear();
15033     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
15034
15035     // FIXME: this should verify that we are targeting a 486 or better.  If not,
15036     // we will turn this bswap into something that will be lowered to logical ops
15037     // instead of emitting the bswap asm.  For now, we don't support 486 or lower
15038     // so don't worry about this.
15039     // bswap $0
15040     if (AsmPieces.size() == 2 &&
15041         (AsmPieces[0] == "bswap" ||
15042          AsmPieces[0] == "bswapq" ||
15043          AsmPieces[0] == "bswapl") &&
15044         (AsmPieces[1] == "$0" ||
15045          AsmPieces[1] == "${0:q}")) {
15046       // No need to check constraints, nothing other than the equivalent of
15047       // "=r,0" would be valid here.
15048       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15049       if (!Ty || Ty->getBitWidth() % 16 != 0)
15050         return false;
15051       return IntrinsicLowering::LowerToByteSwap(CI);
15052     }
15053     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
15054     if (CI->getType()->isIntegerTy(16) &&
15055         AsmPieces.size() == 3 &&
15056         (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
15057         AsmPieces[1] == "$$8," &&
15058         AsmPieces[2] == "${0:w}" &&
15059         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15060       AsmPieces.clear();
15061       const std::string &ConstraintsStr = IA->getConstraintString();
15062       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15063       std::sort(AsmPieces.begin(), AsmPieces.end());
15064       if (AsmPieces.size() == 4 &&
15065           AsmPieces[0] == "~{cc}" &&
15066           AsmPieces[1] == "~{dirflag}" &&
15067           AsmPieces[2] == "~{flags}" &&
15068           AsmPieces[3] == "~{fpsr}") {
15069         IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15070         if (!Ty || Ty->getBitWidth() % 16 != 0)
15071           return false;
15072         return IntrinsicLowering::LowerToByteSwap(CI);
15073       }
15074     }
15075     break;
15076   case 3:
15077     if (CI->getType()->isIntegerTy(32) &&
15078         IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
15079       SmallVector<StringRef, 4> Words;
15080       SplitString(AsmPieces[0], Words, " \t,");
15081       if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15082           Words[2] == "${0:w}") {
15083         Words.clear();
15084         SplitString(AsmPieces[1], Words, " \t,");
15085         if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
15086             Words[2] == "$0") {
15087           Words.clear();
15088           SplitString(AsmPieces[2], Words, " \t,");
15089           if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
15090               Words[2] == "${0:w}") {
15091             AsmPieces.clear();
15092             const std::string &ConstraintsStr = IA->getConstraintString();
15093             SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
15094             std::sort(AsmPieces.begin(), AsmPieces.end());
15095             if (AsmPieces.size() == 4 &&
15096                 AsmPieces[0] == "~{cc}" &&
15097                 AsmPieces[1] == "~{dirflag}" &&
15098                 AsmPieces[2] == "~{flags}" &&
15099                 AsmPieces[3] == "~{fpsr}") {
15100               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15101               if (!Ty || Ty->getBitWidth() % 16 != 0)
15102                 return false;
15103               return IntrinsicLowering::LowerToByteSwap(CI);
15104             }
15105           }
15106         }
15107       }
15108     }
15109
15110     if (CI->getType()->isIntegerTy(64)) {
15111       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
15112       if (Constraints.size() >= 2 &&
15113           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
15114           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
15115         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
15116         SmallVector<StringRef, 4> Words;
15117         SplitString(AsmPieces[0], Words, " \t");
15118         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
15119           Words.clear();
15120           SplitString(AsmPieces[1], Words, " \t");
15121           if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
15122             Words.clear();
15123             SplitString(AsmPieces[2], Words, " \t,");
15124             if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
15125                 Words[2] == "%edx") {
15126               IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15127               if (!Ty || Ty->getBitWidth() % 16 != 0)
15128                 return false;
15129               return IntrinsicLowering::LowerToByteSwap(CI);
15130             }
15131           }
15132         }
15133       }
15134     }
15135     break;
15136   }
15137   return false;
15138 }
15139
15140
15141
15142 /// getConstraintType - Given a constraint letter, return the type of
15143 /// constraint it is for this target.
15144 X86TargetLowering::ConstraintType
15145 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
15146   if (Constraint.size() == 1) {
15147     switch (Constraint[0]) {
15148     case 'R':
15149     case 'q':
15150     case 'Q':
15151     case 'f':
15152     case 't':
15153     case 'u':
15154     case 'y':
15155     case 'x':
15156     case 'Y':
15157     case 'l':
15158       return C_RegisterClass;
15159     case 'a':
15160     case 'b':
15161     case 'c':
15162     case 'd':
15163     case 'S':
15164     case 'D':
15165     case 'A':
15166       return C_Register;
15167     case 'I':
15168     case 'J':
15169     case 'K':
15170     case 'L':
15171     case 'M':
15172     case 'N':
15173     case 'G':
15174     case 'C':
15175     case 'e':
15176     case 'Z':
15177       return C_Other;
15178     default:
15179       break;
15180     }
15181   }
15182   return TargetLowering::getConstraintType(Constraint);
15183 }
15184
15185 /// Examine constraint type and operand type and determine a weight value.
15186 /// This object must already have been set up with the operand type
15187 /// and the current alternative constraint selected.
15188 TargetLowering::ConstraintWeight
15189   X86TargetLowering::getSingleConstraintMatchWeight(
15190     AsmOperandInfo &info, const char *constraint) const {
15191   ConstraintWeight weight = CW_Invalid;
15192   Value *CallOperandVal = info.CallOperandVal;
15193     // If we don't have a value, we can't do a match,
15194     // but allow it at the lowest weight.
15195   if (CallOperandVal == NULL)
15196     return CW_Default;
15197   Type *type = CallOperandVal->getType();
15198   // Look at the constraint type.
15199   switch (*constraint) {
15200   default:
15201     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15202   case 'R':
15203   case 'q':
15204   case 'Q':
15205   case 'a':
15206   case 'b':
15207   case 'c':
15208   case 'd':
15209   case 'S':
15210   case 'D':
15211   case 'A':
15212     if (CallOperandVal->getType()->isIntegerTy())
15213       weight = CW_SpecificReg;
15214     break;
15215   case 'f':
15216   case 't':
15217   case 'u':
15218       if (type->isFloatingPointTy())
15219         weight = CW_SpecificReg;
15220       break;
15221   case 'y':
15222       if (type->isX86_MMXTy() && Subtarget->hasMMX())
15223         weight = CW_SpecificReg;
15224       break;
15225   case 'x':
15226   case 'Y':
15227     if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
15228       weight = CW_Register;
15229     break;
15230   case 'I':
15231     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
15232       if (C->getZExtValue() <= 31)
15233         weight = CW_Constant;
15234     }
15235     break;
15236   case 'J':
15237     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15238       if (C->getZExtValue() <= 63)
15239         weight = CW_Constant;
15240     }
15241     break;
15242   case 'K':
15243     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15244       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
15245         weight = CW_Constant;
15246     }
15247     break;
15248   case 'L':
15249     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15250       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
15251         weight = CW_Constant;
15252     }
15253     break;
15254   case 'M':
15255     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15256       if (C->getZExtValue() <= 3)
15257         weight = CW_Constant;
15258     }
15259     break;
15260   case 'N':
15261     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15262       if (C->getZExtValue() <= 0xff)
15263         weight = CW_Constant;
15264     }
15265     break;
15266   case 'G':
15267   case 'C':
15268     if (dyn_cast<ConstantFP>(CallOperandVal)) {
15269       weight = CW_Constant;
15270     }
15271     break;
15272   case 'e':
15273     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15274       if ((C->getSExtValue() >= -0x80000000LL) &&
15275           (C->getSExtValue() <= 0x7fffffffLL))
15276         weight = CW_Constant;
15277     }
15278     break;
15279   case 'Z':
15280     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
15281       if (C->getZExtValue() <= 0xffffffff)
15282         weight = CW_Constant;
15283     }
15284     break;
15285   }
15286   return weight;
15287 }
15288
15289 /// LowerXConstraint - try to replace an X constraint, which matches anything,
15290 /// with another that has more specific requirements based on the type of the
15291 /// corresponding operand.
15292 const char *X86TargetLowering::
15293 LowerXConstraint(EVT ConstraintVT) const {
15294   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
15295   // 'f' like normal targets.
15296   if (ConstraintVT.isFloatingPoint()) {
15297     if (Subtarget->hasXMMInt())
15298       return "Y";
15299     if (Subtarget->hasXMM())
15300       return "x";
15301   }
15302
15303   return TargetLowering::LowerXConstraint(ConstraintVT);
15304 }
15305
15306 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15307 /// vector.  If it is invalid, don't add anything to Ops.
15308 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15309                                                      std::string &Constraint,
15310                                                      std::vector<SDValue>&Ops,
15311                                                      SelectionDAG &DAG) const {
15312   SDValue Result(0, 0);
15313
15314   // Only support length 1 constraints for now.
15315   if (Constraint.length() > 1) return;
15316
15317   char ConstraintLetter = Constraint[0];
15318   switch (ConstraintLetter) {
15319   default: break;
15320   case 'I':
15321     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15322       if (C->getZExtValue() <= 31) {
15323         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15324         break;
15325       }
15326     }
15327     return;
15328   case 'J':
15329     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15330       if (C->getZExtValue() <= 63) {
15331         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15332         break;
15333       }
15334     }
15335     return;
15336   case 'K':
15337     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15338       if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
15339         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15340         break;
15341       }
15342     }
15343     return;
15344   case 'N':
15345     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15346       if (C->getZExtValue() <= 255) {
15347         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15348         break;
15349       }
15350     }
15351     return;
15352   case 'e': {
15353     // 32-bit signed value
15354     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15355       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15356                                            C->getSExtValue())) {
15357         // Widen to 64 bits here to get it sign extended.
15358         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
15359         break;
15360       }
15361     // FIXME gcc accepts some relocatable values here too, but only in certain
15362     // memory models; it's complicated.
15363     }
15364     return;
15365   }
15366   case 'Z': {
15367     // 32-bit unsigned value
15368     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
15369       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
15370                                            C->getZExtValue())) {
15371         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
15372         break;
15373       }
15374     }
15375     // FIXME gcc accepts some relocatable values here too, but only in certain
15376     // memory models; it's complicated.
15377     return;
15378   }
15379   case 'i': {
15380     // Literal immediates are always ok.
15381     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
15382       // Widen to 64 bits here to get it sign extended.
15383       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
15384       break;
15385     }
15386
15387     // In any sort of PIC mode addresses need to be computed at runtime by
15388     // adding in a register or some sort of table lookup.  These can't
15389     // be used as immediates.
15390     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
15391       return;
15392
15393     // If we are in non-pic codegen mode, we allow the address of a global (with
15394     // an optional displacement) to be used with 'i'.
15395     GlobalAddressSDNode *GA = 0;
15396     int64_t Offset = 0;
15397
15398     // Match either (GA), (GA+C), (GA+C1+C2), etc.
15399     while (1) {
15400       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
15401         Offset += GA->getOffset();
15402         break;
15403       } else if (Op.getOpcode() == ISD::ADD) {
15404         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15405           Offset += C->getZExtValue();
15406           Op = Op.getOperand(0);
15407           continue;
15408         }
15409       } else if (Op.getOpcode() == ISD::SUB) {
15410         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
15411           Offset += -C->getZExtValue();
15412           Op = Op.getOperand(0);
15413           continue;
15414         }
15415       }
15416
15417       // Otherwise, this isn't something we can handle, reject it.
15418       return;
15419     }
15420
15421     const GlobalValue *GV = GA->getGlobal();
15422     // If we require an extra load to get this address, as in PIC mode, we
15423     // can't accept it.
15424     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
15425                                                         getTargetMachine())))
15426       return;
15427
15428     Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
15429                                         GA->getValueType(0), Offset);
15430     break;
15431   }
15432   }
15433
15434   if (Result.getNode()) {
15435     Ops.push_back(Result);
15436     return;
15437   }
15438   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15439 }
15440
15441 std::pair<unsigned, const TargetRegisterClass*>
15442 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
15443                                                 EVT VT) const {
15444   // First, see if this is a constraint that directly corresponds to an LLVM
15445   // register class.
15446   if (Constraint.size() == 1) {
15447     // GCC Constraint Letters
15448     switch (Constraint[0]) {
15449     default: break;
15450       // TODO: Slight differences here in allocation order and leaving
15451       // RIP in the class. Do they matter any more here than they do
15452       // in the normal allocation?
15453     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
15454       if (Subtarget->is64Bit()) {
15455         if (VT == MVT::i32 || VT == MVT::f32)
15456           return std::make_pair(0U, X86::GR32RegisterClass);
15457         else if (VT == MVT::i16)
15458           return std::make_pair(0U, X86::GR16RegisterClass);
15459         else if (VT == MVT::i8 || VT == MVT::i1)
15460           return std::make_pair(0U, X86::GR8RegisterClass);
15461         else if (VT == MVT::i64 || VT == MVT::f64)
15462           return std::make_pair(0U, X86::GR64RegisterClass);
15463         break;
15464       }
15465       // 32-bit fallthrough
15466     case 'Q':   // Q_REGS
15467       if (VT == MVT::i32 || VT == MVT::f32)
15468         return std::make_pair(0U, X86::GR32_ABCDRegisterClass);
15469       else if (VT == MVT::i16)
15470         return std::make_pair(0U, X86::GR16_ABCDRegisterClass);
15471       else if (VT == MVT::i8 || VT == MVT::i1)
15472         return std::make_pair(0U, X86::GR8_ABCD_LRegisterClass);
15473       else if (VT == MVT::i64)
15474         return std::make_pair(0U, X86::GR64_ABCDRegisterClass);
15475       break;
15476     case 'r':   // GENERAL_REGS
15477     case 'l':   // INDEX_REGS
15478       if (VT == MVT::i8 || VT == MVT::i1)
15479         return std::make_pair(0U, X86::GR8RegisterClass);
15480       if (VT == MVT::i16)
15481         return std::make_pair(0U, X86::GR16RegisterClass);
15482       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
15483         return std::make_pair(0U, X86::GR32RegisterClass);
15484       return std::make_pair(0U, X86::GR64RegisterClass);
15485     case 'R':   // LEGACY_REGS
15486       if (VT == MVT::i8 || VT == MVT::i1)
15487         return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
15488       if (VT == MVT::i16)
15489         return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
15490       if (VT == MVT::i32 || !Subtarget->is64Bit())
15491         return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
15492       return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
15493     case 'f':  // FP Stack registers.
15494       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
15495       // value to the correct fpstack register class.
15496       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
15497         return std::make_pair(0U, X86::RFP32RegisterClass);
15498       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
15499         return std::make_pair(0U, X86::RFP64RegisterClass);
15500       return std::make_pair(0U, X86::RFP80RegisterClass);
15501     case 'y':   // MMX_REGS if MMX allowed.
15502       if (!Subtarget->hasMMX()) break;
15503       return std::make_pair(0U, X86::VR64RegisterClass);
15504     case 'Y':   // SSE_REGS if SSE2 allowed
15505       if (!Subtarget->hasXMMInt()) break;
15506       // FALL THROUGH.
15507     case 'x':   // SSE_REGS if SSE1 allowed
15508       if (!Subtarget->hasXMM()) break;
15509
15510       switch (VT.getSimpleVT().SimpleTy) {
15511       default: break;
15512       // Scalar SSE types.
15513       case MVT::f32:
15514       case MVT::i32:
15515         return std::make_pair(0U, X86::FR32RegisterClass);
15516       case MVT::f64:
15517       case MVT::i64:
15518         return std::make_pair(0U, X86::FR64RegisterClass);
15519       // Vector types.
15520       case MVT::v16i8:
15521       case MVT::v8i16:
15522       case MVT::v4i32:
15523       case MVT::v2i64:
15524       case MVT::v4f32:
15525       case MVT::v2f64:
15526         return std::make_pair(0U, X86::VR128RegisterClass);
15527       }
15528       break;
15529     }
15530   }
15531
15532   // Use the default implementation in TargetLowering to convert the register
15533   // constraint into a member of a register class.
15534   std::pair<unsigned, const TargetRegisterClass*> Res;
15535   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
15536
15537   // Not found as a standard register?
15538   if (Res.second == 0) {
15539     // Map st(0) -> st(7) -> ST0
15540     if (Constraint.size() == 7 && Constraint[0] == '{' &&
15541         tolower(Constraint[1]) == 's' &&
15542         tolower(Constraint[2]) == 't' &&
15543         Constraint[3] == '(' &&
15544         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
15545         Constraint[5] == ')' &&
15546         Constraint[6] == '}') {
15547
15548       Res.first = X86::ST0+Constraint[4]-'0';
15549       Res.second = X86::RFP80RegisterClass;
15550       return Res;
15551     }
15552
15553     // GCC allows "st(0)" to be called just plain "st".
15554     if (StringRef("{st}").equals_lower(Constraint)) {
15555       Res.first = X86::ST0;
15556       Res.second = X86::RFP80RegisterClass;
15557       return Res;
15558     }
15559
15560     // flags -> EFLAGS
15561     if (StringRef("{flags}").equals_lower(Constraint)) {
15562       Res.first = X86::EFLAGS;
15563       Res.second = X86::CCRRegisterClass;
15564       return Res;
15565     }
15566
15567     // 'A' means EAX + EDX.
15568     if (Constraint == "A") {
15569       Res.first = X86::EAX;
15570       Res.second = X86::GR32_ADRegisterClass;
15571       return Res;
15572     }
15573     return Res;
15574   }
15575
15576   // Otherwise, check to see if this is a register class of the wrong value
15577   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
15578   // turn into {ax},{dx}.
15579   if (Res.second->hasType(VT))
15580     return Res;   // Correct type already, nothing to do.
15581
15582   // All of the single-register GCC register classes map their values onto
15583   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
15584   // really want an 8-bit or 32-bit register, map to the appropriate register
15585   // class and return the appropriate register.
15586   if (Res.second == X86::GR16RegisterClass) {
15587     if (VT == MVT::i8) {
15588       unsigned DestReg = 0;
15589       switch (Res.first) {
15590       default: break;
15591       case X86::AX: DestReg = X86::AL; break;
15592       case X86::DX: DestReg = X86::DL; break;
15593       case X86::CX: DestReg = X86::CL; break;
15594       case X86::BX: DestReg = X86::BL; break;
15595       }
15596       if (DestReg) {
15597         Res.first = DestReg;
15598         Res.second = X86::GR8RegisterClass;
15599       }
15600     } else if (VT == MVT::i32) {
15601       unsigned DestReg = 0;
15602       switch (Res.first) {
15603       default: break;
15604       case X86::AX: DestReg = X86::EAX; break;
15605       case X86::DX: DestReg = X86::EDX; break;
15606       case X86::CX: DestReg = X86::ECX; break;
15607       case X86::BX: DestReg = X86::EBX; break;
15608       case X86::SI: DestReg = X86::ESI; break;
15609       case X86::DI: DestReg = X86::EDI; break;
15610       case X86::BP: DestReg = X86::EBP; break;
15611       case X86::SP: DestReg = X86::ESP; break;
15612       }
15613       if (DestReg) {
15614         Res.first = DestReg;
15615         Res.second = X86::GR32RegisterClass;
15616       }
15617     } else if (VT == MVT::i64) {
15618       unsigned DestReg = 0;
15619       switch (Res.first) {
15620       default: break;
15621       case X86::AX: DestReg = X86::RAX; break;
15622       case X86::DX: DestReg = X86::RDX; break;
15623       case X86::CX: DestReg = X86::RCX; break;
15624       case X86::BX: DestReg = X86::RBX; break;
15625       case X86::SI: DestReg = X86::RSI; break;
15626       case X86::DI: DestReg = X86::RDI; break;
15627       case X86::BP: DestReg = X86::RBP; break;
15628       case X86::SP: DestReg = X86::RSP; break;
15629       }
15630       if (DestReg) {
15631         Res.first = DestReg;
15632         Res.second = X86::GR64RegisterClass;
15633       }
15634     }
15635   } else if (Res.second == X86::FR32RegisterClass ||
15636              Res.second == X86::FR64RegisterClass ||
15637              Res.second == X86::VR128RegisterClass) {
15638     // Handle references to XMM physical registers that got mapped into the
15639     // wrong class.  This can happen with constraints like {xmm0} where the
15640     // target independent register mapper will just pick the first match it can
15641     // find, ignoring the required type.
15642     if (VT == MVT::f32)
15643       Res.second = X86::FR32RegisterClass;
15644     else if (VT == MVT::f64)
15645       Res.second = X86::FR64RegisterClass;
15646     else if (X86::VR128RegisterClass->hasType(VT))
15647       Res.second = X86::VR128RegisterClass;
15648   }
15649
15650   return Res;
15651 }